You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4313 lines
167KB

  1. /*
  2. * H.26L/H.264/AVC/JVT/14496-10/... decoder
  3. * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /**
  22. * @file
  23. * H.264 / AVC / MPEG4 part10 codec.
  24. * @author Michael Niedermayer <michaelni@gmx.at>
  25. */
  26. #define UNCHECKED_BITSTREAM_READER 1
  27. #include "libavutil/imgutils.h"
  28. #include "libavutil/opt.h"
  29. #include "internal.h"
  30. #include "cabac.h"
  31. #include "cabac_functions.h"
  32. #include "dsputil.h"
  33. #include "avcodec.h"
  34. #include "mpegvideo.h"
  35. #include "h264.h"
  36. #include "h264data.h"
  37. #include "h264_mvpred.h"
  38. #include "golomb.h"
  39. #include "mathops.h"
  40. #include "rectangle.h"
  41. #include "thread.h"
  42. #include "vdpau_internal.h"
  43. #include "libavutil/avassert.h"
  44. // #undef NDEBUG
  45. #include <assert.h>
  46. const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
  47. static const uint8_t rem6[QP_MAX_NUM + 1] = {
  48. 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
  49. 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
  50. 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
  51. 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
  52. 0, 1, 2, 3,
  53. };
  54. static const uint8_t div6[QP_MAX_NUM + 1] = {
  55. 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3,
  56. 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6,
  57. 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10,
  58. 10,10,10,11,11,11,11,11,11,12,12,12,12,12,12,13,13,13, 13, 13, 13,
  59. 14,14,14,14,
  60. };
  61. static const enum AVPixelFormat hwaccel_pixfmt_list_h264_jpeg_420[] = {
  62. AV_PIX_FMT_DXVA2_VLD,
  63. AV_PIX_FMT_VAAPI_VLD,
  64. AV_PIX_FMT_VDA_VLD,
  65. AV_PIX_FMT_YUVJ420P,
  66. AV_PIX_FMT_NONE
  67. };
  68. int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx)
  69. {
  70. H264Context *h = avctx->priv_data;
  71. return h ? h->sps.num_reorder_frames : 0;
  72. }
  73. /**
  74. * Check if the top & left blocks are available if needed and
  75. * change the dc mode so it only uses the available blocks.
  76. */
  77. int ff_h264_check_intra4x4_pred_mode(H264Context *h)
  78. {
  79. MpegEncContext *const s = &h->s;
  80. static const int8_t top[12] = {
  81. -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
  82. };
  83. static const int8_t left[12] = {
  84. 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
  85. };
  86. int i;
  87. if (!(h->top_samples_available & 0x8000)) {
  88. for (i = 0; i < 4; i++) {
  89. int status = top[h->intra4x4_pred_mode_cache[scan8[0] + i]];
  90. if (status < 0) {
  91. av_log(h->s.avctx, AV_LOG_ERROR,
  92. "top block unavailable for requested intra4x4 mode %d at %d %d\n",
  93. status, s->mb_x, s->mb_y);
  94. return -1;
  95. } else if (status) {
  96. h->intra4x4_pred_mode_cache[scan8[0] + i] = status;
  97. }
  98. }
  99. }
  100. if ((h->left_samples_available & 0x8888) != 0x8888) {
  101. static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
  102. for (i = 0; i < 4; i++)
  103. if (!(h->left_samples_available & mask[i])) {
  104. int status = left[h->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
  105. if (status < 0) {
  106. av_log(h->s.avctx, AV_LOG_ERROR,
  107. "left block unavailable for requested intra4x4 mode %d at %d %d\n",
  108. status, s->mb_x, s->mb_y);
  109. return -1;
  110. } else if (status) {
  111. h->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
  112. }
  113. }
  114. }
  115. return 0;
  116. } // FIXME cleanup like ff_h264_check_intra_pred_mode
  117. /**
  118. * Check if the top & left blocks are available if needed and
  119. * change the dc mode so it only uses the available blocks.
  120. */
  121. int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)
  122. {
  123. MpegEncContext *const s = &h->s;
  124. static const int8_t top[7] = { LEFT_DC_PRED8x8, 1, -1, -1 };
  125. static const int8_t left[7] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
  126. if (mode > 6U) {
  127. av_log(h->s.avctx, AV_LOG_ERROR,
  128. "out of range intra chroma pred mode at %d %d\n",
  129. s->mb_x, s->mb_y);
  130. return -1;
  131. }
  132. if (!(h->top_samples_available & 0x8000)) {
  133. mode = top[mode];
  134. if (mode < 0) {
  135. av_log(h->s.avctx, AV_LOG_ERROR,
  136. "top block unavailable for requested intra mode at %d %d\n",
  137. s->mb_x, s->mb_y);
  138. return -1;
  139. }
  140. }
  141. if ((h->left_samples_available & 0x8080) != 0x8080) {
  142. mode = left[mode];
  143. if (is_chroma && (h->left_samples_available & 0x8080)) {
  144. // mad cow disease mode, aka MBAFF + constrained_intra_pred
  145. mode = ALZHEIMER_DC_L0T_PRED8x8 +
  146. (!(h->left_samples_available & 0x8000)) +
  147. 2 * (mode == DC_128_PRED8x8);
  148. }
  149. if (mode < 0) {
  150. av_log(h->s.avctx, AV_LOG_ERROR,
  151. "left block unavailable for requested intra mode at %d %d\n",
  152. s->mb_x, s->mb_y);
  153. return -1;
  154. }
  155. }
  156. return mode;
  157. }
  158. const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
  159. int *dst_length, int *consumed, int length)
  160. {
  161. int i, si, di;
  162. uint8_t *dst;
  163. int bufidx;
  164. // src[0]&0x80; // forbidden bit
  165. h->nal_ref_idc = src[0] >> 5;
  166. h->nal_unit_type = src[0] & 0x1F;
  167. src++;
  168. length--;
  169. #define STARTCODE_TEST \
  170. if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
  171. if (src[i + 2] != 3) { \
  172. /* startcode, so we must be past the end */ \
  173. length = i; \
  174. } \
  175. break; \
  176. }
  177. #if HAVE_FAST_UNALIGNED
  178. #define FIND_FIRST_ZERO \
  179. if (i > 0 && !src[i]) \
  180. i--; \
  181. while (src[i]) \
  182. i++
  183. #if HAVE_FAST_64BIT
  184. for (i = 0; i + 1 < length; i += 9) {
  185. if (!((~AV_RN64A(src + i) &
  186. (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
  187. 0x8000800080008080ULL))
  188. continue;
  189. FIND_FIRST_ZERO;
  190. STARTCODE_TEST;
  191. i -= 7;
  192. }
  193. #else
  194. for (i = 0; i + 1 < length; i += 5) {
  195. if (!((~AV_RN32A(src + i) &
  196. (AV_RN32A(src + i) - 0x01000101U)) &
  197. 0x80008080U))
  198. continue;
  199. FIND_FIRST_ZERO;
  200. STARTCODE_TEST;
  201. i -= 3;
  202. }
  203. #endif
  204. #else
  205. for (i = 0; i + 1 < length; i += 2) {
  206. if (src[i])
  207. continue;
  208. if (i > 0 && src[i - 1] == 0)
  209. i--;
  210. STARTCODE_TEST;
  211. }
  212. #endif
  213. // use second escape buffer for inter data
  214. bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
  215. si = h->rbsp_buffer_size[bufidx];
  216. av_fast_padded_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx], length+MAX_MBPAIR_SIZE);
  217. dst = h->rbsp_buffer[bufidx];
  218. if (dst == NULL)
  219. return NULL;
  220. if(i>=length-1){ //no escaped 0
  221. *dst_length= length;
  222. *consumed= length+1; //+1 for the header
  223. if(h->s.avctx->flags2 & CODEC_FLAG2_FAST){
  224. return src;
  225. }else{
  226. memcpy(dst, src, length);
  227. return dst;
  228. }
  229. }
  230. memcpy(dst, src, i);
  231. si = di = i;
  232. while (si + 2 < length) {
  233. // remove escapes (very rare 1:2^22)
  234. if (src[si + 2] > 3) {
  235. dst[di++] = src[si++];
  236. dst[di++] = src[si++];
  237. } else if (src[si] == 0 && src[si + 1] == 0) {
  238. if (src[si + 2] == 3) { // escape
  239. dst[di++] = 0;
  240. dst[di++] = 0;
  241. si += 3;
  242. continue;
  243. } else // next start code
  244. goto nsc;
  245. }
  246. dst[di++] = src[si++];
  247. }
  248. while (si < length)
  249. dst[di++] = src[si++];
  250. nsc:
  251. memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  252. *dst_length = di;
  253. *consumed = si + 1; // +1 for the header
  254. /* FIXME store exact number of bits in the getbitcontext
  255. * (it is needed for decoding) */
  256. return dst;
  257. }
  258. /**
  259. * Identify the exact end of the bitstream
  260. * @return the length of the trailing, or 0 if damaged
  261. */
  262. static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
  263. {
  264. int v = *src;
  265. int r;
  266. tprintf(h->s.avctx, "rbsp trailing %X\n", v);
  267. for (r = 1; r < 9; r++) {
  268. if (v & 1)
  269. return r;
  270. v >>= 1;
  271. }
  272. return 0;
  273. }
  274. static inline int get_lowest_part_list_y(H264Context *h, Picture *pic, int n,
  275. int height, int y_offset, int list)
  276. {
  277. int raw_my = h->mv_cache[list][scan8[n]][1];
  278. int filter_height = (raw_my & 3) ? 2 : 0;
  279. int full_my = (raw_my >> 2) + y_offset;
  280. int top = full_my - filter_height;
  281. int bottom = full_my + filter_height + height;
  282. return FFMAX(abs(top), bottom);
  283. }
  284. static inline void get_lowest_part_y(H264Context *h, int refs[2][48], int n,
  285. int height, int y_offset, int list0,
  286. int list1, int *nrefs)
  287. {
  288. MpegEncContext *const s = &h->s;
  289. int my;
  290. y_offset += 16 * (s->mb_y >> MB_FIELD);
  291. if (list0) {
  292. int ref_n = h->ref_cache[0][scan8[n]];
  293. Picture *ref = &h->ref_list[0][ref_n];
  294. // Error resilience puts the current picture in the ref list.
  295. // Don't try to wait on these as it will cause a deadlock.
  296. // Fields can wait on each other, though.
  297. if (ref->f.thread_opaque != s->current_picture.f.thread_opaque ||
  298. (ref->f.reference & 3) != s->picture_structure) {
  299. my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
  300. if (refs[0][ref_n] < 0)
  301. nrefs[0] += 1;
  302. refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
  303. }
  304. }
  305. if (list1) {
  306. int ref_n = h->ref_cache[1][scan8[n]];
  307. Picture *ref = &h->ref_list[1][ref_n];
  308. if (ref->f.thread_opaque != s->current_picture.f.thread_opaque ||
  309. (ref->f.reference & 3) != s->picture_structure) {
  310. my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
  311. if (refs[1][ref_n] < 0)
  312. nrefs[1] += 1;
  313. refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
  314. }
  315. }
  316. }
  317. /**
  318. * Wait until all reference frames are available for MC operations.
  319. *
  320. * @param h the H264 context
  321. */
  322. static void await_references(H264Context *h)
  323. {
  324. MpegEncContext *const s = &h->s;
  325. const int mb_xy = h->mb_xy;
  326. const int mb_type = s->current_picture.f.mb_type[mb_xy];
  327. int refs[2][48];
  328. int nrefs[2] = { 0 };
  329. int ref, list;
  330. memset(refs, -1, sizeof(refs));
  331. if (IS_16X16(mb_type)) {
  332. get_lowest_part_y(h, refs, 0, 16, 0,
  333. IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
  334. } else if (IS_16X8(mb_type)) {
  335. get_lowest_part_y(h, refs, 0, 8, 0,
  336. IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
  337. get_lowest_part_y(h, refs, 8, 8, 8,
  338. IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
  339. } else if (IS_8X16(mb_type)) {
  340. get_lowest_part_y(h, refs, 0, 16, 0,
  341. IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
  342. get_lowest_part_y(h, refs, 4, 16, 0,
  343. IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
  344. } else {
  345. int i;
  346. av_assert2(IS_8X8(mb_type));
  347. for (i = 0; i < 4; i++) {
  348. const int sub_mb_type = h->sub_mb_type[i];
  349. const int n = 4 * i;
  350. int y_offset = (i & 2) << 2;
  351. if (IS_SUB_8X8(sub_mb_type)) {
  352. get_lowest_part_y(h, refs, n, 8, y_offset,
  353. IS_DIR(sub_mb_type, 0, 0),
  354. IS_DIR(sub_mb_type, 0, 1),
  355. nrefs);
  356. } else if (IS_SUB_8X4(sub_mb_type)) {
  357. get_lowest_part_y(h, refs, n, 4, y_offset,
  358. IS_DIR(sub_mb_type, 0, 0),
  359. IS_DIR(sub_mb_type, 0, 1),
  360. nrefs);
  361. get_lowest_part_y(h, refs, n + 2, 4, y_offset + 4,
  362. IS_DIR(sub_mb_type, 0, 0),
  363. IS_DIR(sub_mb_type, 0, 1),
  364. nrefs);
  365. } else if (IS_SUB_4X8(sub_mb_type)) {
  366. get_lowest_part_y(h, refs, n, 8, y_offset,
  367. IS_DIR(sub_mb_type, 0, 0),
  368. IS_DIR(sub_mb_type, 0, 1),
  369. nrefs);
  370. get_lowest_part_y(h, refs, n + 1, 8, y_offset,
  371. IS_DIR(sub_mb_type, 0, 0),
  372. IS_DIR(sub_mb_type, 0, 1),
  373. nrefs);
  374. } else {
  375. int j;
  376. av_assert2(IS_SUB_4X4(sub_mb_type));
  377. for (j = 0; j < 4; j++) {
  378. int sub_y_offset = y_offset + 2 * (j & 2);
  379. get_lowest_part_y(h, refs, n + j, 4, sub_y_offset,
  380. IS_DIR(sub_mb_type, 0, 0),
  381. IS_DIR(sub_mb_type, 0, 1),
  382. nrefs);
  383. }
  384. }
  385. }
  386. }
  387. for (list = h->list_count - 1; list >= 0; list--)
  388. for (ref = 0; ref < 48 && nrefs[list]; ref++) {
  389. int row = refs[list][ref];
  390. if (row >= 0) {
  391. Picture *ref_pic = &h->ref_list[list][ref];
  392. int ref_field = ref_pic->f.reference - 1;
  393. int ref_field_picture = ref_pic->field_picture;
  394. int pic_height = 16 * s->mb_height >> ref_field_picture;
  395. row <<= MB_MBAFF;
  396. nrefs[list]--;
  397. if (!FIELD_PICTURE && ref_field_picture) { // frame referencing two fields
  398. ff_thread_await_progress(&ref_pic->f,
  399. FFMIN((row >> 1) - !(row & 1),
  400. pic_height - 1),
  401. 1);
  402. ff_thread_await_progress(&ref_pic->f,
  403. FFMIN((row >> 1), pic_height - 1),
  404. 0);
  405. } else if (FIELD_PICTURE && !ref_field_picture) { // field referencing one field of a frame
  406. ff_thread_await_progress(&ref_pic->f,
  407. FFMIN(row * 2 + ref_field,
  408. pic_height - 1),
  409. 0);
  410. } else if (FIELD_PICTURE) {
  411. ff_thread_await_progress(&ref_pic->f,
  412. FFMIN(row, pic_height - 1),
  413. ref_field);
  414. } else {
  415. ff_thread_await_progress(&ref_pic->f,
  416. FFMIN(row, pic_height - 1),
  417. 0);
  418. }
  419. }
  420. }
  421. }
  422. static av_always_inline void mc_dir_part(H264Context *h, Picture *pic,
  423. int n, int square, int height,
  424. int delta, int list,
  425. uint8_t *dest_y, uint8_t *dest_cb,
  426. uint8_t *dest_cr,
  427. int src_x_offset, int src_y_offset,
  428. qpel_mc_func *qpix_op,
  429. h264_chroma_mc_func chroma_op,
  430. int pixel_shift, int chroma_idc)
  431. {
  432. MpegEncContext *const s = &h->s;
  433. const int mx = h->mv_cache[list][scan8[n]][0] + src_x_offset * 8;
  434. int my = h->mv_cache[list][scan8[n]][1] + src_y_offset * 8;
  435. const int luma_xy = (mx & 3) + ((my & 3) << 2);
  436. int offset = ((mx >> 2) << pixel_shift) + (my >> 2) * h->mb_linesize;
  437. uint8_t *src_y = pic->f.data[0] + offset;
  438. uint8_t *src_cb, *src_cr;
  439. int extra_width = h->emu_edge_width;
  440. int extra_height = h->emu_edge_height;
  441. int emu = 0;
  442. const int full_mx = mx >> 2;
  443. const int full_my = my >> 2;
  444. const int pic_width = 16 * s->mb_width;
  445. const int pic_height = 16 * s->mb_height >> MB_FIELD;
  446. int ysh;
  447. if (mx & 7)
  448. extra_width -= 3;
  449. if (my & 7)
  450. extra_height -= 3;
  451. if (full_mx < 0 - extra_width ||
  452. full_my < 0 - extra_height ||
  453. full_mx + 16 /*FIXME*/ > pic_width + extra_width ||
  454. full_my + 16 /*FIXME*/ > pic_height + extra_height) {
  455. s->dsp.emulated_edge_mc(s->edge_emu_buffer,
  456. src_y - (2 << pixel_shift) - 2 * h->mb_linesize,
  457. h->mb_linesize,
  458. 16 + 5, 16 + 5 /*FIXME*/, full_mx - 2,
  459. full_my - 2, pic_width, pic_height);
  460. src_y = s->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
  461. emu = 1;
  462. }
  463. qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); // FIXME try variable height perhaps?
  464. if (!square)
  465. qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
  466. if (CONFIG_GRAY && s->flags & CODEC_FLAG_GRAY)
  467. return;
  468. if (chroma_idc == 3 /* yuv444 */) {
  469. src_cb = pic->f.data[1] + offset;
  470. if (emu) {
  471. s->dsp.emulated_edge_mc(s->edge_emu_buffer,
  472. src_cb - (2 << pixel_shift) - 2 * h->mb_linesize,
  473. h->mb_linesize,
  474. 16 + 5, 16 + 5 /*FIXME*/,
  475. full_mx - 2, full_my - 2,
  476. pic_width, pic_height);
  477. src_cb = s->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
  478. }
  479. qpix_op[luma_xy](dest_cb, src_cb, h->mb_linesize); // FIXME try variable height perhaps?
  480. if (!square)
  481. qpix_op[luma_xy](dest_cb + delta, src_cb + delta, h->mb_linesize);
  482. src_cr = pic->f.data[2] + offset;
  483. if (emu) {
  484. s->dsp.emulated_edge_mc(s->edge_emu_buffer,
  485. src_cr - (2 << pixel_shift) - 2 * h->mb_linesize,
  486. h->mb_linesize,
  487. 16 + 5, 16 + 5 /*FIXME*/,
  488. full_mx - 2, full_my - 2,
  489. pic_width, pic_height);
  490. src_cr = s->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
  491. }
  492. qpix_op[luma_xy](dest_cr, src_cr, h->mb_linesize); // FIXME try variable height perhaps?
  493. if (!square)
  494. qpix_op[luma_xy](dest_cr + delta, src_cr + delta, h->mb_linesize);
  495. return;
  496. }
  497. ysh = 3 - (chroma_idc == 2 /* yuv422 */);
  498. if (chroma_idc == 1 /* yuv420 */ && MB_FIELD) {
  499. // chroma offset when predicting from a field of opposite parity
  500. my += 2 * ((s->mb_y & 1) - (pic->f.reference - 1));
  501. emu |= (my >> 3) < 0 || (my >> 3) + 8 >= (pic_height >> 1);
  502. }
  503. src_cb = pic->f.data[1] + ((mx >> 3) << pixel_shift) +
  504. (my >> ysh) * h->mb_uvlinesize;
  505. src_cr = pic->f.data[2] + ((mx >> 3) << pixel_shift) +
  506. (my >> ysh) * h->mb_uvlinesize;
  507. if (emu) {
  508. s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cb, h->mb_uvlinesize,
  509. 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
  510. pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
  511. src_cb = s->edge_emu_buffer;
  512. }
  513. chroma_op(dest_cb, src_cb, h->mb_uvlinesize,
  514. height >> (chroma_idc == 1 /* yuv420 */),
  515. mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
  516. if (emu) {
  517. s->dsp.emulated_edge_mc(s->edge_emu_buffer, src_cr, h->mb_uvlinesize,
  518. 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
  519. pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
  520. src_cr = s->edge_emu_buffer;
  521. }
  522. chroma_op(dest_cr, src_cr, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
  523. mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
  524. }
  525. static av_always_inline void mc_part_std(H264Context *h, int n, int square,
  526. int height, int delta,
  527. uint8_t *dest_y, uint8_t *dest_cb,
  528. uint8_t *dest_cr,
  529. int x_offset, int y_offset,
  530. qpel_mc_func *qpix_put,
  531. h264_chroma_mc_func chroma_put,
  532. qpel_mc_func *qpix_avg,
  533. h264_chroma_mc_func chroma_avg,
  534. int list0, int list1,
  535. int pixel_shift, int chroma_idc)
  536. {
  537. MpegEncContext *const s = &h->s;
  538. qpel_mc_func *qpix_op = qpix_put;
  539. h264_chroma_mc_func chroma_op = chroma_put;
  540. dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
  541. if (chroma_idc == 3 /* yuv444 */) {
  542. dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
  543. dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
  544. } else if (chroma_idc == 2 /* yuv422 */) {
  545. dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
  546. dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
  547. } else { /* yuv420 */
  548. dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
  549. dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
  550. }
  551. x_offset += 8 * s->mb_x;
  552. y_offset += 8 * (s->mb_y >> MB_FIELD);
  553. if (list0) {
  554. Picture *ref = &h->ref_list[0][h->ref_cache[0][scan8[n]]];
  555. mc_dir_part(h, ref, n, square, height, delta, 0,
  556. dest_y, dest_cb, dest_cr, x_offset, y_offset,
  557. qpix_op, chroma_op, pixel_shift, chroma_idc);
  558. qpix_op = qpix_avg;
  559. chroma_op = chroma_avg;
  560. }
  561. if (list1) {
  562. Picture *ref = &h->ref_list[1][h->ref_cache[1][scan8[n]]];
  563. mc_dir_part(h, ref, n, square, height, delta, 1,
  564. dest_y, dest_cb, dest_cr, x_offset, y_offset,
  565. qpix_op, chroma_op, pixel_shift, chroma_idc);
  566. }
  567. }
  568. static av_always_inline void mc_part_weighted(H264Context *h, int n, int square,
  569. int height, int delta,
  570. uint8_t *dest_y, uint8_t *dest_cb,
  571. uint8_t *dest_cr,
  572. int x_offset, int y_offset,
  573. qpel_mc_func *qpix_put,
  574. h264_chroma_mc_func chroma_put,
  575. h264_weight_func luma_weight_op,
  576. h264_weight_func chroma_weight_op,
  577. h264_biweight_func luma_weight_avg,
  578. h264_biweight_func chroma_weight_avg,
  579. int list0, int list1,
  580. int pixel_shift, int chroma_idc)
  581. {
  582. MpegEncContext *const s = &h->s;
  583. int chroma_height;
  584. dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
  585. if (chroma_idc == 3 /* yuv444 */) {
  586. chroma_height = height;
  587. chroma_weight_avg = luma_weight_avg;
  588. chroma_weight_op = luma_weight_op;
  589. dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
  590. dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
  591. } else if (chroma_idc == 2 /* yuv422 */) {
  592. chroma_height = height;
  593. dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
  594. dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
  595. } else { /* yuv420 */
  596. chroma_height = height >> 1;
  597. dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
  598. dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
  599. }
  600. x_offset += 8 * s->mb_x;
  601. y_offset += 8 * (s->mb_y >> MB_FIELD);
  602. if (list0 && list1) {
  603. /* don't optimize for luma-only case, since B-frames usually
  604. * use implicit weights => chroma too. */
  605. uint8_t *tmp_cb = h->bipred_scratchpad;
  606. uint8_t *tmp_cr = h->bipred_scratchpad + (16 << pixel_shift);
  607. uint8_t *tmp_y = h->bipred_scratchpad + 16 * h->mb_uvlinesize;
  608. int refn0 = h->ref_cache[0][scan8[n]];
  609. int refn1 = h->ref_cache[1][scan8[n]];
  610. mc_dir_part(h, &h->ref_list[0][refn0], n, square, height, delta, 0,
  611. dest_y, dest_cb, dest_cr,
  612. x_offset, y_offset, qpix_put, chroma_put,
  613. pixel_shift, chroma_idc);
  614. mc_dir_part(h, &h->ref_list[1][refn1], n, square, height, delta, 1,
  615. tmp_y, tmp_cb, tmp_cr,
  616. x_offset, y_offset, qpix_put, chroma_put,
  617. pixel_shift, chroma_idc);
  618. if (h->use_weight == 2) {
  619. int weight0 = h->implicit_weight[refn0][refn1][s->mb_y & 1];
  620. int weight1 = 64 - weight0;
  621. luma_weight_avg(dest_y, tmp_y, h->mb_linesize,
  622. height, 5, weight0, weight1, 0);
  623. chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize,
  624. chroma_height, 5, weight0, weight1, 0);
  625. chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize,
  626. chroma_height, 5, weight0, weight1, 0);
  627. } else {
  628. luma_weight_avg(dest_y, tmp_y, h->mb_linesize, height,
  629. h->luma_log2_weight_denom,
  630. h->luma_weight[refn0][0][0],
  631. h->luma_weight[refn1][1][0],
  632. h->luma_weight[refn0][0][1] +
  633. h->luma_weight[refn1][1][1]);
  634. chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, chroma_height,
  635. h->chroma_log2_weight_denom,
  636. h->chroma_weight[refn0][0][0][0],
  637. h->chroma_weight[refn1][1][0][0],
  638. h->chroma_weight[refn0][0][0][1] +
  639. h->chroma_weight[refn1][1][0][1]);
  640. chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, chroma_height,
  641. h->chroma_log2_weight_denom,
  642. h->chroma_weight[refn0][0][1][0],
  643. h->chroma_weight[refn1][1][1][0],
  644. h->chroma_weight[refn0][0][1][1] +
  645. h->chroma_weight[refn1][1][1][1]);
  646. }
  647. } else {
  648. int list = list1 ? 1 : 0;
  649. int refn = h->ref_cache[list][scan8[n]];
  650. Picture *ref = &h->ref_list[list][refn];
  651. mc_dir_part(h, ref, n, square, height, delta, list,
  652. dest_y, dest_cb, dest_cr, x_offset, y_offset,
  653. qpix_put, chroma_put, pixel_shift, chroma_idc);
  654. luma_weight_op(dest_y, h->mb_linesize, height,
  655. h->luma_log2_weight_denom,
  656. h->luma_weight[refn][list][0],
  657. h->luma_weight[refn][list][1]);
  658. if (h->use_weight_chroma) {
  659. chroma_weight_op(dest_cb, h->mb_uvlinesize, chroma_height,
  660. h->chroma_log2_weight_denom,
  661. h->chroma_weight[refn][list][0][0],
  662. h->chroma_weight[refn][list][0][1]);
  663. chroma_weight_op(dest_cr, h->mb_uvlinesize, chroma_height,
  664. h->chroma_log2_weight_denom,
  665. h->chroma_weight[refn][list][1][0],
  666. h->chroma_weight[refn][list][1][1]);
  667. }
  668. }
  669. }
  670. static av_always_inline void prefetch_motion(H264Context *h, int list,
  671. int pixel_shift, int chroma_idc)
  672. {
  673. /* fetch pixels for estimated mv 4 macroblocks ahead
  674. * optimized for 64byte cache lines */
  675. MpegEncContext *const s = &h->s;
  676. const int refn = h->ref_cache[list][scan8[0]];
  677. if (refn >= 0) {
  678. const int mx = (h->mv_cache[list][scan8[0]][0] >> 2) + 16 * s->mb_x + 8;
  679. const int my = (h->mv_cache[list][scan8[0]][1] >> 2) + 16 * s->mb_y;
  680. uint8_t **src = h->ref_list[list][refn].f.data;
  681. int off = (mx << pixel_shift) +
  682. (my + (s->mb_x & 3) * 4) * h->mb_linesize +
  683. (64 << pixel_shift);
  684. s->dsp.prefetch(src[0] + off, s->linesize, 4);
  685. if (chroma_idc == 3 /* yuv444 */) {
  686. s->dsp.prefetch(src[1] + off, s->linesize, 4);
  687. s->dsp.prefetch(src[2] + off, s->linesize, 4);
  688. } else {
  689. off= (((mx>>1)+64)<<pixel_shift) + ((my>>1) + (s->mb_x&7))*s->uvlinesize;
  690. s->dsp.prefetch(src[1] + off, src[2] - src[1], 2);
  691. }
  692. }
  693. }
  694. static void free_tables(H264Context *h, int free_rbsp)
  695. {
  696. int i;
  697. H264Context *hx;
  698. av_freep(&h->intra4x4_pred_mode);
  699. av_freep(&h->chroma_pred_mode_table);
  700. av_freep(&h->cbp_table);
  701. av_freep(&h->mvd_table[0]);
  702. av_freep(&h->mvd_table[1]);
  703. av_freep(&h->direct_table);
  704. av_freep(&h->non_zero_count);
  705. av_freep(&h->slice_table_base);
  706. h->slice_table = NULL;
  707. av_freep(&h->list_counts);
  708. av_freep(&h->mb2b_xy);
  709. av_freep(&h->mb2br_xy);
  710. for (i = 0; i < MAX_THREADS; i++) {
  711. hx = h->thread_context[i];
  712. if (!hx)
  713. continue;
  714. av_freep(&hx->top_borders[1]);
  715. av_freep(&hx->top_borders[0]);
  716. av_freep(&hx->bipred_scratchpad);
  717. if (free_rbsp) {
  718. av_freep(&hx->rbsp_buffer[1]);
  719. av_freep(&hx->rbsp_buffer[0]);
  720. hx->rbsp_buffer_size[0] = 0;
  721. hx->rbsp_buffer_size[1] = 0;
  722. }
  723. if (i)
  724. av_freep(&h->thread_context[i]);
  725. }
  726. }
  727. static void init_dequant8_coeff_table(H264Context *h)
  728. {
  729. int i, j, q, x;
  730. const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
  731. for (i = 0; i < 6; i++) {
  732. h->dequant8_coeff[i] = h->dequant8_buffer[i];
  733. for (j = 0; j < i; j++)
  734. if (!memcmp(h->pps.scaling_matrix8[j], h->pps.scaling_matrix8[i],
  735. 64 * sizeof(uint8_t))) {
  736. h->dequant8_coeff[i] = h->dequant8_buffer[j];
  737. break;
  738. }
  739. if (j < i)
  740. continue;
  741. for (q = 0; q < max_qp + 1; q++) {
  742. int shift = div6[q];
  743. int idx = rem6[q];
  744. for (x = 0; x < 64; x++)
  745. h->dequant8_coeff[i][q][(x >> 3) | ((x & 7) << 3)] =
  746. ((uint32_t)dequant8_coeff_init[idx][dequant8_coeff_init_scan[((x >> 1) & 12) | (x & 3)]] *
  747. h->pps.scaling_matrix8[i][x]) << shift;
  748. }
  749. }
  750. }
  751. static void init_dequant4_coeff_table(H264Context *h)
  752. {
  753. int i, j, q, x;
  754. const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
  755. for (i = 0; i < 6; i++) {
  756. h->dequant4_coeff[i] = h->dequant4_buffer[i];
  757. for (j = 0; j < i; j++)
  758. if (!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i],
  759. 16 * sizeof(uint8_t))) {
  760. h->dequant4_coeff[i] = h->dequant4_buffer[j];
  761. break;
  762. }
  763. if (j < i)
  764. continue;
  765. for (q = 0; q < max_qp + 1; q++) {
  766. int shift = div6[q] + 2;
  767. int idx = rem6[q];
  768. for (x = 0; x < 16; x++)
  769. h->dequant4_coeff[i][q][(x >> 2) | ((x << 2) & 0xF)] =
  770. ((uint32_t)dequant4_coeff_init[idx][(x & 1) + ((x >> 2) & 1)] *
  771. h->pps.scaling_matrix4[i][x]) << shift;
  772. }
  773. }
  774. }
  775. static void init_dequant_tables(H264Context *h)
  776. {
  777. int i, x;
  778. init_dequant4_coeff_table(h);
  779. if (h->pps.transform_8x8_mode)
  780. init_dequant8_coeff_table(h);
  781. if (h->sps.transform_bypass) {
  782. for (i = 0; i < 6; i++)
  783. for (x = 0; x < 16; x++)
  784. h->dequant4_coeff[i][0][x] = 1 << 6;
  785. if (h->pps.transform_8x8_mode)
  786. for (i = 0; i < 6; i++)
  787. for (x = 0; x < 64; x++)
  788. h->dequant8_coeff[i][0][x] = 1 << 6;
  789. }
  790. }
  791. int ff_h264_alloc_tables(H264Context *h)
  792. {
  793. MpegEncContext *const s = &h->s;
  794. const int big_mb_num = s->mb_stride * (s->mb_height + 1);
  795. const int row_mb_num = 2*s->mb_stride*FFMAX(s->avctx->thread_count, 1);
  796. int x, y;
  797. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->intra4x4_pred_mode,
  798. row_mb_num * 8 * sizeof(uint8_t), fail)
  799. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->non_zero_count,
  800. big_mb_num * 48 * sizeof(uint8_t), fail)
  801. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->slice_table_base,
  802. (big_mb_num + s->mb_stride) * sizeof(*h->slice_table_base), fail)
  803. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->cbp_table,
  804. big_mb_num * sizeof(uint16_t), fail)
  805. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->chroma_pred_mode_table,
  806. big_mb_num * sizeof(uint8_t), fail)
  807. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[0],
  808. 16 * row_mb_num * sizeof(uint8_t), fail);
  809. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mvd_table[1],
  810. 16 * row_mb_num * sizeof(uint8_t), fail);
  811. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->direct_table,
  812. 4 * big_mb_num * sizeof(uint8_t), fail);
  813. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->list_counts,
  814. big_mb_num * sizeof(uint8_t), fail)
  815. memset(h->slice_table_base, -1,
  816. (big_mb_num + s->mb_stride) * sizeof(*h->slice_table_base));
  817. h->slice_table = h->slice_table_base + s->mb_stride * 2 + 1;
  818. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2b_xy,
  819. big_mb_num * sizeof(uint32_t), fail);
  820. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->mb2br_xy,
  821. big_mb_num * sizeof(uint32_t), fail);
  822. for (y = 0; y < s->mb_height; y++)
  823. for (x = 0; x < s->mb_width; x++) {
  824. const int mb_xy = x + y * s->mb_stride;
  825. const int b_xy = 4 * x + 4 * y * h->b_stride;
  826. h->mb2b_xy[mb_xy] = b_xy;
  827. h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * s->mb_stride)));
  828. }
  829. if (!h->dequant4_coeff[0])
  830. init_dequant_tables(h);
  831. return 0;
  832. fail:
  833. free_tables(h, 1);
  834. return -1;
  835. }
  836. /**
  837. * Mimic alloc_tables(), but for every context thread.
  838. */
  839. static void clone_tables(H264Context *dst, H264Context *src, int i)
  840. {
  841. MpegEncContext *const s = &src->s;
  842. dst->intra4x4_pred_mode = src->intra4x4_pred_mode + i * 8 * 2 * s->mb_stride;
  843. dst->non_zero_count = src->non_zero_count;
  844. dst->slice_table = src->slice_table;
  845. dst->cbp_table = src->cbp_table;
  846. dst->mb2b_xy = src->mb2b_xy;
  847. dst->mb2br_xy = src->mb2br_xy;
  848. dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
  849. dst->mvd_table[0] = src->mvd_table[0] + i * 8 * 2 * s->mb_stride;
  850. dst->mvd_table[1] = src->mvd_table[1] + i * 8 * 2 * s->mb_stride;
  851. dst->direct_table = src->direct_table;
  852. dst->list_counts = src->list_counts;
  853. dst->bipred_scratchpad = NULL;
  854. ff_h264_pred_init(&dst->hpc, src->s.codec_id, src->sps.bit_depth_luma,
  855. src->sps.chroma_format_idc);
  856. }
  857. /**
  858. * Init context
  859. * Allocate buffers which are not shared amongst multiple threads.
  860. */
  861. static int context_init(H264Context *h)
  862. {
  863. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[0],
  864. h->s.mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
  865. FF_ALLOCZ_OR_GOTO(h->s.avctx, h->top_borders[1],
  866. h->s.mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
  867. h->ref_cache[0][scan8[5] + 1] =
  868. h->ref_cache[0][scan8[7] + 1] =
  869. h->ref_cache[0][scan8[13] + 1] =
  870. h->ref_cache[1][scan8[5] + 1] =
  871. h->ref_cache[1][scan8[7] + 1] =
  872. h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
  873. return 0;
  874. fail:
  875. return -1; // free_tables will clean up for us
  876. }
  877. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size);
  878. static av_cold void common_init(H264Context *h)
  879. {
  880. MpegEncContext *const s = &h->s;
  881. s->width = s->avctx->width;
  882. s->height = s->avctx->height;
  883. s->codec_id = s->avctx->codec->id;
  884. s->avctx->bits_per_raw_sample = 8;
  885. h->cur_chroma_format_idc = 1;
  886. ff_h264dsp_init(&h->h264dsp,
  887. s->avctx->bits_per_raw_sample, h->cur_chroma_format_idc);
  888. ff_h264_pred_init(&h->hpc, s->codec_id,
  889. s->avctx->bits_per_raw_sample, h->cur_chroma_format_idc);
  890. h->dequant_coeff_pps = -1;
  891. s->unrestricted_mv = 1;
  892. s->dsp.dct_bits = 16;
  893. /* needed so that IDCT permutation is known early */
  894. ff_dsputil_init(&s->dsp, s->avctx);
  895. memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
  896. memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
  897. }
  898. static int ff_h264_decode_extradata_internal(H264Context *h, const uint8_t *buf, int size)
  899. {
  900. AVCodecContext *avctx = h->s.avctx;
  901. if (!buf || size <= 0)
  902. return -1;
  903. if (buf[0] == 1) {
  904. int i, cnt, nalsize;
  905. const unsigned char *p = buf;
  906. h->is_avc = 1;
  907. if (size < 7) {
  908. av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
  909. return -1;
  910. }
  911. /* sps and pps in the avcC always have length coded with 2 bytes,
  912. * so put a fake nal_length_size = 2 while parsing them */
  913. h->nal_length_size = 2;
  914. // Decode sps from avcC
  915. cnt = *(p + 5) & 0x1f; // Number of sps
  916. p += 6;
  917. for (i = 0; i < cnt; i++) {
  918. nalsize = AV_RB16(p) + 2;
  919. if(nalsize > size - (p-buf))
  920. return -1;
  921. if (decode_nal_units(h, p, nalsize) < 0) {
  922. av_log(avctx, AV_LOG_ERROR,
  923. "Decoding sps %d from avcC failed\n", i);
  924. return -1;
  925. }
  926. p += nalsize;
  927. }
  928. // Decode pps from avcC
  929. cnt = *(p++); // Number of pps
  930. for (i = 0; i < cnt; i++) {
  931. nalsize = AV_RB16(p) + 2;
  932. if(nalsize > size - (p-buf))
  933. return -1;
  934. if (decode_nal_units(h, p, nalsize) < 0) {
  935. av_log(avctx, AV_LOG_ERROR,
  936. "Decoding pps %d from avcC failed\n", i);
  937. return -1;
  938. }
  939. p += nalsize;
  940. }
  941. // Now store right nal length size, that will be used to parse all other nals
  942. h->nal_length_size = (buf[4] & 0x03) + 1;
  943. } else {
  944. h->is_avc = 0;
  945. if (decode_nal_units(h, buf, size) < 0)
  946. return -1;
  947. }
  948. return size;
  949. }
  950. int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
  951. {
  952. int ret;
  953. h->decoding_extradata = 1;
  954. ret = ff_h264_decode_extradata_internal(h, buf, size);
  955. h->decoding_extradata = 0;
  956. return ret;
  957. }
  958. av_cold int ff_h264_decode_init(AVCodecContext *avctx)
  959. {
  960. H264Context *h = avctx->priv_data;
  961. MpegEncContext *const s = &h->s;
  962. int i;
  963. ff_MPV_decode_defaults(s);
  964. s->avctx = avctx;
  965. common_init(h);
  966. s->out_format = FMT_H264;
  967. s->workaround_bugs = avctx->workaround_bugs;
  968. /* set defaults */
  969. // s->decode_mb = ff_h263_decode_mb;
  970. s->quarter_sample = 1;
  971. if (!avctx->has_b_frames)
  972. s->low_delay = 1;
  973. avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
  974. ff_h264_decode_init_vlc();
  975. h->pixel_shift = 0;
  976. h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
  977. h->thread_context[0] = h;
  978. h->outputed_poc = h->next_outputed_poc = INT_MIN;
  979. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  980. h->last_pocs[i] = INT_MIN;
  981. h->prev_poc_msb = 1 << 16;
  982. h->prev_frame_num = -1;
  983. h->x264_build = -1;
  984. ff_h264_reset_sei(h);
  985. if (avctx->codec_id == AV_CODEC_ID_H264) {
  986. if (avctx->ticks_per_frame == 1) {
  987. if(s->avctx->time_base.den < INT_MAX/2) {
  988. s->avctx->time_base.den *= 2;
  989. } else
  990. s->avctx->time_base.num /= 2;
  991. }
  992. avctx->ticks_per_frame = 2;
  993. }
  994. if (avctx->extradata_size > 0 && avctx->extradata &&
  995. ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size) < 0) {
  996. ff_h264_free_context(h);
  997. return -1;
  998. }
  999. if (h->sps.bitstream_restriction_flag &&
  1000. s->avctx->has_b_frames < h->sps.num_reorder_frames) {
  1001. s->avctx->has_b_frames = h->sps.num_reorder_frames;
  1002. s->low_delay = 0;
  1003. }
  1004. ff_init_cabac_states();
  1005. return 0;
  1006. }
  1007. #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
  1008. static void copy_picture_range(Picture **to, Picture **from, int count,
  1009. MpegEncContext *new_base,
  1010. MpegEncContext *old_base)
  1011. {
  1012. int i;
  1013. for (i = 0; i < count; i++) {
  1014. assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
  1015. IN_RANGE(from[i], old_base->picture,
  1016. sizeof(Picture) * old_base->picture_count) ||
  1017. !from[i]));
  1018. to[i] = REBASE_PICTURE(from[i], new_base, old_base);
  1019. }
  1020. }
  1021. static void copy_parameter_set(void **to, void **from, int count, int size)
  1022. {
  1023. int i;
  1024. for (i = 0; i < count; i++) {
  1025. if (to[i] && !from[i])
  1026. av_freep(&to[i]);
  1027. else if (from[i] && !to[i])
  1028. to[i] = av_malloc(size);
  1029. if (from[i])
  1030. memcpy(to[i], from[i], size);
  1031. }
  1032. }
  1033. static int decode_init_thread_copy(AVCodecContext *avctx)
  1034. {
  1035. H264Context *h = avctx->priv_data;
  1036. if (!avctx->internal->is_copy)
  1037. return 0;
  1038. memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
  1039. memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
  1040. return 0;
  1041. }
  1042. #define copy_fields(to, from, start_field, end_field) \
  1043. memcpy(&to->start_field, &from->start_field, \
  1044. (char *)&to->end_field - (char *)&to->start_field)
  1045. static int decode_update_thread_context(AVCodecContext *dst,
  1046. const AVCodecContext *src)
  1047. {
  1048. H264Context *h = dst->priv_data, *h1 = src->priv_data;
  1049. MpegEncContext *const s = &h->s, *const s1 = &h1->s;
  1050. int inited = s->context_initialized, err;
  1051. int i;
  1052. if (dst == src)
  1053. return 0;
  1054. err = ff_mpeg_update_thread_context(dst, src);
  1055. if (err)
  1056. return err;
  1057. // FIXME handle width/height changing
  1058. if (!inited) {
  1059. for (i = 0; i < MAX_SPS_COUNT; i++)
  1060. av_freep(h->sps_buffers + i);
  1061. for (i = 0; i < MAX_PPS_COUNT; i++)
  1062. av_freep(h->pps_buffers + i);
  1063. // copy all fields after MpegEnc
  1064. memcpy(&h->s + 1, &h1->s + 1,
  1065. sizeof(H264Context) - sizeof(MpegEncContext));
  1066. memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
  1067. memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
  1068. if (s1->context_initialized) {
  1069. if (ff_h264_alloc_tables(h) < 0) {
  1070. av_log(dst, AV_LOG_ERROR, "Could not allocate memory for h264\n");
  1071. return AVERROR(ENOMEM);
  1072. }
  1073. context_init(h);
  1074. }
  1075. for (i = 0; i < 2; i++) {
  1076. h->rbsp_buffer[i] = NULL;
  1077. h->rbsp_buffer_size[i] = 0;
  1078. }
  1079. h->bipred_scratchpad = NULL;
  1080. h->thread_context[0] = h;
  1081. s->dsp.clear_blocks(h->mb);
  1082. s->dsp.clear_blocks(h->mb + (24 * 16 << h->pixel_shift));
  1083. }
  1084. /* frame_start may not be called for the next thread (if it's decoding
  1085. * a bottom field) so this has to be allocated here */
  1086. if (!h->bipred_scratchpad && s->linesize)
  1087. h->bipred_scratchpad = av_malloc(16 * 6 * s->linesize);
  1088. // extradata/NAL handling
  1089. h->is_avc = h1->is_avc;
  1090. // SPS/PPS
  1091. copy_parameter_set((void **)h->sps_buffers, (void **)h1->sps_buffers,
  1092. MAX_SPS_COUNT, sizeof(SPS));
  1093. h->sps = h1->sps;
  1094. copy_parameter_set((void **)h->pps_buffers, (void **)h1->pps_buffers,
  1095. MAX_PPS_COUNT, sizeof(PPS));
  1096. h->pps = h1->pps;
  1097. // Dequantization matrices
  1098. // FIXME these are big - can they be only copied when PPS changes?
  1099. copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
  1100. for (i = 0; i < 6; i++)
  1101. h->dequant4_coeff[i] = h->dequant4_buffer[0] +
  1102. (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
  1103. for (i = 0; i < 6; i++)
  1104. h->dequant8_coeff[i] = h->dequant8_buffer[0] +
  1105. (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
  1106. h->dequant_coeff_pps = h1->dequant_coeff_pps;
  1107. // POC timing
  1108. copy_fields(h, h1, poc_lsb, redundant_pic_count);
  1109. // reference lists
  1110. copy_fields(h, h1, ref_count, list_count);
  1111. copy_fields(h, h1, ref_list, intra_gb);
  1112. copy_fields(h, h1, short_ref, cabac_init_idc);
  1113. copy_picture_range(h->short_ref, h1->short_ref, 32, s, s1);
  1114. copy_picture_range(h->long_ref, h1->long_ref, 32, s, s1);
  1115. copy_picture_range(h->delayed_pic, h1->delayed_pic,
  1116. MAX_DELAYED_PIC_COUNT + 2, s, s1);
  1117. h->last_slice_type = h1->last_slice_type;
  1118. h->sync = h1->sync;
  1119. if (!s->current_picture_ptr)
  1120. return 0;
  1121. if (!s->droppable) {
  1122. err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
  1123. h->prev_poc_msb = h->poc_msb;
  1124. h->prev_poc_lsb = h->poc_lsb;
  1125. }
  1126. h->prev_frame_num_offset = h->frame_num_offset;
  1127. h->prev_frame_num = h->frame_num;
  1128. h->outputed_poc = h->next_outputed_poc;
  1129. return err;
  1130. }
  1131. int ff_h264_frame_start(H264Context *h)
  1132. {
  1133. MpegEncContext *const s = &h->s;
  1134. int i;
  1135. const int pixel_shift = h->pixel_shift;
  1136. if (ff_MPV_frame_start(s, s->avctx) < 0)
  1137. return -1;
  1138. ff_er_frame_start(s);
  1139. /*
  1140. * ff_MPV_frame_start uses pict_type to derive key_frame.
  1141. * This is incorrect for H.264; IDR markings must be used.
  1142. * Zero here; IDR markings per slice in frame or fields are ORed in later.
  1143. * See decode_nal_units().
  1144. */
  1145. s->current_picture_ptr->f.key_frame = 0;
  1146. s->current_picture_ptr->sync = 0;
  1147. s->current_picture_ptr->mmco_reset = 0;
  1148. assert(s->linesize && s->uvlinesize);
  1149. for (i = 0; i < 16; i++) {
  1150. h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * s->linesize * ((scan8[i] - scan8[0]) >> 3);
  1151. h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * s->linesize * ((scan8[i] - scan8[0]) >> 3);
  1152. }
  1153. for (i = 0; i < 16; i++) {
  1154. h->block_offset[16 + i] =
  1155. h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * s->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
  1156. h->block_offset[48 + 16 + i] =
  1157. h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * s->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
  1158. }
  1159. /* can't be in alloc_tables because linesize isn't known there.
  1160. * FIXME: redo bipred weight to not require extra buffer? */
  1161. for (i = 0; i < s->slice_context_count; i++)
  1162. if (h->thread_context[i] && !h->thread_context[i]->bipred_scratchpad)
  1163. h->thread_context[i]->bipred_scratchpad = av_malloc(16 * 6 * s->linesize);
  1164. /* Some macroblocks can be accessed before they're available in case
  1165. * of lost slices, MBAFF or threading. */
  1166. memset(h->slice_table, -1,
  1167. (s->mb_height * s->mb_stride - 1) * sizeof(*h->slice_table));
  1168. // s->decode = (s->flags & CODEC_FLAG_PSNR) || !s->encoding ||
  1169. // s->current_picture.f.reference /* || h->contains_intra */ || 1;
  1170. /* We mark the current picture as non-reference after allocating it, so
  1171. * that if we break out due to an error it can be released automatically
  1172. * in the next ff_MPV_frame_start().
  1173. * SVQ3 as well as most other codecs have only last/next/current and thus
  1174. * get released even with set reference, besides SVQ3 and others do not
  1175. * mark frames as reference later "naturally". */
  1176. if (s->codec_id != AV_CODEC_ID_SVQ3)
  1177. s->current_picture_ptr->f.reference = 0;
  1178. s->current_picture_ptr->field_poc[0] =
  1179. s->current_picture_ptr->field_poc[1] = INT_MAX;
  1180. h->next_output_pic = NULL;
  1181. assert(s->current_picture_ptr->long_ref == 0);
  1182. return 0;
  1183. }
  1184. /**
  1185. * Run setup operations that must be run after slice header decoding.
  1186. * This includes finding the next displayed frame.
  1187. *
  1188. * @param h h264 master context
  1189. * @param setup_finished enough NALs have been read that we can call
  1190. * ff_thread_finish_setup()
  1191. */
  1192. static void decode_postinit(H264Context *h, int setup_finished)
  1193. {
  1194. MpegEncContext *const s = &h->s;
  1195. Picture *out = s->current_picture_ptr;
  1196. Picture *cur = s->current_picture_ptr;
  1197. int i, pics, out_of_order, out_idx;
  1198. s->current_picture_ptr->f.qscale_type = FF_QSCALE_TYPE_H264;
  1199. s->current_picture_ptr->f.pict_type = s->pict_type;
  1200. if (h->next_output_pic)
  1201. return;
  1202. if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
  1203. /* FIXME: if we have two PAFF fields in one packet, we can't start
  1204. * the next thread here. If we have one field per packet, we can.
  1205. * The check in decode_nal_units() is not good enough to find this
  1206. * yet, so we assume the worst for now. */
  1207. // if (setup_finished)
  1208. // ff_thread_finish_setup(s->avctx);
  1209. return;
  1210. }
  1211. cur->f.interlaced_frame = 0;
  1212. cur->f.repeat_pict = 0;
  1213. /* Signal interlacing information externally. */
  1214. /* Prioritize picture timing SEI information over used
  1215. * decoding process if it exists. */
  1216. if (h->sps.pic_struct_present_flag) {
  1217. switch (h->sei_pic_struct) {
  1218. case SEI_PIC_STRUCT_FRAME:
  1219. break;
  1220. case SEI_PIC_STRUCT_TOP_FIELD:
  1221. case SEI_PIC_STRUCT_BOTTOM_FIELD:
  1222. cur->f.interlaced_frame = 1;
  1223. break;
  1224. case SEI_PIC_STRUCT_TOP_BOTTOM:
  1225. case SEI_PIC_STRUCT_BOTTOM_TOP:
  1226. if (FIELD_OR_MBAFF_PICTURE)
  1227. cur->f.interlaced_frame = 1;
  1228. else
  1229. // try to flag soft telecine progressive
  1230. cur->f.interlaced_frame = h->prev_interlaced_frame;
  1231. break;
  1232. case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
  1233. case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
  1234. /* Signal the possibility of telecined film externally
  1235. * (pic_struct 5,6). From these hints, let the applications
  1236. * decide if they apply deinterlacing. */
  1237. cur->f.repeat_pict = 1;
  1238. break;
  1239. case SEI_PIC_STRUCT_FRAME_DOUBLING:
  1240. // Force progressive here, doubling interlaced frame is a bad idea.
  1241. cur->f.repeat_pict = 2;
  1242. break;
  1243. case SEI_PIC_STRUCT_FRAME_TRIPLING:
  1244. cur->f.repeat_pict = 4;
  1245. break;
  1246. }
  1247. if ((h->sei_ct_type & 3) &&
  1248. h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
  1249. cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
  1250. } else {
  1251. /* Derive interlacing flag from used decoding process. */
  1252. cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE;
  1253. }
  1254. h->prev_interlaced_frame = cur->f.interlaced_frame;
  1255. if (cur->field_poc[0] != cur->field_poc[1]) {
  1256. /* Derive top_field_first from field pocs. */
  1257. cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
  1258. } else {
  1259. if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
  1260. /* Use picture timing SEI information. Even if it is a
  1261. * information of a past frame, better than nothing. */
  1262. if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
  1263. h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
  1264. cur->f.top_field_first = 1;
  1265. else
  1266. cur->f.top_field_first = 0;
  1267. } else {
  1268. /* Most likely progressive */
  1269. cur->f.top_field_first = 0;
  1270. }
  1271. }
  1272. cur->mmco_reset = h->mmco_reset;
  1273. h->mmco_reset = 0;
  1274. // FIXME do something with unavailable reference frames
  1275. /* Sort B-frames into display order */
  1276. if (h->sps.bitstream_restriction_flag &&
  1277. s->avctx->has_b_frames < h->sps.num_reorder_frames) {
  1278. s->avctx->has_b_frames = h->sps.num_reorder_frames;
  1279. s->low_delay = 0;
  1280. }
  1281. if (s->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
  1282. !h->sps.bitstream_restriction_flag) {
  1283. s->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
  1284. s->low_delay = 0;
  1285. }
  1286. for (i = 0; 1; i++) {
  1287. if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
  1288. if(i)
  1289. h->last_pocs[i-1] = cur->poc;
  1290. break;
  1291. } else if(i) {
  1292. h->last_pocs[i-1]= h->last_pocs[i];
  1293. }
  1294. }
  1295. out_of_order = MAX_DELAYED_PIC_COUNT - i;
  1296. if( cur->f.pict_type == AV_PICTURE_TYPE_B
  1297. || (h->last_pocs[MAX_DELAYED_PIC_COUNT-2] > INT_MIN && h->last_pocs[MAX_DELAYED_PIC_COUNT-1] - h->last_pocs[MAX_DELAYED_PIC_COUNT-2] > 2))
  1298. out_of_order = FFMAX(out_of_order, 1);
  1299. if(s->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
  1300. av_log(s->avctx, AV_LOG_VERBOSE, "Increasing reorder buffer to %d\n", out_of_order);
  1301. s->avctx->has_b_frames = out_of_order;
  1302. s->low_delay = 0;
  1303. }
  1304. pics = 0;
  1305. while (h->delayed_pic[pics])
  1306. pics++;
  1307. av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
  1308. h->delayed_pic[pics++] = cur;
  1309. if (cur->f.reference == 0)
  1310. cur->f.reference = DELAYED_PIC_REF;
  1311. out = h->delayed_pic[0];
  1312. out_idx = 0;
  1313. for (i = 1; h->delayed_pic[i] &&
  1314. !h->delayed_pic[i]->f.key_frame &&
  1315. !h->delayed_pic[i]->mmco_reset;
  1316. i++)
  1317. if (h->delayed_pic[i]->poc < out->poc) {
  1318. out = h->delayed_pic[i];
  1319. out_idx = i;
  1320. }
  1321. if (s->avctx->has_b_frames == 0 &&
  1322. (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset))
  1323. h->next_outputed_poc = INT_MIN;
  1324. out_of_order = out->poc < h->next_outputed_poc;
  1325. if (out_of_order || pics > s->avctx->has_b_frames) {
  1326. out->f.reference &= ~DELAYED_PIC_REF;
  1327. // for frame threading, the owner must be the second field's thread or
  1328. // else the first thread can release the picture and reuse it unsafely
  1329. out->owner2 = s;
  1330. for (i = out_idx; h->delayed_pic[i]; i++)
  1331. h->delayed_pic[i] = h->delayed_pic[i + 1];
  1332. }
  1333. if (!out_of_order && pics > s->avctx->has_b_frames) {
  1334. h->next_output_pic = out;
  1335. if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset)) {
  1336. h->next_outputed_poc = INT_MIN;
  1337. } else
  1338. h->next_outputed_poc = out->poc;
  1339. } else {
  1340. av_log(s->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
  1341. }
  1342. if (h->next_output_pic && h->next_output_pic->sync) {
  1343. h->sync |= 2;
  1344. }
  1345. if (setup_finished)
  1346. ff_thread_finish_setup(s->avctx);
  1347. }
  1348. static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
  1349. uint8_t *src_cb, uint8_t *src_cr,
  1350. int linesize, int uvlinesize,
  1351. int simple)
  1352. {
  1353. MpegEncContext *const s = &h->s;
  1354. uint8_t *top_border;
  1355. int top_idx = 1;
  1356. const int pixel_shift = h->pixel_shift;
  1357. int chroma444 = CHROMA444;
  1358. int chroma422 = CHROMA422;
  1359. src_y -= linesize;
  1360. src_cb -= uvlinesize;
  1361. src_cr -= uvlinesize;
  1362. if (!simple && FRAME_MBAFF) {
  1363. if (s->mb_y & 1) {
  1364. if (!MB_MBAFF) {
  1365. top_border = h->top_borders[0][s->mb_x];
  1366. AV_COPY128(top_border, src_y + 15 * linesize);
  1367. if (pixel_shift)
  1368. AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
  1369. if (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
  1370. if (chroma444) {
  1371. if (pixel_shift) {
  1372. AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
  1373. AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
  1374. AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
  1375. AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
  1376. } else {
  1377. AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
  1378. AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
  1379. }
  1380. } else if (chroma422) {
  1381. if (pixel_shift) {
  1382. AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
  1383. AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
  1384. } else {
  1385. AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
  1386. AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
  1387. }
  1388. } else {
  1389. if (pixel_shift) {
  1390. AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
  1391. AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
  1392. } else {
  1393. AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
  1394. AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
  1395. }
  1396. }
  1397. }
  1398. }
  1399. } else if (MB_MBAFF) {
  1400. top_idx = 0;
  1401. } else
  1402. return;
  1403. }
  1404. top_border = h->top_borders[top_idx][s->mb_x];
  1405. /* There are two lines saved, the line above the top macroblock
  1406. * of a pair, and the line above the bottom macroblock. */
  1407. AV_COPY128(top_border, src_y + 16 * linesize);
  1408. if (pixel_shift)
  1409. AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
  1410. if (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
  1411. if (chroma444) {
  1412. if (pixel_shift) {
  1413. AV_COPY128(top_border + 32, src_cb + 16 * linesize);
  1414. AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
  1415. AV_COPY128(top_border + 64, src_cr + 16 * linesize);
  1416. AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
  1417. } else {
  1418. AV_COPY128(top_border + 16, src_cb + 16 * linesize);
  1419. AV_COPY128(top_border + 32, src_cr + 16 * linesize);
  1420. }
  1421. } else if (chroma422) {
  1422. if (pixel_shift) {
  1423. AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
  1424. AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
  1425. } else {
  1426. AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
  1427. AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
  1428. }
  1429. } else {
  1430. if (pixel_shift) {
  1431. AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
  1432. AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
  1433. } else {
  1434. AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
  1435. AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
  1436. }
  1437. }
  1438. }
  1439. }
  1440. static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
  1441. uint8_t *src_cb, uint8_t *src_cr,
  1442. int linesize, int uvlinesize,
  1443. int xchg, int chroma444,
  1444. int simple, int pixel_shift)
  1445. {
  1446. MpegEncContext *const s = &h->s;
  1447. int deblock_topleft;
  1448. int deblock_top;
  1449. int top_idx = 1;
  1450. uint8_t *top_border_m1;
  1451. uint8_t *top_border;
  1452. if (!simple && FRAME_MBAFF) {
  1453. if (s->mb_y & 1) {
  1454. if (!MB_MBAFF)
  1455. return;
  1456. } else {
  1457. top_idx = MB_MBAFF ? 0 : 1;
  1458. }
  1459. }
  1460. if (h->deblocking_filter == 2) {
  1461. deblock_topleft = h->slice_table[h->mb_xy - 1 - s->mb_stride] == h->slice_num;
  1462. deblock_top = h->top_type;
  1463. } else {
  1464. deblock_topleft = (s->mb_x > 0);
  1465. deblock_top = (s->mb_y > !!MB_FIELD);
  1466. }
  1467. src_y -= linesize + 1 + pixel_shift;
  1468. src_cb -= uvlinesize + 1 + pixel_shift;
  1469. src_cr -= uvlinesize + 1 + pixel_shift;
  1470. top_border_m1 = h->top_borders[top_idx][s->mb_x - 1];
  1471. top_border = h->top_borders[top_idx][s->mb_x];
  1472. #define XCHG(a, b, xchg) \
  1473. if (pixel_shift) { \
  1474. if (xchg) { \
  1475. AV_SWAP64(b + 0, a + 0); \
  1476. AV_SWAP64(b + 8, a + 8); \
  1477. } else { \
  1478. AV_COPY128(b, a); \
  1479. } \
  1480. } else if (xchg) \
  1481. AV_SWAP64(b, a); \
  1482. else \
  1483. AV_COPY64(b, a);
  1484. if (deblock_top) {
  1485. if (deblock_topleft) {
  1486. XCHG(top_border_m1 + (8 << pixel_shift),
  1487. src_y - (7 << pixel_shift), 1);
  1488. }
  1489. XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
  1490. XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
  1491. if (s->mb_x + 1 < s->mb_width) {
  1492. XCHG(h->top_borders[top_idx][s->mb_x + 1],
  1493. src_y + (17 << pixel_shift), 1);
  1494. }
  1495. }
  1496. if (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
  1497. if (chroma444) {
  1498. if (deblock_topleft) {
  1499. XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
  1500. XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
  1501. }
  1502. XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
  1503. XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
  1504. XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
  1505. XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
  1506. if (s->mb_x + 1 < s->mb_width) {
  1507. XCHG(h->top_borders[top_idx][s->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
  1508. XCHG(h->top_borders[top_idx][s->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
  1509. }
  1510. } else {
  1511. if (deblock_top) {
  1512. if (deblock_topleft) {
  1513. XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
  1514. XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
  1515. }
  1516. XCHG(top_border + (16 << pixel_shift), src_cb + 1 + pixel_shift, 1);
  1517. XCHG(top_border + (24 << pixel_shift), src_cr + 1 + pixel_shift, 1);
  1518. }
  1519. }
  1520. }
  1521. }
  1522. static av_always_inline int dctcoef_get(DCTELEM *mb, int high_bit_depth,
  1523. int index)
  1524. {
  1525. if (high_bit_depth) {
  1526. return AV_RN32A(((int32_t *)mb) + index);
  1527. } else
  1528. return AV_RN16A(mb + index);
  1529. }
  1530. static av_always_inline void dctcoef_set(DCTELEM *mb, int high_bit_depth,
  1531. int index, int value)
  1532. {
  1533. if (high_bit_depth) {
  1534. AV_WN32A(((int32_t *)mb) + index, value);
  1535. } else
  1536. AV_WN16A(mb + index, value);
  1537. }
  1538. static av_always_inline void hl_decode_mb_predict_luma(H264Context *h,
  1539. int mb_type, int is_h264,
  1540. int simple,
  1541. int transform_bypass,
  1542. int pixel_shift,
  1543. int *block_offset,
  1544. int linesize,
  1545. uint8_t *dest_y, int p)
  1546. {
  1547. MpegEncContext *const s = &h->s;
  1548. void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
  1549. void (*idct_dc_add)(uint8_t *dst, DCTELEM *block, int stride);
  1550. int i;
  1551. int qscale = p == 0 ? s->qscale : h->chroma_qp[p - 1];
  1552. block_offset += 16 * p;
  1553. if (IS_INTRA4x4(mb_type)) {
  1554. if (simple || !s->encoding) {
  1555. if (IS_8x8DCT(mb_type)) {
  1556. if (transform_bypass) {
  1557. idct_dc_add =
  1558. idct_add = s->dsp.add_pixels8;
  1559. } else {
  1560. idct_dc_add = h->h264dsp.h264_idct8_dc_add;
  1561. idct_add = h->h264dsp.h264_idct8_add;
  1562. }
  1563. for (i = 0; i < 16; i += 4) {
  1564. uint8_t *const ptr = dest_y + block_offset[i];
  1565. const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
  1566. if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
  1567. h->hpc.pred8x8l_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  1568. } else {
  1569. const int nnz = h->non_zero_count_cache[scan8[i + p * 16]];
  1570. h->hpc.pred8x8l[dir](ptr, (h->topleft_samples_available << i) & 0x8000,
  1571. (h->topright_samples_available << i) & 0x4000, linesize);
  1572. if (nnz) {
  1573. if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
  1574. idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  1575. else
  1576. idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  1577. }
  1578. }
  1579. }
  1580. } else {
  1581. if (transform_bypass) {
  1582. idct_dc_add =
  1583. idct_add = s->dsp.add_pixels4;
  1584. } else {
  1585. idct_dc_add = h->h264dsp.h264_idct_dc_add;
  1586. idct_add = h->h264dsp.h264_idct_add;
  1587. }
  1588. for (i = 0; i < 16; i++) {
  1589. uint8_t *const ptr = dest_y + block_offset[i];
  1590. const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
  1591. if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
  1592. h->hpc.pred4x4_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  1593. } else {
  1594. uint8_t *topright;
  1595. int nnz, tr;
  1596. uint64_t tr_high;
  1597. if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
  1598. const int topright_avail = (h->topright_samples_available << i) & 0x8000;
  1599. av_assert2(s->mb_y || linesize <= block_offset[i]);
  1600. if (!topright_avail) {
  1601. if (pixel_shift) {
  1602. tr_high = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
  1603. topright = (uint8_t *)&tr_high;
  1604. } else {
  1605. tr = ptr[3 - linesize] * 0x01010101u;
  1606. topright = (uint8_t *)&tr;
  1607. }
  1608. } else
  1609. topright = ptr + (4 << pixel_shift) - linesize;
  1610. } else
  1611. topright = NULL;
  1612. h->hpc.pred4x4[dir](ptr, topright, linesize);
  1613. nnz = h->non_zero_count_cache[scan8[i + p * 16]];
  1614. if (nnz) {
  1615. if (is_h264) {
  1616. if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
  1617. idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  1618. else
  1619. idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  1620. } else if (CONFIG_SVQ3_DECODER)
  1621. ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize, qscale, 0);
  1622. }
  1623. }
  1624. }
  1625. }
  1626. }
  1627. } else {
  1628. h->hpc.pred16x16[h->intra16x16_pred_mode](dest_y, linesize);
  1629. if (is_h264) {
  1630. if (h->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {
  1631. if (!transform_bypass)
  1632. h->h264dsp.h264_luma_dc_dequant_idct(h->mb + (p * 256 << pixel_shift),
  1633. h->mb_luma_dc[p],
  1634. h->dequant4_coeff[p][qscale][0]);
  1635. else {
  1636. static const uint8_t dc_mapping[16] = {
  1637. 0 * 16, 1 * 16, 4 * 16, 5 * 16,
  1638. 2 * 16, 3 * 16, 6 * 16, 7 * 16,
  1639. 8 * 16, 9 * 16, 12 * 16, 13 * 16,
  1640. 10 * 16, 11 * 16, 14 * 16, 15 * 16 };
  1641. for (i = 0; i < 16; i++)
  1642. dctcoef_set(h->mb + (p * 256 << pixel_shift),
  1643. pixel_shift, dc_mapping[i],
  1644. dctcoef_get(h->mb_luma_dc[p],
  1645. pixel_shift, i));
  1646. }
  1647. }
  1648. } else if (CONFIG_SVQ3_DECODER)
  1649. ff_svq3_luma_dc_dequant_idct_c(h->mb + p * 256,
  1650. h->mb_luma_dc[p], qscale);
  1651. }
  1652. }
  1653. static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type,
  1654. int is_h264, int simple,
  1655. int transform_bypass,
  1656. int pixel_shift,
  1657. int *block_offset,
  1658. int linesize,
  1659. uint8_t *dest_y, int p)
  1660. {
  1661. MpegEncContext *const s = &h->s;
  1662. void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
  1663. int i;
  1664. block_offset += 16 * p;
  1665. if (!IS_INTRA4x4(mb_type)) {
  1666. if (is_h264) {
  1667. if (IS_INTRA16x16(mb_type)) {
  1668. if (transform_bypass) {
  1669. if (h->sps.profile_idc == 244 &&
  1670. (h->intra16x16_pred_mode == VERT_PRED8x8 ||
  1671. h->intra16x16_pred_mode == HOR_PRED8x8)) {
  1672. h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset,
  1673. h->mb + (p * 256 << pixel_shift),
  1674. linesize);
  1675. } else {
  1676. for (i = 0; i < 16; i++)
  1677. if (h->non_zero_count_cache[scan8[i + p * 16]] ||
  1678. dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
  1679. s->dsp.add_pixels4(dest_y + block_offset[i],
  1680. h->mb + (i * 16 + p * 256 << pixel_shift),
  1681. linesize);
  1682. }
  1683. } else {
  1684. h->h264dsp.h264_idct_add16intra(dest_y, block_offset,
  1685. h->mb + (p * 256 << pixel_shift),
  1686. linesize,
  1687. h->non_zero_count_cache + p * 5 * 8);
  1688. }
  1689. } else if (h->cbp & 15) {
  1690. if (transform_bypass) {
  1691. const int di = IS_8x8DCT(mb_type) ? 4 : 1;
  1692. idct_add = IS_8x8DCT(mb_type) ? s->dsp.add_pixels8
  1693. : s->dsp.add_pixels4;
  1694. for (i = 0; i < 16; i += di)
  1695. if (h->non_zero_count_cache[scan8[i + p * 16]])
  1696. idct_add(dest_y + block_offset[i],
  1697. h->mb + (i * 16 + p * 256 << pixel_shift),
  1698. linesize);
  1699. } else {
  1700. if (IS_8x8DCT(mb_type))
  1701. h->h264dsp.h264_idct8_add4(dest_y, block_offset,
  1702. h->mb + (p * 256 << pixel_shift),
  1703. linesize,
  1704. h->non_zero_count_cache + p * 5 * 8);
  1705. else
  1706. h->h264dsp.h264_idct_add16(dest_y, block_offset,
  1707. h->mb + (p * 256 << pixel_shift),
  1708. linesize,
  1709. h->non_zero_count_cache + p * 5 * 8);
  1710. }
  1711. }
  1712. } else if (CONFIG_SVQ3_DECODER) {
  1713. for (i = 0; i < 16; i++)
  1714. if (h->non_zero_count_cache[scan8[i + p * 16]] || h->mb[i * 16 + p * 256]) {
  1715. // FIXME benchmark weird rule, & below
  1716. uint8_t *const ptr = dest_y + block_offset[i];
  1717. ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize,
  1718. s->qscale, IS_INTRA(mb_type) ? 1 : 0);
  1719. }
  1720. }
  1721. }
  1722. }
  1723. #define BITS 8
  1724. #define SIMPLE 1
  1725. #include "h264_mb_template.c"
  1726. #undef BITS
  1727. #define BITS 16
  1728. #include "h264_mb_template.c"
  1729. #undef SIMPLE
  1730. #define SIMPLE 0
  1731. #include "h264_mb_template.c"
  1732. void ff_h264_hl_decode_mb(H264Context *h)
  1733. {
  1734. MpegEncContext *const s = &h->s;
  1735. const int mb_xy = h->mb_xy;
  1736. const int mb_type = s->current_picture.f.mb_type[mb_xy];
  1737. int is_complex = CONFIG_SMALL || h->is_complex || IS_INTRA_PCM(mb_type) || s->qscale == 0;
  1738. if (CHROMA444) {
  1739. if (is_complex || h->pixel_shift)
  1740. hl_decode_mb_444_complex(h);
  1741. else
  1742. hl_decode_mb_444_simple_8(h);
  1743. } else if (is_complex) {
  1744. hl_decode_mb_complex(h);
  1745. } else if (h->pixel_shift) {
  1746. hl_decode_mb_simple_16(h);
  1747. } else
  1748. hl_decode_mb_simple_8(h);
  1749. }
  1750. static int pred_weight_table(H264Context *h)
  1751. {
  1752. MpegEncContext *const s = &h->s;
  1753. int list, i;
  1754. int luma_def, chroma_def;
  1755. h->use_weight = 0;
  1756. h->use_weight_chroma = 0;
  1757. h->luma_log2_weight_denom = get_ue_golomb(&s->gb);
  1758. if (h->sps.chroma_format_idc)
  1759. h->chroma_log2_weight_denom = get_ue_golomb(&s->gb);
  1760. luma_def = 1 << h->luma_log2_weight_denom;
  1761. chroma_def = 1 << h->chroma_log2_weight_denom;
  1762. for (list = 0; list < 2; list++) {
  1763. h->luma_weight_flag[list] = 0;
  1764. h->chroma_weight_flag[list] = 0;
  1765. for (i = 0; i < h->ref_count[list]; i++) {
  1766. int luma_weight_flag, chroma_weight_flag;
  1767. luma_weight_flag = get_bits1(&s->gb);
  1768. if (luma_weight_flag) {
  1769. h->luma_weight[i][list][0] = get_se_golomb(&s->gb);
  1770. h->luma_weight[i][list][1] = get_se_golomb(&s->gb);
  1771. if (h->luma_weight[i][list][0] != luma_def ||
  1772. h->luma_weight[i][list][1] != 0) {
  1773. h->use_weight = 1;
  1774. h->luma_weight_flag[list] = 1;
  1775. }
  1776. } else {
  1777. h->luma_weight[i][list][0] = luma_def;
  1778. h->luma_weight[i][list][1] = 0;
  1779. }
  1780. if (h->sps.chroma_format_idc) {
  1781. chroma_weight_flag = get_bits1(&s->gb);
  1782. if (chroma_weight_flag) {
  1783. int j;
  1784. for (j = 0; j < 2; j++) {
  1785. h->chroma_weight[i][list][j][0] = get_se_golomb(&s->gb);
  1786. h->chroma_weight[i][list][j][1] = get_se_golomb(&s->gb);
  1787. if (h->chroma_weight[i][list][j][0] != chroma_def ||
  1788. h->chroma_weight[i][list][j][1] != 0) {
  1789. h->use_weight_chroma = 1;
  1790. h->chroma_weight_flag[list] = 1;
  1791. }
  1792. }
  1793. } else {
  1794. int j;
  1795. for (j = 0; j < 2; j++) {
  1796. h->chroma_weight[i][list][j][0] = chroma_def;
  1797. h->chroma_weight[i][list][j][1] = 0;
  1798. }
  1799. }
  1800. }
  1801. }
  1802. if (h->slice_type_nos != AV_PICTURE_TYPE_B)
  1803. break;
  1804. }
  1805. h->use_weight = h->use_weight || h->use_weight_chroma;
  1806. return 0;
  1807. }
  1808. /**
  1809. * Initialize implicit_weight table.
  1810. * @param field 0/1 initialize the weight for interlaced MBAFF
  1811. * -1 initializes the rest
  1812. */
  1813. static void implicit_weight_table(H264Context *h, int field)
  1814. {
  1815. MpegEncContext *const s = &h->s;
  1816. int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
  1817. for (i = 0; i < 2; i++) {
  1818. h->luma_weight_flag[i] = 0;
  1819. h->chroma_weight_flag[i] = 0;
  1820. }
  1821. if (field < 0) {
  1822. if (s->picture_structure == PICT_FRAME) {
  1823. cur_poc = s->current_picture_ptr->poc;
  1824. } else {
  1825. cur_poc = s->current_picture_ptr->field_poc[s->picture_structure - 1];
  1826. }
  1827. if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF &&
  1828. h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) {
  1829. h->use_weight = 0;
  1830. h->use_weight_chroma = 0;
  1831. return;
  1832. }
  1833. ref_start = 0;
  1834. ref_count0 = h->ref_count[0];
  1835. ref_count1 = h->ref_count[1];
  1836. } else {
  1837. cur_poc = s->current_picture_ptr->field_poc[field];
  1838. ref_start = 16;
  1839. ref_count0 = 16 + 2 * h->ref_count[0];
  1840. ref_count1 = 16 + 2 * h->ref_count[1];
  1841. }
  1842. h->use_weight = 2;
  1843. h->use_weight_chroma = 2;
  1844. h->luma_log2_weight_denom = 5;
  1845. h->chroma_log2_weight_denom = 5;
  1846. for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
  1847. int poc0 = h->ref_list[0][ref0].poc;
  1848. for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
  1849. int w = 32;
  1850. if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
  1851. int poc1 = h->ref_list[1][ref1].poc;
  1852. int td = av_clip(poc1 - poc0, -128, 127);
  1853. if (td) {
  1854. int tb = av_clip(cur_poc - poc0, -128, 127);
  1855. int tx = (16384 + (FFABS(td) >> 1)) / td;
  1856. int dist_scale_factor = (tb * tx + 32) >> 8;
  1857. if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
  1858. w = 64 - dist_scale_factor;
  1859. }
  1860. }
  1861. if (field < 0) {
  1862. h->implicit_weight[ref0][ref1][0] =
  1863. h->implicit_weight[ref0][ref1][1] = w;
  1864. } else {
  1865. h->implicit_weight[ref0][ref1][field] = w;
  1866. }
  1867. }
  1868. }
  1869. }
  1870. /**
  1871. * instantaneous decoder refresh.
  1872. */
  1873. static void idr(H264Context *h)
  1874. {
  1875. int i;
  1876. ff_h264_remove_all_refs(h);
  1877. h->prev_frame_num = 0;
  1878. h->prev_frame_num_offset = 0;
  1879. h->prev_poc_msb = 1<<16;
  1880. h->prev_poc_lsb = 0;
  1881. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  1882. h->last_pocs[i] = INT_MIN;
  1883. }
  1884. /* forget old pics after a seek */
  1885. static void flush_dpb(AVCodecContext *avctx)
  1886. {
  1887. H264Context *h = avctx->priv_data;
  1888. int i;
  1889. for (i=0; i<=MAX_DELAYED_PIC_COUNT; i++) {
  1890. if (h->delayed_pic[i])
  1891. h->delayed_pic[i]->f.reference = 0;
  1892. h->delayed_pic[i] = NULL;
  1893. }
  1894. h->outputed_poc = h->next_outputed_poc = INT_MIN;
  1895. h->prev_interlaced_frame = 1;
  1896. idr(h);
  1897. h->prev_frame_num = -1;
  1898. if (h->s.current_picture_ptr)
  1899. h->s.current_picture_ptr->f.reference = 0;
  1900. h->s.first_field = 0;
  1901. ff_h264_reset_sei(h);
  1902. ff_mpeg_flush(avctx);
  1903. h->recovery_frame= -1;
  1904. h->sync= 0;
  1905. }
  1906. static int init_poc(H264Context *h)
  1907. {
  1908. MpegEncContext *const s = &h->s;
  1909. const int max_frame_num = 1 << h->sps.log2_max_frame_num;
  1910. int field_poc[2];
  1911. Picture *cur = s->current_picture_ptr;
  1912. h->frame_num_offset = h->prev_frame_num_offset;
  1913. if (h->frame_num < h->prev_frame_num)
  1914. h->frame_num_offset += max_frame_num;
  1915. if (h->sps.poc_type == 0) {
  1916. const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
  1917. if (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
  1918. h->poc_msb = h->prev_poc_msb + max_poc_lsb;
  1919. else if (h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
  1920. h->poc_msb = h->prev_poc_msb - max_poc_lsb;
  1921. else
  1922. h->poc_msb = h->prev_poc_msb;
  1923. field_poc[0] =
  1924. field_poc[1] = h->poc_msb + h->poc_lsb;
  1925. if (s->picture_structure == PICT_FRAME)
  1926. field_poc[1] += h->delta_poc_bottom;
  1927. } else if (h->sps.poc_type == 1) {
  1928. int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
  1929. int i;
  1930. if (h->sps.poc_cycle_length != 0)
  1931. abs_frame_num = h->frame_num_offset + h->frame_num;
  1932. else
  1933. abs_frame_num = 0;
  1934. if (h->nal_ref_idc == 0 && abs_frame_num > 0)
  1935. abs_frame_num--;
  1936. expected_delta_per_poc_cycle = 0;
  1937. for (i = 0; i < h->sps.poc_cycle_length; i++)
  1938. // FIXME integrate during sps parse
  1939. expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
  1940. if (abs_frame_num > 0) {
  1941. int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
  1942. int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
  1943. expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
  1944. for (i = 0; i <= frame_num_in_poc_cycle; i++)
  1945. expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
  1946. } else
  1947. expectedpoc = 0;
  1948. if (h->nal_ref_idc == 0)
  1949. expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
  1950. field_poc[0] = expectedpoc + h->delta_poc[0];
  1951. field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
  1952. if (s->picture_structure == PICT_FRAME)
  1953. field_poc[1] += h->delta_poc[1];
  1954. } else {
  1955. int poc = 2 * (h->frame_num_offset + h->frame_num);
  1956. if (!h->nal_ref_idc)
  1957. poc--;
  1958. field_poc[0] = poc;
  1959. field_poc[1] = poc;
  1960. }
  1961. if (s->picture_structure != PICT_BOTTOM_FIELD)
  1962. s->current_picture_ptr->field_poc[0] = field_poc[0];
  1963. if (s->picture_structure != PICT_TOP_FIELD)
  1964. s->current_picture_ptr->field_poc[1] = field_poc[1];
  1965. cur->poc = FFMIN(cur->field_poc[0], cur->field_poc[1]);
  1966. return 0;
  1967. }
  1968. /**
  1969. * initialize scan tables
  1970. */
  1971. static void init_scan_tables(H264Context *h)
  1972. {
  1973. int i;
  1974. for (i = 0; i < 16; i++) {
  1975. #define T(x) (x >> 2) | ((x << 2) & 0xF)
  1976. h->zigzag_scan[i] = T(zigzag_scan[i]);
  1977. h->field_scan[i] = T(field_scan[i]);
  1978. #undef T
  1979. }
  1980. for (i = 0; i < 64; i++) {
  1981. #define T(x) (x >> 3) | ((x & 7) << 3)
  1982. h->zigzag_scan8x8[i] = T(ff_zigzag_direct[i]);
  1983. h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
  1984. h->field_scan8x8[i] = T(field_scan8x8[i]);
  1985. h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
  1986. #undef T
  1987. }
  1988. if (h->sps.transform_bypass) { // FIXME same ugly
  1989. memcpy(h->zigzag_scan_q0 , zigzag_scan , sizeof(h->zigzag_scan_q0 ));
  1990. memcpy(h->zigzag_scan8x8_q0 , ff_zigzag_direct , sizeof(h->zigzag_scan8x8_q0 ));
  1991. memcpy(h->zigzag_scan8x8_cavlc_q0 , zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
  1992. memcpy(h->field_scan_q0 , field_scan , sizeof(h->field_scan_q0 ));
  1993. memcpy(h->field_scan8x8_q0 , field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
  1994. memcpy(h->field_scan8x8_cavlc_q0 , field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
  1995. } else {
  1996. memcpy(h->zigzag_scan_q0 , h->zigzag_scan , sizeof(h->zigzag_scan_q0 ));
  1997. memcpy(h->zigzag_scan8x8_q0 , h->zigzag_scan8x8 , sizeof(h->zigzag_scan8x8_q0 ));
  1998. memcpy(h->zigzag_scan8x8_cavlc_q0 , h->zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
  1999. memcpy(h->field_scan_q0 , h->field_scan , sizeof(h->field_scan_q0 ));
  2000. memcpy(h->field_scan8x8_q0 , h->field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
  2001. memcpy(h->field_scan8x8_cavlc_q0 , h->field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
  2002. }
  2003. }
  2004. static int field_end(H264Context *h, int in_setup)
  2005. {
  2006. MpegEncContext *const s = &h->s;
  2007. AVCodecContext *const avctx = s->avctx;
  2008. int err = 0;
  2009. s->mb_y = 0;
  2010. if (!in_setup && !s->droppable)
  2011. ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX,
  2012. s->picture_structure == PICT_BOTTOM_FIELD);
  2013. if (CONFIG_H264_VDPAU_DECODER &&
  2014. s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  2015. ff_vdpau_h264_set_reference_frames(s);
  2016. if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
  2017. if (!s->droppable) {
  2018. err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
  2019. h->prev_poc_msb = h->poc_msb;
  2020. h->prev_poc_lsb = h->poc_lsb;
  2021. }
  2022. h->prev_frame_num_offset = h->frame_num_offset;
  2023. h->prev_frame_num = h->frame_num;
  2024. h->outputed_poc = h->next_outputed_poc;
  2025. }
  2026. if (avctx->hwaccel) {
  2027. if (avctx->hwaccel->end_frame(avctx) < 0)
  2028. av_log(avctx, AV_LOG_ERROR,
  2029. "hardware accelerator failed to decode picture\n");
  2030. }
  2031. if (CONFIG_H264_VDPAU_DECODER &&
  2032. s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  2033. ff_vdpau_h264_picture_complete(s);
  2034. /*
  2035. * FIXME: Error handling code does not seem to support interlaced
  2036. * when slices span multiple rows
  2037. * The ff_er_add_slice calls don't work right for bottom
  2038. * fields; they cause massive erroneous error concealing
  2039. * Error marking covers both fields (top and bottom).
  2040. * This causes a mismatched s->error_count
  2041. * and a bad error table. Further, the error count goes to
  2042. * INT_MAX when called for bottom field, because mb_y is
  2043. * past end by one (callers fault) and resync_mb_y != 0
  2044. * causes problems for the first MB line, too.
  2045. */
  2046. if (!FIELD_PICTURE)
  2047. ff_er_frame_end(s);
  2048. ff_MPV_frame_end(s);
  2049. h->current_slice = 0;
  2050. return err;
  2051. }
  2052. /**
  2053. * Replicate H264 "master" context to thread contexts.
  2054. */
  2055. static void clone_slice(H264Context *dst, H264Context *src)
  2056. {
  2057. memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
  2058. dst->s.current_picture_ptr = src->s.current_picture_ptr;
  2059. dst->s.current_picture = src->s.current_picture;
  2060. dst->s.linesize = src->s.linesize;
  2061. dst->s.uvlinesize = src->s.uvlinesize;
  2062. dst->s.first_field = src->s.first_field;
  2063. dst->prev_poc_msb = src->prev_poc_msb;
  2064. dst->prev_poc_lsb = src->prev_poc_lsb;
  2065. dst->prev_frame_num_offset = src->prev_frame_num_offset;
  2066. dst->prev_frame_num = src->prev_frame_num;
  2067. dst->short_ref_count = src->short_ref_count;
  2068. memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
  2069. memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
  2070. memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
  2071. memcpy(dst->ref_list, src->ref_list, sizeof(dst->ref_list));
  2072. memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
  2073. memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
  2074. }
  2075. /**
  2076. * Compute profile from profile_idc and constraint_set?_flags.
  2077. *
  2078. * @param sps SPS
  2079. *
  2080. * @return profile as defined by FF_PROFILE_H264_*
  2081. */
  2082. int ff_h264_get_profile(SPS *sps)
  2083. {
  2084. int profile = sps->profile_idc;
  2085. switch (sps->profile_idc) {
  2086. case FF_PROFILE_H264_BASELINE:
  2087. // constraint_set1_flag set to 1
  2088. profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
  2089. break;
  2090. case FF_PROFILE_H264_HIGH_10:
  2091. case FF_PROFILE_H264_HIGH_422:
  2092. case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
  2093. // constraint_set3_flag set to 1
  2094. profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
  2095. break;
  2096. }
  2097. return profile;
  2098. }
  2099. /**
  2100. * Decode a slice header.
  2101. * This will also call ff_MPV_common_init() and frame_start() as needed.
  2102. *
  2103. * @param h h264context
  2104. * @param h0 h264 master context (differs from 'h' when doing sliced based
  2105. * parallel decoding)
  2106. *
  2107. * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
  2108. */
  2109. static int decode_slice_header(H264Context *h, H264Context *h0)
  2110. {
  2111. MpegEncContext *const s = &h->s;
  2112. MpegEncContext *const s0 = &h0->s;
  2113. unsigned int first_mb_in_slice;
  2114. unsigned int pps_id;
  2115. int num_ref_idx_active_override_flag;
  2116. unsigned int slice_type, tmp, i, j;
  2117. int default_ref_list_done = 0;
  2118. int last_pic_structure, last_pic_droppable;
  2119. int must_reinit;
  2120. /* FIXME: 2tap qpel isn't implemented for high bit depth. */
  2121. if ((s->avctx->flags2 & CODEC_FLAG2_FAST) &&
  2122. !h->nal_ref_idc && !h->pixel_shift) {
  2123. s->me.qpel_put = s->dsp.put_2tap_qpel_pixels_tab;
  2124. s->me.qpel_avg = s->dsp.avg_2tap_qpel_pixels_tab;
  2125. } else {
  2126. s->me.qpel_put = s->dsp.put_h264_qpel_pixels_tab;
  2127. s->me.qpel_avg = s->dsp.avg_h264_qpel_pixels_tab;
  2128. }
  2129. first_mb_in_slice = get_ue_golomb_long(&s->gb);
  2130. if (first_mb_in_slice == 0) { // FIXME better field boundary detection
  2131. if (h0->current_slice && FIELD_PICTURE) {
  2132. field_end(h, 1);
  2133. }
  2134. h0->current_slice = 0;
  2135. if (!s0->first_field) {
  2136. if (s->current_picture_ptr && !s->droppable &&
  2137. s->current_picture_ptr->owner2 == s) {
  2138. ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX,
  2139. s->picture_structure == PICT_BOTTOM_FIELD);
  2140. }
  2141. s->current_picture_ptr = NULL;
  2142. }
  2143. }
  2144. slice_type = get_ue_golomb_31(&s->gb);
  2145. if (slice_type > 9) {
  2146. av_log(h->s.avctx, AV_LOG_ERROR,
  2147. "slice type too large (%d) at %d %d\n",
  2148. slice_type, s->mb_x, s->mb_y);
  2149. return -1;
  2150. }
  2151. if (slice_type > 4) {
  2152. slice_type -= 5;
  2153. h->slice_type_fixed = 1;
  2154. } else
  2155. h->slice_type_fixed = 0;
  2156. slice_type = golomb_to_pict_type[slice_type];
  2157. if (slice_type == AV_PICTURE_TYPE_I ||
  2158. (h0->current_slice != 0 && slice_type == h0->last_slice_type)) {
  2159. default_ref_list_done = 1;
  2160. }
  2161. h->slice_type = slice_type;
  2162. h->slice_type_nos = slice_type & 3;
  2163. // to make a few old functions happy, it's wrong though
  2164. s->pict_type = h->slice_type;
  2165. pps_id = get_ue_golomb(&s->gb);
  2166. if (pps_id >= MAX_PPS_COUNT) {
  2167. av_log(h->s.avctx, AV_LOG_ERROR, "pps_id %d out of range\n", pps_id);
  2168. return -1;
  2169. }
  2170. if (!h0->pps_buffers[pps_id]) {
  2171. av_log(h->s.avctx, AV_LOG_ERROR,
  2172. "non-existing PPS %u referenced\n",
  2173. pps_id);
  2174. return -1;
  2175. }
  2176. h->pps = *h0->pps_buffers[pps_id];
  2177. if (!h0->sps_buffers[h->pps.sps_id]) {
  2178. av_log(h->s.avctx, AV_LOG_ERROR,
  2179. "non-existing SPS %u referenced\n",
  2180. h->pps.sps_id);
  2181. return -1;
  2182. }
  2183. h->sps = *h0->sps_buffers[h->pps.sps_id];
  2184. s->avctx->profile = ff_h264_get_profile(&h->sps);
  2185. s->avctx->level = h->sps.level_idc;
  2186. s->avctx->refs = h->sps.ref_frame_count;
  2187. must_reinit = (s->context_initialized &&
  2188. ( 16*h->sps.mb_width != s->avctx->coded_width
  2189. || 16*h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) != s->avctx->coded_height
  2190. || s->avctx->bits_per_raw_sample != h->sps.bit_depth_luma
  2191. || h->cur_chroma_format_idc != h->sps.chroma_format_idc
  2192. || av_cmp_q(h->sps.sar, s->avctx->sample_aspect_ratio)));
  2193. if(must_reinit && (h != h0 || (s->avctx->active_thread_type & FF_THREAD_FRAME))) {
  2194. av_log_missing_feature(s->avctx,
  2195. "Width/height/bit depth/chroma idc changing with threads", 0);
  2196. return AVERROR_PATCHWELCOME; // width / height changed during parallelized decoding
  2197. }
  2198. s->mb_width = h->sps.mb_width;
  2199. s->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
  2200. h->b_stride = s->mb_width * 4;
  2201. s->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
  2202. s->width = 16 * s->mb_width;
  2203. s->height = 16 * s->mb_height;
  2204. if(must_reinit) {
  2205. free_tables(h, 0);
  2206. flush_dpb(s->avctx);
  2207. ff_MPV_common_end(s);
  2208. h->list_count = 0;
  2209. h->current_slice = 0;
  2210. }
  2211. if (!s->context_initialized) {
  2212. if (h != h0) {
  2213. av_log(h->s.avctx, AV_LOG_ERROR,
  2214. "Cannot (re-)initialize context during parallel decoding.\n");
  2215. return -1;
  2216. }
  2217. if( FFALIGN(s->avctx->width , 16 ) == s->width
  2218. && FFALIGN(s->avctx->height, 16*(2 - h->sps.frame_mbs_only_flag)) == s->height
  2219. && !h->sps.crop_right && !h->sps.crop_bottom
  2220. && (s->avctx->width != s->width || s->avctx->height && s->height)
  2221. ) {
  2222. av_log(h->s.avctx, AV_LOG_DEBUG, "Using externally provided dimensions\n");
  2223. s->avctx->coded_width = s->width;
  2224. s->avctx->coded_height = s->height;
  2225. } else{
  2226. avcodec_set_dimensions(s->avctx, s->width, s->height);
  2227. s->avctx->width -= (2>>CHROMA444)*FFMIN(h->sps.crop_right, (8<<CHROMA444)-1);
  2228. s->avctx->height -= (1<<s->chroma_y_shift)*FFMIN(h->sps.crop_bottom, (16>>s->chroma_y_shift)-1) * (2 - h->sps.frame_mbs_only_flag);
  2229. }
  2230. s->avctx->sample_aspect_ratio = h->sps.sar;
  2231. av_assert0(s->avctx->sample_aspect_ratio.den);
  2232. if (s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU
  2233. && (h->sps.bit_depth_luma != 8 ||
  2234. h->sps.chroma_format_idc > 1)) {
  2235. av_log(s->avctx, AV_LOG_ERROR,
  2236. "VDPAU decoding does not support video "
  2237. "colorspace\n");
  2238. return -1;
  2239. }
  2240. if (s->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
  2241. h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
  2242. if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 14 && h->sps.bit_depth_luma != 11 && h->sps.bit_depth_luma != 13 &&
  2243. (h->sps.bit_depth_luma != 9 || !CHROMA422)) {
  2244. s->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
  2245. h->cur_chroma_format_idc = h->sps.chroma_format_idc;
  2246. h->pixel_shift = h->sps.bit_depth_luma > 8;
  2247. ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma, h->sps.chroma_format_idc);
  2248. ff_h264_pred_init(&h->hpc, s->codec_id, h->sps.bit_depth_luma, h->sps.chroma_format_idc);
  2249. s->dsp.dct_bits = h->sps.bit_depth_luma > 8 ? 32 : 16;
  2250. ff_dsputil_init(&s->dsp, s->avctx);
  2251. } else {
  2252. av_log(s->avctx, AV_LOG_ERROR, "Unsupported bit depth: %d chroma_idc: %d\n",
  2253. h->sps.bit_depth_luma, h->sps.chroma_format_idc);
  2254. return -1;
  2255. }
  2256. }
  2257. if (h->sps.video_signal_type_present_flag) {
  2258. s->avctx->color_range = h->sps.full_range>0 ? AVCOL_RANGE_JPEG
  2259. : AVCOL_RANGE_MPEG;
  2260. if (h->sps.colour_description_present_flag) {
  2261. s->avctx->color_primaries = h->sps.color_primaries;
  2262. s->avctx->color_trc = h->sps.color_trc;
  2263. s->avctx->colorspace = h->sps.colorspace;
  2264. }
  2265. }
  2266. if (h->sps.timing_info_present_flag) {
  2267. int64_t den = h->sps.time_scale;
  2268. if (h->x264_build < 44U)
  2269. den *= 2;
  2270. av_reduce(&s->avctx->time_base.num, &s->avctx->time_base.den,
  2271. h->sps.num_units_in_tick, den, 1 << 30);
  2272. }
  2273. switch (h->sps.bit_depth_luma) {
  2274. case 9:
  2275. if (CHROMA444) {
  2276. if (s->avctx->colorspace == AVCOL_SPC_RGB) {
  2277. s->avctx->pix_fmt = AV_PIX_FMT_GBRP9;
  2278. } else
  2279. s->avctx->pix_fmt = AV_PIX_FMT_YUV444P9;
  2280. } else if (CHROMA422)
  2281. s->avctx->pix_fmt = AV_PIX_FMT_YUV422P9;
  2282. else
  2283. s->avctx->pix_fmt = AV_PIX_FMT_YUV420P9;
  2284. break;
  2285. case 10:
  2286. if (CHROMA444) {
  2287. if (s->avctx->colorspace == AVCOL_SPC_RGB) {
  2288. s->avctx->pix_fmt = AV_PIX_FMT_GBRP10;
  2289. } else
  2290. s->avctx->pix_fmt = AV_PIX_FMT_YUV444P10;
  2291. } else if (CHROMA422)
  2292. s->avctx->pix_fmt = AV_PIX_FMT_YUV422P10;
  2293. else
  2294. s->avctx->pix_fmt = AV_PIX_FMT_YUV420P10;
  2295. break;
  2296. case 12:
  2297. if (CHROMA444) {
  2298. if (s->avctx->colorspace == AVCOL_SPC_RGB) {
  2299. s->avctx->pix_fmt = AV_PIX_FMT_GBRP12;
  2300. } else
  2301. s->avctx->pix_fmt = AV_PIX_FMT_YUV444P12;
  2302. } else if (CHROMA422)
  2303. s->avctx->pix_fmt = AV_PIX_FMT_YUV422P12;
  2304. else
  2305. s->avctx->pix_fmt = AV_PIX_FMT_YUV420P12;
  2306. break;
  2307. case 14:
  2308. if (CHROMA444) {
  2309. if (s->avctx->colorspace == AVCOL_SPC_RGB) {
  2310. s->avctx->pix_fmt = AV_PIX_FMT_GBRP14;
  2311. } else
  2312. s->avctx->pix_fmt = AV_PIX_FMT_YUV444P14;
  2313. } else if (CHROMA422)
  2314. s->avctx->pix_fmt = AV_PIX_FMT_YUV422P14;
  2315. else
  2316. s->avctx->pix_fmt = AV_PIX_FMT_YUV420P14;
  2317. break;
  2318. case 8:
  2319. if (CHROMA444) {
  2320. s->avctx->pix_fmt = s->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ444P
  2321. : AV_PIX_FMT_YUV444P;
  2322. if (s->avctx->colorspace == AVCOL_SPC_RGB) {
  2323. s->avctx->pix_fmt = AV_PIX_FMT_GBR24P;
  2324. av_log(h->s.avctx, AV_LOG_DEBUG, "Detected GBR colorspace.\n");
  2325. } else if (s->avctx->colorspace == AVCOL_SPC_YCGCO) {
  2326. av_log(h->s.avctx, AV_LOG_WARNING, "Detected unsupported YCgCo colorspace.\n");
  2327. }
  2328. } else if (CHROMA422) {
  2329. s->avctx->pix_fmt = s->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ422P
  2330. : AV_PIX_FMT_YUV422P;
  2331. } else {
  2332. s->avctx->pix_fmt = s->avctx->get_format(s->avctx,
  2333. s->avctx->codec->pix_fmts ?
  2334. s->avctx->codec->pix_fmts :
  2335. s->avctx->color_range == AVCOL_RANGE_JPEG ?
  2336. hwaccel_pixfmt_list_h264_jpeg_420 :
  2337. ff_hwaccel_pixfmt_list_420);
  2338. }
  2339. break;
  2340. default:
  2341. av_log(s->avctx, AV_LOG_ERROR,
  2342. "Unsupported bit depth: %d\n", h->sps.bit_depth_luma);
  2343. return AVERROR_INVALIDDATA;
  2344. }
  2345. s->avctx->hwaccel = ff_find_hwaccel(s->avctx->codec->id,
  2346. s->avctx->pix_fmt);
  2347. if (ff_MPV_common_init(s) < 0) {
  2348. av_log(h->s.avctx, AV_LOG_ERROR, "ff_MPV_common_init() failed.\n");
  2349. return -1;
  2350. }
  2351. s->first_field = 0;
  2352. h->prev_interlaced_frame = 1;
  2353. init_scan_tables(h);
  2354. if (ff_h264_alloc_tables(h) < 0) {
  2355. av_log(h->s.avctx, AV_LOG_ERROR,
  2356. "Could not allocate memory for h264\n");
  2357. return AVERROR(ENOMEM);
  2358. }
  2359. h->bipred_scratchpad = NULL;
  2360. if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_SLICE)) {
  2361. if (context_init(h) < 0) {
  2362. av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed.\n");
  2363. return -1;
  2364. }
  2365. } else {
  2366. for (i = 1; i < s->slice_context_count; i++) {
  2367. H264Context *c;
  2368. c = h->thread_context[i] = av_malloc(sizeof(H264Context));
  2369. memcpy(c, h->s.thread_context[i], sizeof(MpegEncContext));
  2370. memset(&c->s + 1, 0, sizeof(H264Context) - sizeof(MpegEncContext));
  2371. c->h264dsp = h->h264dsp;
  2372. c->sps = h->sps;
  2373. c->pps = h->pps;
  2374. c->pixel_shift = h->pixel_shift;
  2375. c->cur_chroma_format_idc = h->cur_chroma_format_idc;
  2376. init_scan_tables(c);
  2377. clone_tables(c, h, i);
  2378. }
  2379. for (i = 0; i < s->slice_context_count; i++)
  2380. if (context_init(h->thread_context[i]) < 0) {
  2381. av_log(h->s.avctx, AV_LOG_ERROR,
  2382. "context_init() failed.\n");
  2383. return -1;
  2384. }
  2385. }
  2386. }
  2387. if (h == h0 && h->dequant_coeff_pps != pps_id) {
  2388. h->dequant_coeff_pps = pps_id;
  2389. init_dequant_tables(h);
  2390. }
  2391. h->frame_num = get_bits(&s->gb, h->sps.log2_max_frame_num);
  2392. h->mb_mbaff = 0;
  2393. h->mb_aff_frame = 0;
  2394. last_pic_structure = s0->picture_structure;
  2395. last_pic_droppable = s0->droppable;
  2396. s->droppable = h->nal_ref_idc == 0;
  2397. if (h->sps.frame_mbs_only_flag) {
  2398. s->picture_structure = PICT_FRAME;
  2399. } else {
  2400. if (!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B) {
  2401. av_log(h->s.avctx, AV_LOG_ERROR, "This stream was generated by a broken encoder, invalid 8x8 inference\n");
  2402. return -1;
  2403. }
  2404. if (get_bits1(&s->gb)) { // field_pic_flag
  2405. s->picture_structure = PICT_TOP_FIELD + get_bits1(&s->gb); // bottom_field_flag
  2406. } else {
  2407. s->picture_structure = PICT_FRAME;
  2408. h->mb_aff_frame = h->sps.mb_aff;
  2409. }
  2410. }
  2411. h->mb_field_decoding_flag = s->picture_structure != PICT_FRAME;
  2412. if (h0->current_slice != 0) {
  2413. if (last_pic_structure != s->picture_structure ||
  2414. last_pic_droppable != s->droppable) {
  2415. av_log(h->s.avctx, AV_LOG_ERROR,
  2416. "Changing field mode (%d -> %d) between slices is not allowed\n",
  2417. last_pic_structure, s->picture_structure);
  2418. s->picture_structure = last_pic_structure;
  2419. s->droppable = last_pic_droppable;
  2420. return AVERROR_INVALIDDATA;
  2421. } else if (!s0->current_picture_ptr) {
  2422. av_log(s->avctx, AV_LOG_ERROR,
  2423. "unset current_picture_ptr on %d. slice\n",
  2424. h0->current_slice + 1);
  2425. return AVERROR_INVALIDDATA;
  2426. }
  2427. } else {
  2428. /* Shorten frame num gaps so we don't have to allocate reference
  2429. * frames just to throw them away */
  2430. if (h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0) {
  2431. int unwrap_prev_frame_num = h->prev_frame_num;
  2432. int max_frame_num = 1 << h->sps.log2_max_frame_num;
  2433. if (unwrap_prev_frame_num > h->frame_num)
  2434. unwrap_prev_frame_num -= max_frame_num;
  2435. if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
  2436. unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
  2437. if (unwrap_prev_frame_num < 0)
  2438. unwrap_prev_frame_num += max_frame_num;
  2439. h->prev_frame_num = unwrap_prev_frame_num;
  2440. }
  2441. }
  2442. /* See if we have a decoded first field looking for a pair...
  2443. * Here, we're using that to see if we should mark previously
  2444. * decode frames as "finished".
  2445. * We have to do that before the "dummy" in-between frame allocation,
  2446. * since that can modify s->current_picture_ptr. */
  2447. if (s0->first_field) {
  2448. assert(s0->current_picture_ptr);
  2449. assert(s0->current_picture_ptr->f.data[0]);
  2450. assert(s0->current_picture_ptr->f.reference != DELAYED_PIC_REF);
  2451. /* Mark old field/frame as completed */
  2452. if (!last_pic_droppable && s0->current_picture_ptr->owner2 == s0) {
  2453. ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
  2454. last_pic_structure == PICT_BOTTOM_FIELD);
  2455. }
  2456. /* figure out if we have a complementary field pair */
  2457. if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
  2458. /* Previous field is unmatched. Don't display it, but let it
  2459. * remain for reference if marked as such. */
  2460. if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
  2461. ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
  2462. last_pic_structure == PICT_TOP_FIELD);
  2463. }
  2464. } else {
  2465. if (s0->current_picture_ptr->frame_num != h->frame_num) {
  2466. /* This and previous field were reference, but had
  2467. * different frame_nums. Consider this field first in
  2468. * pair. Throw away previous field except for reference
  2469. * purposes. */
  2470. if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
  2471. ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
  2472. last_pic_structure == PICT_TOP_FIELD);
  2473. }
  2474. } else {
  2475. /* Second field in complementary pair */
  2476. if (!((last_pic_structure == PICT_TOP_FIELD &&
  2477. s->picture_structure == PICT_BOTTOM_FIELD) ||
  2478. (last_pic_structure == PICT_BOTTOM_FIELD &&
  2479. s->picture_structure == PICT_TOP_FIELD))) {
  2480. av_log(s->avctx, AV_LOG_ERROR,
  2481. "Invalid field mode combination %d/%d\n",
  2482. last_pic_structure, s->picture_structure);
  2483. s->picture_structure = last_pic_structure;
  2484. s->droppable = last_pic_droppable;
  2485. return AVERROR_INVALIDDATA;
  2486. } else if (last_pic_droppable != s->droppable) {
  2487. av_log(s->avctx, AV_LOG_ERROR,
  2488. "Cannot combine reference and non-reference fields in the same frame\n");
  2489. av_log_ask_for_sample(s->avctx, NULL);
  2490. s->picture_structure = last_pic_structure;
  2491. s->droppable = last_pic_droppable;
  2492. return AVERROR_INVALIDDATA;
  2493. }
  2494. /* Take ownership of this buffer. Note that if another thread owned
  2495. * the first field of this buffer, we're not operating on that pointer,
  2496. * so the original thread is still responsible for reporting progress
  2497. * on that first field (or if that was us, we just did that above).
  2498. * By taking ownership, we assign responsibility to ourselves to
  2499. * report progress on the second field. */
  2500. s0->current_picture_ptr->owner2 = s0;
  2501. }
  2502. }
  2503. }
  2504. while (h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0 &&
  2505. h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
  2506. Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
  2507. av_log(h->s.avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
  2508. h->frame_num, h->prev_frame_num);
  2509. if (ff_h264_frame_start(h) < 0)
  2510. return -1;
  2511. h->prev_frame_num++;
  2512. h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;
  2513. s->current_picture_ptr->frame_num = h->prev_frame_num;
  2514. ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX, 0);
  2515. ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX, 1);
  2516. ff_generate_sliding_window_mmcos(h);
  2517. if (ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index) < 0 &&
  2518. (s->avctx->err_recognition & AV_EF_EXPLODE))
  2519. return AVERROR_INVALIDDATA;
  2520. /* Error concealment: if a ref is missing, copy the previous ref in its place.
  2521. * FIXME: avoiding a memcpy would be nice, but ref handling makes many assumptions
  2522. * about there being no actual duplicates.
  2523. * FIXME: this doesn't copy padding for out-of-frame motion vectors. Given we're
  2524. * concealing a lost frame, this probably isn't noticeable by comparison, but it should
  2525. * be fixed. */
  2526. if (h->short_ref_count) {
  2527. if (prev) {
  2528. av_image_copy(h->short_ref[0]->f.data, h->short_ref[0]->f.linesize,
  2529. (const uint8_t **)prev->f.data, prev->f.linesize,
  2530. s->avctx->pix_fmt, s->mb_width * 16, s->mb_height * 16);
  2531. h->short_ref[0]->poc = prev->poc + 2;
  2532. }
  2533. h->short_ref[0]->frame_num = h->prev_frame_num;
  2534. }
  2535. }
  2536. /* See if we have a decoded first field looking for a pair...
  2537. * We're using that to see whether to continue decoding in that
  2538. * frame, or to allocate a new one. */
  2539. if (s0->first_field) {
  2540. assert(s0->current_picture_ptr);
  2541. assert(s0->current_picture_ptr->f.data[0]);
  2542. assert(s0->current_picture_ptr->f.reference != DELAYED_PIC_REF);
  2543. /* figure out if we have a complementary field pair */
  2544. if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
  2545. /* Previous field is unmatched. Don't display it, but let it
  2546. * remain for reference if marked as such. */
  2547. s0->current_picture_ptr = NULL;
  2548. s0->first_field = FIELD_PICTURE;
  2549. } else {
  2550. if (s0->current_picture_ptr->frame_num != h->frame_num) {
  2551. ff_thread_report_progress((AVFrame*)s0->current_picture_ptr, INT_MAX,
  2552. s0->picture_structure==PICT_BOTTOM_FIELD);
  2553. /* This and the previous field had different frame_nums.
  2554. * Consider this field first in pair. Throw away previous
  2555. * one except for reference purposes. */
  2556. s0->first_field = 1;
  2557. s0->current_picture_ptr = NULL;
  2558. } else {
  2559. /* Second field in complementary pair */
  2560. s0->first_field = 0;
  2561. }
  2562. }
  2563. } else {
  2564. /* Frame or first field in a potentially complementary pair */
  2565. s0->first_field = FIELD_PICTURE;
  2566. }
  2567. if (!FIELD_PICTURE || s0->first_field) {
  2568. if (ff_h264_frame_start(h) < 0) {
  2569. s0->first_field = 0;
  2570. return -1;
  2571. }
  2572. } else {
  2573. ff_release_unused_pictures(s, 0);
  2574. }
  2575. }
  2576. if (h != h0)
  2577. clone_slice(h, h0);
  2578. s->current_picture_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
  2579. av_assert1(s->mb_num == s->mb_width * s->mb_height);
  2580. if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= s->mb_num ||
  2581. first_mb_in_slice >= s->mb_num) {
  2582. av_log(h->s.avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
  2583. return -1;
  2584. }
  2585. s->resync_mb_x = s->mb_x = first_mb_in_slice % s->mb_width;
  2586. s->resync_mb_y = s->mb_y = (first_mb_in_slice / s->mb_width) << FIELD_OR_MBAFF_PICTURE;
  2587. if (s->picture_structure == PICT_BOTTOM_FIELD)
  2588. s->resync_mb_y = s->mb_y = s->mb_y + 1;
  2589. av_assert1(s->mb_y < s->mb_height);
  2590. if (s->picture_structure == PICT_FRAME) {
  2591. h->curr_pic_num = h->frame_num;
  2592. h->max_pic_num = 1 << h->sps.log2_max_frame_num;
  2593. } else {
  2594. h->curr_pic_num = 2 * h->frame_num + 1;
  2595. h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1);
  2596. }
  2597. if (h->nal_unit_type == NAL_IDR_SLICE)
  2598. get_ue_golomb(&s->gb); /* idr_pic_id */
  2599. if (h->sps.poc_type == 0) {
  2600. h->poc_lsb = get_bits(&s->gb, h->sps.log2_max_poc_lsb);
  2601. if (h->pps.pic_order_present == 1 && s->picture_structure == PICT_FRAME)
  2602. h->delta_poc_bottom = get_se_golomb(&s->gb);
  2603. }
  2604. if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {
  2605. h->delta_poc[0] = get_se_golomb(&s->gb);
  2606. if (h->pps.pic_order_present == 1 && s->picture_structure == PICT_FRAME)
  2607. h->delta_poc[1] = get_se_golomb(&s->gb);
  2608. }
  2609. init_poc(h);
  2610. if (h->pps.redundant_pic_cnt_present)
  2611. h->redundant_pic_count = get_ue_golomb(&s->gb);
  2612. // set defaults, might be overridden a few lines later
  2613. h->ref_count[0] = h->pps.ref_count[0];
  2614. h->ref_count[1] = h->pps.ref_count[1];
  2615. if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
  2616. unsigned max[2];
  2617. max[0] = max[1] = s->picture_structure == PICT_FRAME ? 15 : 31;
  2618. if (h->slice_type_nos == AV_PICTURE_TYPE_B)
  2619. h->direct_spatial_mv_pred = get_bits1(&s->gb);
  2620. num_ref_idx_active_override_flag = get_bits1(&s->gb);
  2621. if (num_ref_idx_active_override_flag) {
  2622. h->ref_count[0] = get_ue_golomb(&s->gb) + 1;
  2623. if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
  2624. h->ref_count[1] = get_ue_golomb(&s->gb) + 1;
  2625. } else
  2626. // full range is spec-ok in this case, even for frames
  2627. h->ref_count[1] = 1;
  2628. }
  2629. if (h->ref_count[0]-1 > max[0] || h->ref_count[1]-1 > max[1]){
  2630. av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow %u > %u or %u > %u\n", h->ref_count[0]-1, max[0], h->ref_count[1]-1, max[1]);
  2631. h->ref_count[0] = h->ref_count[1] = 1;
  2632. return AVERROR_INVALIDDATA;
  2633. }
  2634. if (h->slice_type_nos == AV_PICTURE_TYPE_B)
  2635. h->list_count = 2;
  2636. else
  2637. h->list_count = 1;
  2638. } else
  2639. h->ref_count[1]= h->ref_count[0]= h->list_count= 0;
  2640. if (!default_ref_list_done)
  2641. ff_h264_fill_default_ref_list(h);
  2642. if (h->slice_type_nos != AV_PICTURE_TYPE_I &&
  2643. ff_h264_decode_ref_pic_list_reordering(h) < 0) {
  2644. h->ref_count[1] = h->ref_count[0] = 0;
  2645. return -1;
  2646. }
  2647. if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
  2648. s->last_picture_ptr = &h->ref_list[0][0];
  2649. s->last_picture_ptr->owner2 = s;
  2650. ff_copy_picture(&s->last_picture, s->last_picture_ptr);
  2651. }
  2652. if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
  2653. s->next_picture_ptr = &h->ref_list[1][0];
  2654. s->next_picture_ptr->owner2 = s;
  2655. ff_copy_picture(&s->next_picture, s->next_picture_ptr);
  2656. }
  2657. if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||
  2658. (h->pps.weighted_bipred_idc == 1 &&
  2659. h->slice_type_nos == AV_PICTURE_TYPE_B))
  2660. pred_weight_table(h);
  2661. else if (h->pps.weighted_bipred_idc == 2 &&
  2662. h->slice_type_nos == AV_PICTURE_TYPE_B) {
  2663. implicit_weight_table(h, -1);
  2664. } else {
  2665. h->use_weight = 0;
  2666. for (i = 0; i < 2; i++) {
  2667. h->luma_weight_flag[i] = 0;
  2668. h->chroma_weight_flag[i] = 0;
  2669. }
  2670. }
  2671. if (h->nal_ref_idc && ff_h264_decode_ref_pic_marking(h0, &s->gb) < 0 &&
  2672. (s->avctx->err_recognition & AV_EF_EXPLODE))
  2673. return AVERROR_INVALIDDATA;
  2674. if (FRAME_MBAFF) {
  2675. ff_h264_fill_mbaff_ref_list(h);
  2676. if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) {
  2677. implicit_weight_table(h, 0);
  2678. implicit_weight_table(h, 1);
  2679. }
  2680. }
  2681. if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
  2682. ff_h264_direct_dist_scale_factor(h);
  2683. ff_h264_direct_ref_list_init(h);
  2684. if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {
  2685. tmp = get_ue_golomb_31(&s->gb);
  2686. if (tmp > 2) {
  2687. av_log(s->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
  2688. return -1;
  2689. }
  2690. h->cabac_init_idc = tmp;
  2691. }
  2692. h->last_qscale_diff = 0;
  2693. tmp = h->pps.init_qp + get_se_golomb(&s->gb);
  2694. if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {
  2695. av_log(s->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
  2696. return -1;
  2697. }
  2698. s->qscale = tmp;
  2699. h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
  2700. h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
  2701. // FIXME qscale / qp ... stuff
  2702. if (h->slice_type == AV_PICTURE_TYPE_SP)
  2703. get_bits1(&s->gb); /* sp_for_switch_flag */
  2704. if (h->slice_type == AV_PICTURE_TYPE_SP ||
  2705. h->slice_type == AV_PICTURE_TYPE_SI)
  2706. get_se_golomb(&s->gb); /* slice_qs_delta */
  2707. h->deblocking_filter = 1;
  2708. h->slice_alpha_c0_offset = 52;
  2709. h->slice_beta_offset = 52;
  2710. if (h->pps.deblocking_filter_parameters_present) {
  2711. tmp = get_ue_golomb_31(&s->gb);
  2712. if (tmp > 2) {
  2713. av_log(s->avctx, AV_LOG_ERROR,
  2714. "deblocking_filter_idc %u out of range\n", tmp);
  2715. return -1;
  2716. }
  2717. h->deblocking_filter = tmp;
  2718. if (h->deblocking_filter < 2)
  2719. h->deblocking_filter ^= 1; // 1<->0
  2720. if (h->deblocking_filter) {
  2721. h->slice_alpha_c0_offset += get_se_golomb(&s->gb) << 1;
  2722. h->slice_beta_offset += get_se_golomb(&s->gb) << 1;
  2723. if (h->slice_alpha_c0_offset > 104U ||
  2724. h->slice_beta_offset > 104U) {
  2725. av_log(s->avctx, AV_LOG_ERROR,
  2726. "deblocking filter parameters %d %d out of range\n",
  2727. h->slice_alpha_c0_offset, h->slice_beta_offset);
  2728. return -1;
  2729. }
  2730. }
  2731. }
  2732. if (s->avctx->skip_loop_filter >= AVDISCARD_ALL ||
  2733. (s->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
  2734. h->slice_type_nos != AV_PICTURE_TYPE_I) ||
  2735. (s->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&
  2736. h->slice_type_nos == AV_PICTURE_TYPE_B) ||
  2737. (s->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
  2738. h->nal_ref_idc == 0))
  2739. h->deblocking_filter = 0;
  2740. if (h->deblocking_filter == 1 && h0->max_contexts > 1) {
  2741. if (s->avctx->flags2 & CODEC_FLAG2_FAST) {
  2742. /* Cheat slightly for speed:
  2743. * Do not bother to deblock across slices. */
  2744. h->deblocking_filter = 2;
  2745. } else {
  2746. h0->max_contexts = 1;
  2747. if (!h0->single_decode_warning) {
  2748. av_log(s->avctx, AV_LOG_INFO,
  2749. "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
  2750. h0->single_decode_warning = 1;
  2751. }
  2752. if (h != h0) {
  2753. av_log(h->s.avctx, AV_LOG_ERROR,
  2754. "Deblocking switched inside frame.\n");
  2755. return 1;
  2756. }
  2757. }
  2758. }
  2759. h->qp_thresh = 15 + 52 -
  2760. FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) -
  2761. FFMAX3(0,
  2762. h->pps.chroma_qp_index_offset[0],
  2763. h->pps.chroma_qp_index_offset[1]) +
  2764. 6 * (h->sps.bit_depth_luma - 8);
  2765. h0->last_slice_type = slice_type;
  2766. h->slice_num = ++h0->current_slice;
  2767. if (h->slice_num)
  2768. h0->slice_row[(h->slice_num-1)&(MAX_SLICES-1)]= s->resync_mb_y;
  2769. if ( h0->slice_row[h->slice_num&(MAX_SLICES-1)] + 3 >= s->resync_mb_y
  2770. && h0->slice_row[h->slice_num&(MAX_SLICES-1)] <= s->resync_mb_y
  2771. && h->slice_num >= MAX_SLICES) {
  2772. //in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case
  2773. av_log(s->avctx, AV_LOG_WARNING, "Possibly too many slices (%d >= %d), increase MAX_SLICES and recompile if there are artifacts\n", h->slice_num, MAX_SLICES);
  2774. }
  2775. for (j = 0; j < 2; j++) {
  2776. int id_list[16];
  2777. int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j];
  2778. for (i = 0; i < 16; i++) {
  2779. id_list[i] = 60;
  2780. if (h->ref_list[j][i].f.data[0]) {
  2781. int k;
  2782. uint8_t *base = h->ref_list[j][i].f.base[0];
  2783. for (k = 0; k < h->short_ref_count; k++)
  2784. if (h->short_ref[k]->f.base[0] == base) {
  2785. id_list[i] = k;
  2786. break;
  2787. }
  2788. for (k = 0; k < h->long_ref_count; k++)
  2789. if (h->long_ref[k] && h->long_ref[k]->f.base[0] == base) {
  2790. id_list[i] = h->short_ref_count + k;
  2791. break;
  2792. }
  2793. }
  2794. }
  2795. ref2frm[0] =
  2796. ref2frm[1] = -1;
  2797. for (i = 0; i < 16; i++)
  2798. ref2frm[i + 2] = 4 * id_list[i] +
  2799. (h->ref_list[j][i].f.reference & 3);
  2800. ref2frm[18 + 0] =
  2801. ref2frm[18 + 1] = -1;
  2802. for (i = 16; i < 48; i++)
  2803. ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
  2804. (h->ref_list[j][i].f.reference & 3);
  2805. }
  2806. // FIXME: fix draw_edges + PAFF + frame threads
  2807. h->emu_edge_width = (s->flags & CODEC_FLAG_EMU_EDGE ||
  2808. (!h->sps.frame_mbs_only_flag &&
  2809. s->avctx->active_thread_type))
  2810. ? 0 : 16;
  2811. h->emu_edge_height = (FRAME_MBAFF || FIELD_PICTURE) ? 0 : h->emu_edge_width;
  2812. if (s->avctx->debug & FF_DEBUG_PICT_INFO) {
  2813. av_log(h->s.avctx, AV_LOG_DEBUG,
  2814. "slice:%d %s mb:%d %c%s%s pps:%u frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d:%d:%d weight:%d%s %s\n",
  2815. h->slice_num,
  2816. (s->picture_structure == PICT_FRAME ? "F" : s->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
  2817. first_mb_in_slice,
  2818. av_get_picture_type_char(h->slice_type),
  2819. h->slice_type_fixed ? " fix" : "",
  2820. h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
  2821. pps_id, h->frame_num,
  2822. s->current_picture_ptr->field_poc[0],
  2823. s->current_picture_ptr->field_poc[1],
  2824. h->ref_count[0], h->ref_count[1],
  2825. s->qscale,
  2826. h->deblocking_filter,
  2827. h->slice_alpha_c0_offset / 2 - 26, h->slice_beta_offset / 2 - 26,
  2828. h->use_weight,
  2829. h->use_weight == 1 && h->use_weight_chroma ? "c" : "",
  2830. h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
  2831. }
  2832. return 0;
  2833. }
  2834. int ff_h264_get_slice_type(const H264Context *h)
  2835. {
  2836. switch (h->slice_type) {
  2837. case AV_PICTURE_TYPE_P:
  2838. return 0;
  2839. case AV_PICTURE_TYPE_B:
  2840. return 1;
  2841. case AV_PICTURE_TYPE_I:
  2842. return 2;
  2843. case AV_PICTURE_TYPE_SP:
  2844. return 3;
  2845. case AV_PICTURE_TYPE_SI:
  2846. return 4;
  2847. default:
  2848. return -1;
  2849. }
  2850. }
  2851. static av_always_inline void fill_filter_caches_inter(H264Context *h,
  2852. MpegEncContext *const s,
  2853. int mb_type, int top_xy,
  2854. int left_xy[LEFT_MBS],
  2855. int top_type,
  2856. int left_type[LEFT_MBS],
  2857. int mb_xy, int list)
  2858. {
  2859. int b_stride = h->b_stride;
  2860. int16_t(*mv_dst)[2] = &h->mv_cache[list][scan8[0]];
  2861. int8_t *ref_cache = &h->ref_cache[list][scan8[0]];
  2862. if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
  2863. if (USES_LIST(top_type, list)) {
  2864. const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride;
  2865. const int b8_xy = 4 * top_xy + 2;
  2866. int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2));
  2867. AV_COPY128(mv_dst - 1 * 8, s->current_picture.f.motion_val[list][b_xy + 0]);
  2868. ref_cache[0 - 1 * 8] =
  2869. ref_cache[1 - 1 * 8] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 0]];
  2870. ref_cache[2 - 1 * 8] =
  2871. ref_cache[3 - 1 * 8] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 1]];
  2872. } else {
  2873. AV_ZERO128(mv_dst - 1 * 8);
  2874. AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  2875. }
  2876. if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
  2877. if (USES_LIST(left_type[LTOP], list)) {
  2878. const int b_xy = h->mb2b_xy[left_xy[LTOP]] + 3;
  2879. const int b8_xy = 4 * left_xy[LTOP] + 1;
  2880. int (*ref2frm)[64] =(void*)( h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2));
  2881. AV_COPY32(mv_dst - 1 + 0, s->current_picture.f.motion_val[list][b_xy + b_stride * 0]);
  2882. AV_COPY32(mv_dst - 1 + 8, s->current_picture.f.motion_val[list][b_xy + b_stride * 1]);
  2883. AV_COPY32(mv_dst - 1 + 16, s->current_picture.f.motion_val[list][b_xy + b_stride * 2]);
  2884. AV_COPY32(mv_dst - 1 + 24, s->current_picture.f.motion_val[list][b_xy + b_stride * 3]);
  2885. ref_cache[-1 + 0] =
  2886. ref_cache[-1 + 8] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 2 * 0]];
  2887. ref_cache[-1 + 16] =
  2888. ref_cache[-1 + 24] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 2 * 1]];
  2889. } else {
  2890. AV_ZERO32(mv_dst - 1 + 0);
  2891. AV_ZERO32(mv_dst - 1 + 8);
  2892. AV_ZERO32(mv_dst - 1 + 16);
  2893. AV_ZERO32(mv_dst - 1 + 24);
  2894. ref_cache[-1 + 0] =
  2895. ref_cache[-1 + 8] =
  2896. ref_cache[-1 + 16] =
  2897. ref_cache[-1 + 24] = LIST_NOT_USED;
  2898. }
  2899. }
  2900. }
  2901. if (!USES_LIST(mb_type, list)) {
  2902. fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
  2903. AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  2904. AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  2905. AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  2906. AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  2907. return;
  2908. }
  2909. {
  2910. int8_t *ref = &s->current_picture.f.ref_index[list][4 * mb_xy];
  2911. int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2));
  2912. uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]], ref2frm[list][ref[1]]) & 0x00FF00FF) * 0x0101;
  2913. uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]], ref2frm[list][ref[3]]) & 0x00FF00FF) * 0x0101;
  2914. AV_WN32A(&ref_cache[0 * 8], ref01);
  2915. AV_WN32A(&ref_cache[1 * 8], ref01);
  2916. AV_WN32A(&ref_cache[2 * 8], ref23);
  2917. AV_WN32A(&ref_cache[3 * 8], ref23);
  2918. }
  2919. {
  2920. int16_t(*mv_src)[2] = &s->current_picture.f.motion_val[list][4 * s->mb_x + 4 * s->mb_y * b_stride];
  2921. AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
  2922. AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
  2923. AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
  2924. AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
  2925. }
  2926. }
  2927. /**
  2928. *
  2929. * @return non zero if the loop filter can be skipped
  2930. */
  2931. static int fill_filter_caches(H264Context *h, int mb_type)
  2932. {
  2933. MpegEncContext *const s = &h->s;
  2934. const int mb_xy = h->mb_xy;
  2935. int top_xy, left_xy[LEFT_MBS];
  2936. int top_type, left_type[LEFT_MBS];
  2937. uint8_t *nnz;
  2938. uint8_t *nnz_cache;
  2939. top_xy = mb_xy - (s->mb_stride << MB_FIELD);
  2940. /* Wow, what a mess, why didn't they simplify the interlacing & intra
  2941. * stuff, I can't imagine that these complex rules are worth it. */
  2942. left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
  2943. if (FRAME_MBAFF) {
  2944. const int left_mb_field_flag = IS_INTERLACED(s->current_picture.f.mb_type[mb_xy - 1]);
  2945. const int curr_mb_field_flag = IS_INTERLACED(mb_type);
  2946. if (s->mb_y & 1) {
  2947. if (left_mb_field_flag != curr_mb_field_flag)
  2948. left_xy[LTOP] -= s->mb_stride;
  2949. } else {
  2950. if (curr_mb_field_flag)
  2951. top_xy += s->mb_stride &
  2952. (((s->current_picture.f.mb_type[top_xy] >> 7) & 1) - 1);
  2953. if (left_mb_field_flag != curr_mb_field_flag)
  2954. left_xy[LBOT] += s->mb_stride;
  2955. }
  2956. }
  2957. h->top_mb_xy = top_xy;
  2958. h->left_mb_xy[LTOP] = left_xy[LTOP];
  2959. h->left_mb_xy[LBOT] = left_xy[LBOT];
  2960. {
  2961. /* For sufficiently low qp, filtering wouldn't do anything.
  2962. * This is a conservative estimate: could also check beta_offset
  2963. * and more accurate chroma_qp. */
  2964. int qp_thresh = h->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
  2965. int qp = s->current_picture.f.qscale_table[mb_xy];
  2966. if (qp <= qp_thresh &&
  2967. (left_xy[LTOP] < 0 ||
  2968. ((qp + s->current_picture.f.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
  2969. (top_xy < 0 ||
  2970. ((qp + s->current_picture.f.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
  2971. if (!FRAME_MBAFF)
  2972. return 1;
  2973. if ((left_xy[LTOP] < 0 ||
  2974. ((qp + s->current_picture.f.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
  2975. (top_xy < s->mb_stride ||
  2976. ((qp + s->current_picture.f.qscale_table[top_xy - s->mb_stride] + 1) >> 1) <= qp_thresh))
  2977. return 1;
  2978. }
  2979. }
  2980. top_type = s->current_picture.f.mb_type[top_xy];
  2981. left_type[LTOP] = s->current_picture.f.mb_type[left_xy[LTOP]];
  2982. left_type[LBOT] = s->current_picture.f.mb_type[left_xy[LBOT]];
  2983. if (h->deblocking_filter == 2) {
  2984. if (h->slice_table[top_xy] != h->slice_num)
  2985. top_type = 0;
  2986. if (h->slice_table[left_xy[LBOT]] != h->slice_num)
  2987. left_type[LTOP] = left_type[LBOT] = 0;
  2988. } else {
  2989. if (h->slice_table[top_xy] == 0xFFFF)
  2990. top_type = 0;
  2991. if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
  2992. left_type[LTOP] = left_type[LBOT] = 0;
  2993. }
  2994. h->top_type = top_type;
  2995. h->left_type[LTOP] = left_type[LTOP];
  2996. h->left_type[LBOT] = left_type[LBOT];
  2997. if (IS_INTRA(mb_type))
  2998. return 0;
  2999. fill_filter_caches_inter(h, s, mb_type, top_xy, left_xy,
  3000. top_type, left_type, mb_xy, 0);
  3001. if (h->list_count == 2)
  3002. fill_filter_caches_inter(h, s, mb_type, top_xy, left_xy,
  3003. top_type, left_type, mb_xy, 1);
  3004. nnz = h->non_zero_count[mb_xy];
  3005. nnz_cache = h->non_zero_count_cache;
  3006. AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
  3007. AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
  3008. AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
  3009. AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
  3010. h->cbp = h->cbp_table[mb_xy];
  3011. if (top_type) {
  3012. nnz = h->non_zero_count[top_xy];
  3013. AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
  3014. }
  3015. if (left_type[LTOP]) {
  3016. nnz = h->non_zero_count[left_xy[LTOP]];
  3017. nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
  3018. nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
  3019. nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
  3020. nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
  3021. }
  3022. /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
  3023. * from what the loop filter needs */
  3024. if (!CABAC && h->pps.transform_8x8_mode) {
  3025. if (IS_8x8DCT(top_type)) {
  3026. nnz_cache[4 + 8 * 0] =
  3027. nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
  3028. nnz_cache[6 + 8 * 0] =
  3029. nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
  3030. }
  3031. if (IS_8x8DCT(left_type[LTOP])) {
  3032. nnz_cache[3 + 8 * 1] =
  3033. nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
  3034. }
  3035. if (IS_8x8DCT(left_type[LBOT])) {
  3036. nnz_cache[3 + 8 * 3] =
  3037. nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
  3038. }
  3039. if (IS_8x8DCT(mb_type)) {
  3040. nnz_cache[scan8[0]] =
  3041. nnz_cache[scan8[1]] =
  3042. nnz_cache[scan8[2]] =
  3043. nnz_cache[scan8[3]] = (h->cbp & 0x1000) >> 12;
  3044. nnz_cache[scan8[0 + 4]] =
  3045. nnz_cache[scan8[1 + 4]] =
  3046. nnz_cache[scan8[2 + 4]] =
  3047. nnz_cache[scan8[3 + 4]] = (h->cbp & 0x2000) >> 12;
  3048. nnz_cache[scan8[0 + 8]] =
  3049. nnz_cache[scan8[1 + 8]] =
  3050. nnz_cache[scan8[2 + 8]] =
  3051. nnz_cache[scan8[3 + 8]] = (h->cbp & 0x4000) >> 12;
  3052. nnz_cache[scan8[0 + 12]] =
  3053. nnz_cache[scan8[1 + 12]] =
  3054. nnz_cache[scan8[2 + 12]] =
  3055. nnz_cache[scan8[3 + 12]] = (h->cbp & 0x8000) >> 12;
  3056. }
  3057. }
  3058. return 0;
  3059. }
  3060. static void loop_filter(H264Context *h, int start_x, int end_x)
  3061. {
  3062. MpegEncContext *const s = &h->s;
  3063. uint8_t *dest_y, *dest_cb, *dest_cr;
  3064. int linesize, uvlinesize, mb_x, mb_y;
  3065. const int end_mb_y = s->mb_y + FRAME_MBAFF;
  3066. const int old_slice_type = h->slice_type;
  3067. const int pixel_shift = h->pixel_shift;
  3068. const int block_h = 16 >> s->chroma_y_shift;
  3069. if (h->deblocking_filter) {
  3070. for (mb_x = start_x; mb_x < end_x; mb_x++)
  3071. for (mb_y = end_mb_y - FRAME_MBAFF; mb_y <= end_mb_y; mb_y++) {
  3072. int mb_xy, mb_type;
  3073. mb_xy = h->mb_xy = mb_x + mb_y * s->mb_stride;
  3074. h->slice_num = h->slice_table[mb_xy];
  3075. mb_type = s->current_picture.f.mb_type[mb_xy];
  3076. h->list_count = h->list_counts[mb_xy];
  3077. if (FRAME_MBAFF)
  3078. h->mb_mbaff =
  3079. h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
  3080. s->mb_x = mb_x;
  3081. s->mb_y = mb_y;
  3082. dest_y = s->current_picture.f.data[0] +
  3083. ((mb_x << pixel_shift) + mb_y * s->linesize) * 16;
  3084. dest_cb = s->current_picture.f.data[1] +
  3085. (mb_x << pixel_shift) * (8 << CHROMA444) +
  3086. mb_y * s->uvlinesize * block_h;
  3087. dest_cr = s->current_picture.f.data[2] +
  3088. (mb_x << pixel_shift) * (8 << CHROMA444) +
  3089. mb_y * s->uvlinesize * block_h;
  3090. // FIXME simplify above
  3091. if (MB_FIELD) {
  3092. linesize = h->mb_linesize = s->linesize * 2;
  3093. uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
  3094. if (mb_y & 1) { // FIXME move out of this function?
  3095. dest_y -= s->linesize * 15;
  3096. dest_cb -= s->uvlinesize * (block_h - 1);
  3097. dest_cr -= s->uvlinesize * (block_h - 1);
  3098. }
  3099. } else {
  3100. linesize = h->mb_linesize = s->linesize;
  3101. uvlinesize = h->mb_uvlinesize = s->uvlinesize;
  3102. }
  3103. backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize,
  3104. uvlinesize, 0);
  3105. if (fill_filter_caches(h, mb_type))
  3106. continue;
  3107. h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.f.qscale_table[mb_xy]);
  3108. h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.f.qscale_table[mb_xy]);
  3109. if (FRAME_MBAFF) {
  3110. ff_h264_filter_mb(h, mb_x, mb_y, dest_y, dest_cb, dest_cr,
  3111. linesize, uvlinesize);
  3112. } else {
  3113. ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb,
  3114. dest_cr, linesize, uvlinesize);
  3115. }
  3116. }
  3117. }
  3118. h->slice_type = old_slice_type;
  3119. s->mb_x = end_x;
  3120. s->mb_y = end_mb_y - FRAME_MBAFF;
  3121. h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
  3122. h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
  3123. }
  3124. static void predict_field_decoding_flag(H264Context *h)
  3125. {
  3126. MpegEncContext *const s = &h->s;
  3127. const int mb_xy = s->mb_x + s->mb_y * s->mb_stride;
  3128. int mb_type = (h->slice_table[mb_xy - 1] == h->slice_num) ?
  3129. s->current_picture.f.mb_type[mb_xy - 1] :
  3130. (h->slice_table[mb_xy - s->mb_stride] == h->slice_num) ?
  3131. s->current_picture.f.mb_type[mb_xy - s->mb_stride] : 0;
  3132. h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
  3133. }
  3134. /**
  3135. * Draw edges and report progress for the last MB row.
  3136. */
  3137. static void decode_finish_row(H264Context *h)
  3138. {
  3139. MpegEncContext *const s = &h->s;
  3140. int top = 16 * (s->mb_y >> FIELD_PICTURE);
  3141. int pic_height = 16 * s->mb_height >> FIELD_PICTURE;
  3142. int height = 16 << FRAME_MBAFF;
  3143. int deblock_border = (16 + 4) << FRAME_MBAFF;
  3144. if (h->deblocking_filter) {
  3145. if ((top + height) >= pic_height)
  3146. height += deblock_border;
  3147. top -= deblock_border;
  3148. }
  3149. if (top >= pic_height || (top + height) < h->emu_edge_height)
  3150. return;
  3151. height = FFMIN(height, pic_height - top);
  3152. if (top < h->emu_edge_height) {
  3153. height = top + height;
  3154. top = 0;
  3155. }
  3156. ff_draw_horiz_band(s, top, height);
  3157. if (s->droppable)
  3158. return;
  3159. ff_thread_report_progress(&s->current_picture_ptr->f, top + height - 1,
  3160. s->picture_structure == PICT_BOTTOM_FIELD);
  3161. }
  3162. static int decode_slice(struct AVCodecContext *avctx, void *arg)
  3163. {
  3164. H264Context *h = *(void **)arg;
  3165. MpegEncContext *const s = &h->s;
  3166. const int part_mask = s->partitioned_frame ? (ER_AC_END | ER_AC_ERROR)
  3167. : 0x7F;
  3168. int lf_x_start = s->mb_x;
  3169. s->mb_skip_run = -1;
  3170. h->is_complex = FRAME_MBAFF || s->picture_structure != PICT_FRAME ||
  3171. s->codec_id != AV_CODEC_ID_H264 ||
  3172. (CONFIG_GRAY && (s->flags & CODEC_FLAG_GRAY));
  3173. if (h->pps.cabac) {
  3174. /* realign */
  3175. align_get_bits(&s->gb);
  3176. /* init cabac */
  3177. ff_init_cabac_decoder(&h->cabac,
  3178. s->gb.buffer + get_bits_count(&s->gb) / 8,
  3179. (get_bits_left(&s->gb) + 7) / 8);
  3180. ff_h264_init_cabac_states(h);
  3181. for (;;) {
  3182. // START_TIMER
  3183. int ret = ff_h264_decode_mb_cabac(h);
  3184. int eos;
  3185. // STOP_TIMER("decode_mb_cabac")
  3186. if (ret >= 0)
  3187. ff_h264_hl_decode_mb(h);
  3188. // FIXME optimal? or let mb_decode decode 16x32 ?
  3189. if (ret >= 0 && FRAME_MBAFF) {
  3190. s->mb_y++;
  3191. ret = ff_h264_decode_mb_cabac(h);
  3192. if (ret >= 0)
  3193. ff_h264_hl_decode_mb(h);
  3194. s->mb_y--;
  3195. }
  3196. eos = get_cabac_terminate(&h->cabac);
  3197. if ((s->workaround_bugs & FF_BUG_TRUNCATED) &&
  3198. h->cabac.bytestream > h->cabac.bytestream_end + 2) {
  3199. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x - 1,
  3200. s->mb_y, ER_MB_END & part_mask);
  3201. if (s->mb_x >= lf_x_start)
  3202. loop_filter(h, lf_x_start, s->mb_x + 1);
  3203. return 0;
  3204. }
  3205. if (h->cabac.bytestream > h->cabac.bytestream_end + 2 )
  3206. av_log(h->s.avctx, AV_LOG_DEBUG, "bytestream overread %td\n", h->cabac.bytestream_end - h->cabac.bytestream);
  3207. if (ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 4) {
  3208. av_log(h->s.avctx, AV_LOG_ERROR,
  3209. "error while decoding MB %d %d, bytestream (%td)\n",
  3210. s->mb_x, s->mb_y,
  3211. h->cabac.bytestream_end - h->cabac.bytestream);
  3212. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x,
  3213. s->mb_y, ER_MB_ERROR & part_mask);
  3214. return -1;
  3215. }
  3216. if (++s->mb_x >= s->mb_width) {
  3217. loop_filter(h, lf_x_start, s->mb_x);
  3218. s->mb_x = lf_x_start = 0;
  3219. decode_finish_row(h);
  3220. ++s->mb_y;
  3221. if (FIELD_OR_MBAFF_PICTURE) {
  3222. ++s->mb_y;
  3223. if (FRAME_MBAFF && s->mb_y < s->mb_height)
  3224. predict_field_decoding_flag(h);
  3225. }
  3226. }
  3227. if (eos || s->mb_y >= s->mb_height) {
  3228. tprintf(s->avctx, "slice end %d %d\n",
  3229. get_bits_count(&s->gb), s->gb.size_in_bits);
  3230. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x - 1,
  3231. s->mb_y, ER_MB_END & part_mask);
  3232. if (s->mb_x > lf_x_start)
  3233. loop_filter(h, lf_x_start, s->mb_x);
  3234. return 0;
  3235. }
  3236. }
  3237. } else {
  3238. for (;;) {
  3239. int ret = ff_h264_decode_mb_cavlc(h);
  3240. if (ret >= 0)
  3241. ff_h264_hl_decode_mb(h);
  3242. // FIXME optimal? or let mb_decode decode 16x32 ?
  3243. if (ret >= 0 && FRAME_MBAFF) {
  3244. s->mb_y++;
  3245. ret = ff_h264_decode_mb_cavlc(h);
  3246. if (ret >= 0)
  3247. ff_h264_hl_decode_mb(h);
  3248. s->mb_y--;
  3249. }
  3250. if (ret < 0) {
  3251. av_log(h->s.avctx, AV_LOG_ERROR,
  3252. "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
  3253. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x,
  3254. s->mb_y, ER_MB_ERROR & part_mask);
  3255. return -1;
  3256. }
  3257. if (++s->mb_x >= s->mb_width) {
  3258. loop_filter(h, lf_x_start, s->mb_x);
  3259. s->mb_x = lf_x_start = 0;
  3260. decode_finish_row(h);
  3261. ++s->mb_y;
  3262. if (FIELD_OR_MBAFF_PICTURE) {
  3263. ++s->mb_y;
  3264. if (FRAME_MBAFF && s->mb_y < s->mb_height)
  3265. predict_field_decoding_flag(h);
  3266. }
  3267. if (s->mb_y >= s->mb_height) {
  3268. tprintf(s->avctx, "slice end %d %d\n",
  3269. get_bits_count(&s->gb), s->gb.size_in_bits);
  3270. if ( get_bits_left(&s->gb) == 0
  3271. || get_bits_left(&s->gb) > 0 && !(s->avctx->err_recognition & AV_EF_AGGRESSIVE)) {
  3272. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y,
  3273. s->mb_x - 1, s->mb_y,
  3274. ER_MB_END & part_mask);
  3275. return 0;
  3276. } else {
  3277. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y,
  3278. s->mb_x, s->mb_y,
  3279. ER_MB_END & part_mask);
  3280. return -1;
  3281. }
  3282. }
  3283. }
  3284. if (get_bits_left(&s->gb) <= 0 && s->mb_skip_run <= 0) {
  3285. tprintf(s->avctx, "slice end %d %d\n",
  3286. get_bits_count(&s->gb), s->gb.size_in_bits);
  3287. if (get_bits_left(&s->gb) == 0) {
  3288. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y,
  3289. s->mb_x - 1, s->mb_y,
  3290. ER_MB_END & part_mask);
  3291. if (s->mb_x > lf_x_start)
  3292. loop_filter(h, lf_x_start, s->mb_x);
  3293. return 0;
  3294. } else {
  3295. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x,
  3296. s->mb_y, ER_MB_ERROR & part_mask);
  3297. return -1;
  3298. }
  3299. }
  3300. }
  3301. }
  3302. }
  3303. /**
  3304. * Call decode_slice() for each context.
  3305. *
  3306. * @param h h264 master context
  3307. * @param context_count number of contexts to execute
  3308. */
  3309. static int execute_decode_slices(H264Context *h, int context_count)
  3310. {
  3311. MpegEncContext *const s = &h->s;
  3312. AVCodecContext *const avctx = s->avctx;
  3313. H264Context *hx;
  3314. int i;
  3315. if (s->avctx->hwaccel ||
  3316. s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  3317. return 0;
  3318. if (context_count == 1) {
  3319. return decode_slice(avctx, &h);
  3320. } else {
  3321. for (i = 1; i < context_count; i++) {
  3322. hx = h->thread_context[i];
  3323. hx->s.err_recognition = avctx->err_recognition;
  3324. hx->s.error_count = 0;
  3325. hx->x264_build = h->x264_build;
  3326. }
  3327. avctx->execute(avctx, decode_slice, h->thread_context,
  3328. NULL, context_count, sizeof(void *));
  3329. /* pull back stuff from slices to master context */
  3330. hx = h->thread_context[context_count - 1];
  3331. s->mb_x = hx->s.mb_x;
  3332. s->mb_y = hx->s.mb_y;
  3333. s->droppable = hx->s.droppable;
  3334. s->picture_structure = hx->s.picture_structure;
  3335. for (i = 1; i < context_count; i++)
  3336. h->s.error_count += h->thread_context[i]->s.error_count;
  3337. }
  3338. return 0;
  3339. }
  3340. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size)
  3341. {
  3342. MpegEncContext *const s = &h->s;
  3343. AVCodecContext *const avctx = s->avctx;
  3344. H264Context *hx; ///< thread context
  3345. int buf_index;
  3346. int context_count;
  3347. int next_avc;
  3348. int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);
  3349. int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
  3350. int nal_index;
  3351. int idr_cleared=0;
  3352. h->nal_unit_type= 0;
  3353. if(!s->slice_context_count)
  3354. s->slice_context_count= 1;
  3355. h->max_contexts = s->slice_context_count;
  3356. if (!(s->flags2 & CODEC_FLAG2_CHUNKS)) {
  3357. h->current_slice = 0;
  3358. if (!s->first_field)
  3359. s->current_picture_ptr = NULL;
  3360. ff_h264_reset_sei(h);
  3361. }
  3362. if (h->nal_length_size == 4) {
  3363. if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
  3364. h->is_avc = 0;
  3365. }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
  3366. h->is_avc = 1;
  3367. }
  3368. for (; pass <= 1; pass++) {
  3369. buf_index = 0;
  3370. context_count = 0;
  3371. next_avc = h->is_avc ? 0 : buf_size;
  3372. nal_index = 0;
  3373. for (;;) {
  3374. int consumed;
  3375. int dst_length;
  3376. int bit_length;
  3377. const uint8_t *ptr;
  3378. int i, nalsize = 0;
  3379. int err;
  3380. if (buf_index >= next_avc) {
  3381. if (buf_index >= buf_size - h->nal_length_size)
  3382. break;
  3383. nalsize = 0;
  3384. for (i = 0; i < h->nal_length_size; i++)
  3385. nalsize = (nalsize << 8) | buf[buf_index++];
  3386. if (nalsize <= 0 || nalsize > buf_size - buf_index) {
  3387. av_log(h->s.avctx, AV_LOG_ERROR,
  3388. "AVC: nal size %d\n", nalsize);
  3389. break;
  3390. }
  3391. next_avc = buf_index + nalsize;
  3392. } else {
  3393. // start code prefix search
  3394. for (; buf_index + 3 < next_avc; buf_index++)
  3395. // This should always succeed in the first iteration.
  3396. if (buf[buf_index] == 0 &&
  3397. buf[buf_index + 1] == 0 &&
  3398. buf[buf_index + 2] == 1)
  3399. break;
  3400. if (buf_index + 3 >= buf_size) {
  3401. buf_index = buf_size;
  3402. break;
  3403. }
  3404. buf_index += 3;
  3405. if (buf_index >= next_avc)
  3406. continue;
  3407. }
  3408. hx = h->thread_context[context_count];
  3409. ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
  3410. &consumed, next_avc - buf_index);
  3411. if (ptr == NULL || dst_length < 0) {
  3412. buf_index = -1;
  3413. goto end;
  3414. }
  3415. i = buf_index + consumed;
  3416. if ((s->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
  3417. buf[i] == 0x00 && buf[i + 1] == 0x00 &&
  3418. buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
  3419. s->workaround_bugs |= FF_BUG_TRUNCATED;
  3420. if (!(s->workaround_bugs & FF_BUG_TRUNCATED))
  3421. while(dst_length > 0 && ptr[dst_length - 1] == 0)
  3422. dst_length--;
  3423. bit_length = !dst_length ? 0
  3424. : (8 * dst_length -
  3425. decode_rbsp_trailing(h, ptr + dst_length - 1));
  3426. if (s->avctx->debug & FF_DEBUG_STARTCODE)
  3427. av_log(h->s.avctx, AV_LOG_DEBUG, "NAL %d/%d at %d/%d length %d pass %d\n", hx->nal_unit_type, hx->nal_ref_idc, buf_index, buf_size, dst_length, pass);
  3428. if (h->is_avc && (nalsize != consumed) && nalsize)
  3429. av_log(h->s.avctx, AV_LOG_DEBUG,
  3430. "AVC: Consumed only %d bytes instead of %d\n",
  3431. consumed, nalsize);
  3432. buf_index += consumed;
  3433. nal_index++;
  3434. if (pass == 0) {
  3435. /* packets can sometimes contain multiple PPS/SPS,
  3436. * e.g. two PAFF field pictures in one packet, or a demuxer
  3437. * which splits NALs strangely if so, when frame threading we
  3438. * can't start the next thread until we've read all of them */
  3439. switch (hx->nal_unit_type) {
  3440. case NAL_SPS:
  3441. case NAL_PPS:
  3442. nals_needed = nal_index;
  3443. break;
  3444. case NAL_IDR_SLICE:
  3445. case NAL_SLICE:
  3446. init_get_bits(&hx->s.gb, ptr, bit_length);
  3447. if (!get_ue_golomb(&hx->s.gb))
  3448. nals_needed = nal_index;
  3449. }
  3450. continue;
  3451. }
  3452. // FIXME do not discard SEI id
  3453. if (avctx->skip_frame >= AVDISCARD_NONREF && h->nal_ref_idc == 0)
  3454. continue;
  3455. again:
  3456. err = 0;
  3457. if (h->decoding_extradata) {
  3458. switch (hx->nal_unit_type) {
  3459. case NAL_IDR_SLICE:
  3460. case NAL_SLICE:
  3461. case NAL_DPA:
  3462. case NAL_DPB:
  3463. case NAL_DPC:
  3464. case NAL_AUXILIARY_SLICE:
  3465. av_log(h->s.avctx, AV_LOG_WARNING, "Ignoring NAL %d in global header\n", hx->nal_unit_type);
  3466. hx->nal_unit_type = NAL_FILLER_DATA;
  3467. }
  3468. }
  3469. switch (hx->nal_unit_type) {
  3470. case NAL_IDR_SLICE:
  3471. if (h->nal_unit_type != NAL_IDR_SLICE) {
  3472. av_log(h->s.avctx, AV_LOG_ERROR,
  3473. "Invalid mix of idr and non-idr slices\n");
  3474. buf_index = -1;
  3475. goto end;
  3476. }
  3477. if(!idr_cleared)
  3478. idr(h); // FIXME ensure we don't lose some frames if there is reordering
  3479. idr_cleared = 1;
  3480. case NAL_SLICE:
  3481. init_get_bits(&hx->s.gb, ptr, bit_length);
  3482. hx->intra_gb_ptr =
  3483. hx->inter_gb_ptr = &hx->s.gb;
  3484. hx->s.data_partitioning = 0;
  3485. if ((err = decode_slice_header(hx, h)))
  3486. break;
  3487. if (h->sei_recovery_frame_cnt >= 0 && (h->frame_num != h->sei_recovery_frame_cnt || hx->slice_type_nos != AV_PICTURE_TYPE_I))
  3488. h->valid_recovery_point = 1;
  3489. if ( h->sei_recovery_frame_cnt >= 0
  3490. && ( h->recovery_frame<0
  3491. || ((h->recovery_frame - h->frame_num) & ((1 << h->sps.log2_max_frame_num)-1)) > h->sei_recovery_frame_cnt)) {
  3492. h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) %
  3493. (1 << h->sps.log2_max_frame_num);
  3494. if (!h->valid_recovery_point)
  3495. h->recovery_frame = h->frame_num;
  3496. }
  3497. s->current_picture_ptr->f.key_frame |=
  3498. (hx->nal_unit_type == NAL_IDR_SLICE);
  3499. if (h->recovery_frame == h->frame_num) {
  3500. s->current_picture_ptr->sync |= 1;
  3501. h->recovery_frame = -1;
  3502. }
  3503. h->sync |= !!s->current_picture_ptr->f.key_frame;
  3504. h->sync |= 3*!!(s->flags2 & CODEC_FLAG2_SHOW_ALL);
  3505. s->current_picture_ptr->sync |= h->sync;
  3506. if (h->current_slice == 1) {
  3507. if (!(s->flags2 & CODEC_FLAG2_CHUNKS))
  3508. decode_postinit(h, nal_index >= nals_needed);
  3509. if (s->avctx->hwaccel &&
  3510. s->avctx->hwaccel->start_frame(s->avctx, NULL, 0) < 0)
  3511. return -1;
  3512. if (CONFIG_H264_VDPAU_DECODER &&
  3513. s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  3514. ff_vdpau_h264_picture_start(s);
  3515. }
  3516. if (hx->redundant_pic_count == 0 &&
  3517. (avctx->skip_frame < AVDISCARD_NONREF ||
  3518. hx->nal_ref_idc) &&
  3519. (avctx->skip_frame < AVDISCARD_BIDIR ||
  3520. hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
  3521. (avctx->skip_frame < AVDISCARD_NONKEY ||
  3522. hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
  3523. avctx->skip_frame < AVDISCARD_ALL) {
  3524. if (avctx->hwaccel) {
  3525. if (avctx->hwaccel->decode_slice(avctx,
  3526. &buf[buf_index - consumed],
  3527. consumed) < 0)
  3528. return -1;
  3529. } else if (CONFIG_H264_VDPAU_DECODER &&
  3530. s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
  3531. static const uint8_t start_code[] = {
  3532. 0x00, 0x00, 0x01 };
  3533. ff_vdpau_add_data_chunk(s, start_code,
  3534. sizeof(start_code));
  3535. ff_vdpau_add_data_chunk(s, &buf[buf_index - consumed],
  3536. consumed);
  3537. } else
  3538. context_count++;
  3539. }
  3540. break;
  3541. case NAL_DPA:
  3542. init_get_bits(&hx->s.gb, ptr, bit_length);
  3543. hx->intra_gb_ptr =
  3544. hx->inter_gb_ptr = NULL;
  3545. if ((err = decode_slice_header(hx, h)) < 0)
  3546. break;
  3547. hx->s.data_partitioning = 1;
  3548. break;
  3549. case NAL_DPB:
  3550. init_get_bits(&hx->intra_gb, ptr, bit_length);
  3551. hx->intra_gb_ptr = &hx->intra_gb;
  3552. break;
  3553. case NAL_DPC:
  3554. init_get_bits(&hx->inter_gb, ptr, bit_length);
  3555. hx->inter_gb_ptr = &hx->inter_gb;
  3556. av_log(h->s.avctx, AV_LOG_ERROR, "Partitioned H.264 support is incomplete\n");
  3557. break;
  3558. if (hx->redundant_pic_count == 0 &&
  3559. hx->intra_gb_ptr &&
  3560. hx->s.data_partitioning &&
  3561. s->current_picture_ptr &&
  3562. s->context_initialized &&
  3563. (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
  3564. (avctx->skip_frame < AVDISCARD_BIDIR ||
  3565. hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
  3566. (avctx->skip_frame < AVDISCARD_NONKEY ||
  3567. hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
  3568. avctx->skip_frame < AVDISCARD_ALL)
  3569. context_count++;
  3570. break;
  3571. case NAL_SEI:
  3572. init_get_bits(&s->gb, ptr, bit_length);
  3573. ff_h264_decode_sei(h);
  3574. break;
  3575. case NAL_SPS:
  3576. init_get_bits(&s->gb, ptr, bit_length);
  3577. if (ff_h264_decode_seq_parameter_set(h) < 0 && (h->is_avc ? (nalsize != consumed) && nalsize : 1)) {
  3578. av_log(h->s.avctx, AV_LOG_DEBUG,
  3579. "SPS decoding failure, trying again with the complete NAL\n");
  3580. if (h->is_avc)
  3581. av_assert0(next_avc - buf_index + consumed == nalsize);
  3582. if ((next_avc - buf_index + consumed - 1) >= INT_MAX/8)
  3583. break;
  3584. init_get_bits(&s->gb, &buf[buf_index + 1 - consumed],
  3585. 8*(next_avc - buf_index + consumed - 1));
  3586. ff_h264_decode_seq_parameter_set(h);
  3587. }
  3588. if (s->flags & CODEC_FLAG_LOW_DELAY ||
  3589. (h->sps.bitstream_restriction_flag &&
  3590. !h->sps.num_reorder_frames)) {
  3591. if (s->avctx->has_b_frames > 1 || h->delayed_pic[0])
  3592. av_log(avctx, AV_LOG_WARNING, "Delayed frames seen "
  3593. "reenabling low delay requires a codec "
  3594. "flush.\n");
  3595. else
  3596. s->low_delay = 1;
  3597. }
  3598. if (avctx->has_b_frames < 2)
  3599. avctx->has_b_frames = !s->low_delay;
  3600. break;
  3601. case NAL_PPS:
  3602. init_get_bits(&s->gb, ptr, bit_length);
  3603. ff_h264_decode_picture_parameter_set(h, bit_length);
  3604. break;
  3605. case NAL_AUD:
  3606. case NAL_END_SEQUENCE:
  3607. case NAL_END_STREAM:
  3608. case NAL_FILLER_DATA:
  3609. case NAL_SPS_EXT:
  3610. case NAL_AUXILIARY_SLICE:
  3611. break;
  3612. default:
  3613. av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
  3614. hx->nal_unit_type, bit_length);
  3615. }
  3616. if (context_count == h->max_contexts) {
  3617. execute_decode_slices(h, context_count);
  3618. context_count = 0;
  3619. }
  3620. if (err < 0)
  3621. av_log(h->s.avctx, AV_LOG_ERROR, "decode_slice_header error\n");
  3622. else if (err == 1) {
  3623. /* Slice could not be decoded in parallel mode, copy down
  3624. * NAL unit stuff to context 0 and restart. Note that
  3625. * rbsp_buffer is not transferred, but since we no longer
  3626. * run in parallel mode this should not be an issue. */
  3627. h->nal_unit_type = hx->nal_unit_type;
  3628. h->nal_ref_idc = hx->nal_ref_idc;
  3629. hx = h;
  3630. goto again;
  3631. }
  3632. }
  3633. }
  3634. if (context_count)
  3635. execute_decode_slices(h, context_count);
  3636. end:
  3637. /* clean up */
  3638. if (s->current_picture_ptr && s->current_picture_ptr->owner2 == s &&
  3639. !s->droppable) {
  3640. ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX,
  3641. s->picture_structure == PICT_BOTTOM_FIELD);
  3642. }
  3643. return buf_index;
  3644. }
  3645. /**
  3646. * Return the number of bytes consumed for building the current frame.
  3647. */
  3648. static int get_consumed_bytes(MpegEncContext *s, int pos, int buf_size)
  3649. {
  3650. if (pos == 0)
  3651. pos = 1; // avoid infinite loops (i doubt that is needed but ...)
  3652. if (pos + 10 > buf_size)
  3653. pos = buf_size; // oops ;)
  3654. return pos;
  3655. }
  3656. static int decode_frame(AVCodecContext *avctx, void *data,
  3657. int *got_frame, AVPacket *avpkt)
  3658. {
  3659. const uint8_t *buf = avpkt->data;
  3660. int buf_size = avpkt->size;
  3661. H264Context *h = avctx->priv_data;
  3662. MpegEncContext *s = &h->s;
  3663. AVFrame *pict = data;
  3664. int buf_index = 0;
  3665. Picture *out;
  3666. int i, out_idx;
  3667. s->flags = avctx->flags;
  3668. s->flags2 = avctx->flags2;
  3669. /* end of stream, output what is still in the buffers */
  3670. if (buf_size == 0) {
  3671. out:
  3672. s->current_picture_ptr = NULL;
  3673. // FIXME factorize this with the output code below
  3674. out = h->delayed_pic[0];
  3675. out_idx = 0;
  3676. for (i = 1;
  3677. h->delayed_pic[i] &&
  3678. !h->delayed_pic[i]->f.key_frame &&
  3679. !h->delayed_pic[i]->mmco_reset;
  3680. i++)
  3681. if (h->delayed_pic[i]->poc < out->poc) {
  3682. out = h->delayed_pic[i];
  3683. out_idx = i;
  3684. }
  3685. for (i = out_idx; h->delayed_pic[i]; i++)
  3686. h->delayed_pic[i] = h->delayed_pic[i + 1];
  3687. if (out) {
  3688. *got_frame = 1;
  3689. *pict = out->f;
  3690. }
  3691. return buf_index;
  3692. }
  3693. if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
  3694. int cnt= buf[5]&0x1f;
  3695. const uint8_t *p= buf+6;
  3696. while(cnt--){
  3697. int nalsize= AV_RB16(p) + 2;
  3698. if(nalsize > buf_size - (p-buf) || p[2]!=0x67)
  3699. goto not_extra;
  3700. p += nalsize;
  3701. }
  3702. cnt = *(p++);
  3703. if(!cnt)
  3704. goto not_extra;
  3705. while(cnt--){
  3706. int nalsize= AV_RB16(p) + 2;
  3707. if(nalsize > buf_size - (p-buf) || p[2]!=0x68)
  3708. goto not_extra;
  3709. p += nalsize;
  3710. }
  3711. return ff_h264_decode_extradata(h, buf, buf_size);
  3712. }
  3713. not_extra:
  3714. buf_index = decode_nal_units(h, buf, buf_size);
  3715. if (buf_index < 0)
  3716. return -1;
  3717. if (!s->current_picture_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
  3718. av_assert0(buf_index <= buf_size);
  3719. goto out;
  3720. }
  3721. if (!(s->flags2 & CODEC_FLAG2_CHUNKS) && !s->current_picture_ptr) {
  3722. if (avctx->skip_frame >= AVDISCARD_NONREF ||
  3723. buf_size >= 4 && !memcmp("Q264", buf, 4))
  3724. return buf_size;
  3725. av_log(avctx, AV_LOG_ERROR, "no frame!\n");
  3726. return -1;
  3727. }
  3728. if (!(s->flags2 & CODEC_FLAG2_CHUNKS) ||
  3729. (s->mb_y >= s->mb_height && s->mb_height)) {
  3730. if (s->flags2 & CODEC_FLAG2_CHUNKS)
  3731. decode_postinit(h, 1);
  3732. field_end(h, 0);
  3733. /* Wait for second field. */
  3734. *got_frame = 0;
  3735. if (h->next_output_pic && (h->next_output_pic->sync || h->sync>1)) {
  3736. *got_frame = 1;
  3737. *pict = h->next_output_pic->f;
  3738. }
  3739. }
  3740. assert(pict->data[0] || !*got_frame);
  3741. ff_print_debug_info(s, pict);
  3742. return get_consumed_bytes(s, buf_index, buf_size);
  3743. }
  3744. av_cold void ff_h264_free_context(H264Context *h)
  3745. {
  3746. int i;
  3747. free_tables(h, 1); // FIXME cleanup init stuff perhaps
  3748. for (i = 0; i < MAX_SPS_COUNT; i++)
  3749. av_freep(h->sps_buffers + i);
  3750. for (i = 0; i < MAX_PPS_COUNT; i++)
  3751. av_freep(h->pps_buffers + i);
  3752. }
  3753. static av_cold int h264_decode_end(AVCodecContext *avctx)
  3754. {
  3755. H264Context *h = avctx->priv_data;
  3756. MpegEncContext *s = &h->s;
  3757. ff_h264_remove_all_refs(h);
  3758. ff_h264_free_context(h);
  3759. ff_MPV_common_end(s);
  3760. // memset(h, 0, sizeof(H264Context));
  3761. return 0;
  3762. }
  3763. static const AVProfile profiles[] = {
  3764. { FF_PROFILE_H264_BASELINE, "Baseline" },
  3765. { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
  3766. { FF_PROFILE_H264_MAIN, "Main" },
  3767. { FF_PROFILE_H264_EXTENDED, "Extended" },
  3768. { FF_PROFILE_H264_HIGH, "High" },
  3769. { FF_PROFILE_H264_HIGH_10, "High 10" },
  3770. { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
  3771. { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
  3772. { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
  3773. { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
  3774. { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
  3775. { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
  3776. { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
  3777. { FF_PROFILE_UNKNOWN },
  3778. };
  3779. static const AVOption h264_options[] = {
  3780. {"is_avc", "is avc", offsetof(H264Context, is_avc), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0},
  3781. {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
  3782. {NULL}
  3783. };
  3784. static const AVClass h264_class = {
  3785. .class_name = "H264 Decoder",
  3786. .item_name = av_default_item_name,
  3787. .option = h264_options,
  3788. .version = LIBAVUTIL_VERSION_INT,
  3789. };
  3790. static const AVClass h264_vdpau_class = {
  3791. .class_name = "H264 VDPAU Decoder",
  3792. .item_name = av_default_item_name,
  3793. .option = h264_options,
  3794. .version = LIBAVUTIL_VERSION_INT,
  3795. };
  3796. AVCodec ff_h264_decoder = {
  3797. .name = "h264",
  3798. .type = AVMEDIA_TYPE_VIDEO,
  3799. .id = AV_CODEC_ID_H264,
  3800. .priv_data_size = sizeof(H264Context),
  3801. .init = ff_h264_decode_init,
  3802. .close = h264_decode_end,
  3803. .decode = decode_frame,
  3804. .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
  3805. CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
  3806. CODEC_CAP_FRAME_THREADS,
  3807. .flush = flush_dpb,
  3808. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
  3809. .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
  3810. .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
  3811. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  3812. .priv_class = &h264_class,
  3813. };
  3814. #if CONFIG_H264_VDPAU_DECODER
  3815. AVCodec ff_h264_vdpau_decoder = {
  3816. .name = "h264_vdpau",
  3817. .type = AVMEDIA_TYPE_VIDEO,
  3818. .id = AV_CODEC_ID_H264,
  3819. .priv_data_size = sizeof(H264Context),
  3820. .init = ff_h264_decode_init,
  3821. .close = h264_decode_end,
  3822. .decode = decode_frame,
  3823. .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
  3824. .flush = flush_dpb,
  3825. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
  3826. .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
  3827. AV_PIX_FMT_NONE},
  3828. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  3829. .priv_class = &h264_vdpau_class,
  3830. };
  3831. #endif