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.

4637 lines
174KB

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