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.

4639 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, ref_count, list_count);
  1364. copy_fields(h, h1, ref2frm, intra_gb);
  1365. copy_fields(h, h1, short_ref, cabac_init_idc);
  1366. copy_picture_range(h->short_ref, h1->short_ref, 32, h, h1);
  1367. copy_picture_range(h->long_ref, h1->long_ref, 32, h, h1);
  1368. copy_picture_range(h->delayed_pic, h1->delayed_pic,
  1369. MAX_DELAYED_PIC_COUNT + 2, h, h1);
  1370. h->last_slice_type = h1->last_slice_type;
  1371. if (context_reinitialized)
  1372. h264_set_parameter_from_sps(h);
  1373. if (!h->cur_pic_ptr)
  1374. return 0;
  1375. if (!h->droppable) {
  1376. err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
  1377. h->prev_poc_msb = h->poc_msb;
  1378. h->prev_poc_lsb = h->poc_lsb;
  1379. }
  1380. h->prev_frame_num_offset = h->frame_num_offset;
  1381. h->prev_frame_num = h->frame_num;
  1382. h->outputed_poc = h->next_outputed_poc;
  1383. return err;
  1384. }
  1385. int ff_h264_frame_start(H264Context *h)
  1386. {
  1387. Picture *pic;
  1388. int i, ret;
  1389. const int pixel_shift = h->pixel_shift;
  1390. release_unused_pictures(h, 1);
  1391. h->cur_pic_ptr = NULL;
  1392. i = find_unused_picture(h);
  1393. if (i < 0) {
  1394. av_log(h->avctx, AV_LOG_ERROR, "no frame buffer available\n");
  1395. return i;
  1396. }
  1397. pic = &h->DPB[i];
  1398. pic->f.reference = h->droppable ? 0 : h->picture_structure;
  1399. pic->f.coded_picture_number = h->coded_picture_number++;
  1400. pic->field_picture = h->picture_structure != PICT_FRAME;
  1401. /*
  1402. * Zero key_frame here; IDR markings per slice in frame or fields are ORed
  1403. * in later.
  1404. * See decode_nal_units().
  1405. */
  1406. pic->f.key_frame = 0;
  1407. pic->mmco_reset = 0;
  1408. if ((ret = alloc_picture(h, pic)) < 0)
  1409. return ret;
  1410. h->cur_pic_ptr = pic;
  1411. h->cur_pic = *h->cur_pic_ptr;
  1412. h->cur_pic.f.extended_data = h->cur_pic.f.data;
  1413. ff_er_frame_start(&h->er);
  1414. assert(h->linesize && h->uvlinesize);
  1415. for (i = 0; i < 16; i++) {
  1416. h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
  1417. h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
  1418. }
  1419. for (i = 0; i < 16; i++) {
  1420. h->block_offset[16 + i] =
  1421. h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
  1422. h->block_offset[48 + 16 + i] =
  1423. h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
  1424. }
  1425. /* can't be in alloc_tables because linesize isn't known there.
  1426. * FIXME: redo bipred weight to not require extra buffer? */
  1427. for (i = 0; i < h->slice_context_count; i++)
  1428. if (h->thread_context[i]) {
  1429. ret = alloc_scratch_buffers(h->thread_context[i], h->linesize);
  1430. if (ret < 0)
  1431. return ret;
  1432. }
  1433. /* Some macroblocks can be accessed before they're available in case
  1434. * of lost slices, MBAFF or threading. */
  1435. memset(h->slice_table, -1,
  1436. (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));
  1437. // s->decode = (s->flags & CODEC_FLAG_PSNR) || !s->encoding ||
  1438. // s->current_picture.f.reference /* || h->contains_intra */ || 1;
  1439. /* We mark the current picture as non-reference after allocating it, so
  1440. * that if we break out due to an error it can be released automatically
  1441. * in the next ff_MPV_frame_start().
  1442. * SVQ3 as well as most other codecs have only last/next/current and thus
  1443. * get released even with set reference, besides SVQ3 and others do not
  1444. * mark frames as reference later "naturally". */
  1445. if (h->avctx->codec_id != AV_CODEC_ID_SVQ3)
  1446. h->cur_pic_ptr->f.reference = 0;
  1447. h->cur_pic_ptr->field_poc[0] = h->cur_pic_ptr->field_poc[1] = INT_MAX;
  1448. h->next_output_pic = NULL;
  1449. assert(h->cur_pic_ptr->long_ref == 0);
  1450. return 0;
  1451. }
  1452. /**
  1453. * Run setup operations that must be run after slice header decoding.
  1454. * This includes finding the next displayed frame.
  1455. *
  1456. * @param h h264 master context
  1457. * @param setup_finished enough NALs have been read that we can call
  1458. * ff_thread_finish_setup()
  1459. */
  1460. static void decode_postinit(H264Context *h, int setup_finished)
  1461. {
  1462. Picture *out = h->cur_pic_ptr;
  1463. Picture *cur = h->cur_pic_ptr;
  1464. int i, pics, out_of_order, out_idx;
  1465. int invalid = 0, cnt = 0;
  1466. h->cur_pic_ptr->f.qscale_type = FF_QSCALE_TYPE_H264;
  1467. h->cur_pic_ptr->f.pict_type = h->pict_type;
  1468. if (h->next_output_pic)
  1469. return;
  1470. if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
  1471. /* FIXME: if we have two PAFF fields in one packet, we can't start
  1472. * the next thread here. If we have one field per packet, we can.
  1473. * The check in decode_nal_units() is not good enough to find this
  1474. * yet, so we assume the worst for now. */
  1475. // if (setup_finished)
  1476. // ff_thread_finish_setup(h->avctx);
  1477. return;
  1478. }
  1479. cur->f.interlaced_frame = 0;
  1480. cur->f.repeat_pict = 0;
  1481. /* Signal interlacing information externally. */
  1482. /* Prioritize picture timing SEI information over used
  1483. * decoding process if it exists. */
  1484. if (h->sps.pic_struct_present_flag) {
  1485. switch (h->sei_pic_struct) {
  1486. case SEI_PIC_STRUCT_FRAME:
  1487. break;
  1488. case SEI_PIC_STRUCT_TOP_FIELD:
  1489. case SEI_PIC_STRUCT_BOTTOM_FIELD:
  1490. cur->f.interlaced_frame = 1;
  1491. break;
  1492. case SEI_PIC_STRUCT_TOP_BOTTOM:
  1493. case SEI_PIC_STRUCT_BOTTOM_TOP:
  1494. if (FIELD_OR_MBAFF_PICTURE)
  1495. cur->f.interlaced_frame = 1;
  1496. else
  1497. // try to flag soft telecine progressive
  1498. cur->f.interlaced_frame = h->prev_interlaced_frame;
  1499. break;
  1500. case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
  1501. case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
  1502. /* Signal the possibility of telecined film externally
  1503. * (pic_struct 5,6). From these hints, let the applications
  1504. * decide if they apply deinterlacing. */
  1505. cur->f.repeat_pict = 1;
  1506. break;
  1507. case SEI_PIC_STRUCT_FRAME_DOUBLING:
  1508. cur->f.repeat_pict = 2;
  1509. break;
  1510. case SEI_PIC_STRUCT_FRAME_TRIPLING:
  1511. cur->f.repeat_pict = 4;
  1512. break;
  1513. }
  1514. if ((h->sei_ct_type & 3) &&
  1515. h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
  1516. cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
  1517. } else {
  1518. /* Derive interlacing flag from used decoding process. */
  1519. cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE;
  1520. }
  1521. h->prev_interlaced_frame = cur->f.interlaced_frame;
  1522. if (cur->field_poc[0] != cur->field_poc[1]) {
  1523. /* Derive top_field_first from field pocs. */
  1524. cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
  1525. } else {
  1526. if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
  1527. /* Use picture timing SEI information. Even if it is a
  1528. * information of a past frame, better than nothing. */
  1529. if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
  1530. h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
  1531. cur->f.top_field_first = 1;
  1532. else
  1533. cur->f.top_field_first = 0;
  1534. } else {
  1535. /* Most likely progressive */
  1536. cur->f.top_field_first = 0;
  1537. }
  1538. }
  1539. // FIXME do something with unavailable reference frames
  1540. /* Sort B-frames into display order */
  1541. if (h->sps.bitstream_restriction_flag &&
  1542. h->avctx->has_b_frames < h->sps.num_reorder_frames) {
  1543. h->avctx->has_b_frames = h->sps.num_reorder_frames;
  1544. h->low_delay = 0;
  1545. }
  1546. if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
  1547. !h->sps.bitstream_restriction_flag) {
  1548. h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
  1549. h->low_delay = 0;
  1550. }
  1551. pics = 0;
  1552. while (h->delayed_pic[pics])
  1553. pics++;
  1554. assert(pics <= MAX_DELAYED_PIC_COUNT);
  1555. h->delayed_pic[pics++] = cur;
  1556. if (cur->f.reference == 0)
  1557. cur->f.reference = DELAYED_PIC_REF;
  1558. /* Frame reordering. This code takes pictures from coding order and sorts
  1559. * them by their incremental POC value into display order. It supports POC
  1560. * gaps, MMCO reset codes and random resets.
  1561. * A "display group" can start either with a IDR frame (f.key_frame = 1),
  1562. * and/or can be closed down with a MMCO reset code. In sequences where
  1563. * there is no delay, we can't detect that (since the frame was already
  1564. * output to the user), so we also set h->mmco_reset to detect the MMCO
  1565. * reset code.
  1566. * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
  1567. * we increase the delay between input and output. All frames affected by
  1568. * the lag (e.g. those that should have been output before another frame
  1569. * that we already returned to the user) will be dropped. This is a bug
  1570. * that we will fix later. */
  1571. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
  1572. cnt += out->poc < h->last_pocs[i];
  1573. invalid += out->poc == INT_MIN;
  1574. }
  1575. if (!h->mmco_reset && !cur->f.key_frame &&
  1576. cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
  1577. h->mmco_reset = 2;
  1578. if (pics > 1)
  1579. h->delayed_pic[pics - 2]->mmco_reset = 2;
  1580. }
  1581. if (h->mmco_reset || cur->f.key_frame) {
  1582. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  1583. h->last_pocs[i] = INT_MIN;
  1584. cnt = 0;
  1585. invalid = MAX_DELAYED_PIC_COUNT;
  1586. }
  1587. out = h->delayed_pic[0];
  1588. out_idx = 0;
  1589. for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
  1590. h->delayed_pic[i] &&
  1591. !h->delayed_pic[i - 1]->mmco_reset &&
  1592. !h->delayed_pic[i]->f.key_frame;
  1593. i++)
  1594. if (h->delayed_pic[i]->poc < out->poc) {
  1595. out = h->delayed_pic[i];
  1596. out_idx = i;
  1597. }
  1598. if (h->avctx->has_b_frames == 0 &&
  1599. (h->delayed_pic[0]->f.key_frame || h->mmco_reset))
  1600. h->next_outputed_poc = INT_MIN;
  1601. out_of_order = !out->f.key_frame && !h->mmco_reset &&
  1602. (out->poc < h->next_outputed_poc);
  1603. if (h->sps.bitstream_restriction_flag &&
  1604. h->avctx->has_b_frames >= h->sps.num_reorder_frames) {
  1605. } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
  1606. h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
  1607. if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
  1608. h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
  1609. }
  1610. h->low_delay = 0;
  1611. } else if (h->low_delay &&
  1612. ((h->next_outputed_poc != INT_MIN &&
  1613. out->poc > h->next_outputed_poc + 2) ||
  1614. cur->f.pict_type == AV_PICTURE_TYPE_B)) {
  1615. h->low_delay = 0;
  1616. h->avctx->has_b_frames++;
  1617. }
  1618. if (pics > h->avctx->has_b_frames) {
  1619. out->f.reference &= ~DELAYED_PIC_REF;
  1620. // for frame threading, the owner must be the second field's thread or
  1621. // else the first thread can release the picture and reuse it unsafely
  1622. out->owner2 = h;
  1623. for (i = out_idx; h->delayed_pic[i]; i++)
  1624. h->delayed_pic[i] = h->delayed_pic[i + 1];
  1625. }
  1626. memmove(h->last_pocs, &h->last_pocs[1],
  1627. sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
  1628. h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
  1629. if (!out_of_order && pics > h->avctx->has_b_frames) {
  1630. h->next_output_pic = out;
  1631. if (out->mmco_reset) {
  1632. if (out_idx > 0) {
  1633. h->next_outputed_poc = out->poc;
  1634. h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
  1635. } else {
  1636. h->next_outputed_poc = INT_MIN;
  1637. }
  1638. } else {
  1639. if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f.key_frame) {
  1640. h->next_outputed_poc = INT_MIN;
  1641. } else {
  1642. h->next_outputed_poc = out->poc;
  1643. }
  1644. }
  1645. h->mmco_reset = 0;
  1646. } else {
  1647. av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
  1648. }
  1649. if (setup_finished)
  1650. ff_thread_finish_setup(h->avctx);
  1651. }
  1652. static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
  1653. uint8_t *src_cb, uint8_t *src_cr,
  1654. int linesize, int uvlinesize,
  1655. int simple)
  1656. {
  1657. uint8_t *top_border;
  1658. int top_idx = 1;
  1659. const int pixel_shift = h->pixel_shift;
  1660. int chroma444 = CHROMA444;
  1661. int chroma422 = CHROMA422;
  1662. src_y -= linesize;
  1663. src_cb -= uvlinesize;
  1664. src_cr -= uvlinesize;
  1665. if (!simple && FRAME_MBAFF) {
  1666. if (h->mb_y & 1) {
  1667. if (!MB_MBAFF) {
  1668. top_border = h->top_borders[0][h->mb_x];
  1669. AV_COPY128(top_border, src_y + 15 * linesize);
  1670. if (pixel_shift)
  1671. AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
  1672. if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
  1673. if (chroma444) {
  1674. if (pixel_shift) {
  1675. AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
  1676. AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
  1677. AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
  1678. AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
  1679. } else {
  1680. AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
  1681. AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
  1682. }
  1683. } else if (chroma422) {
  1684. if (pixel_shift) {
  1685. AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
  1686. AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
  1687. } else {
  1688. AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
  1689. AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
  1690. }
  1691. } else {
  1692. if (pixel_shift) {
  1693. AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
  1694. AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
  1695. } else {
  1696. AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
  1697. AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
  1698. }
  1699. }
  1700. }
  1701. }
  1702. } else if (MB_MBAFF) {
  1703. top_idx = 0;
  1704. } else
  1705. return;
  1706. }
  1707. top_border = h->top_borders[top_idx][h->mb_x];
  1708. /* There are two lines saved, the line above the top macroblock
  1709. * of a pair, and the line above the bottom macroblock. */
  1710. AV_COPY128(top_border, src_y + 16 * linesize);
  1711. if (pixel_shift)
  1712. AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
  1713. if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
  1714. if (chroma444) {
  1715. if (pixel_shift) {
  1716. AV_COPY128(top_border + 32, src_cb + 16 * linesize);
  1717. AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
  1718. AV_COPY128(top_border + 64, src_cr + 16 * linesize);
  1719. AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
  1720. } else {
  1721. AV_COPY128(top_border + 16, src_cb + 16 * linesize);
  1722. AV_COPY128(top_border + 32, src_cr + 16 * linesize);
  1723. }
  1724. } else if (chroma422) {
  1725. if (pixel_shift) {
  1726. AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
  1727. AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
  1728. } else {
  1729. AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
  1730. AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
  1731. }
  1732. } else {
  1733. if (pixel_shift) {
  1734. AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
  1735. AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
  1736. } else {
  1737. AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
  1738. AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
  1739. }
  1740. }
  1741. }
  1742. }
  1743. static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
  1744. uint8_t *src_cb, uint8_t *src_cr,
  1745. int linesize, int uvlinesize,
  1746. int xchg, int chroma444,
  1747. int simple, int pixel_shift)
  1748. {
  1749. int deblock_topleft;
  1750. int deblock_top;
  1751. int top_idx = 1;
  1752. uint8_t *top_border_m1;
  1753. uint8_t *top_border;
  1754. if (!simple && FRAME_MBAFF) {
  1755. if (h->mb_y & 1) {
  1756. if (!MB_MBAFF)
  1757. return;
  1758. } else {
  1759. top_idx = MB_MBAFF ? 0 : 1;
  1760. }
  1761. }
  1762. if (h->deblocking_filter == 2) {
  1763. deblock_topleft = h->slice_table[h->mb_xy - 1 - h->mb_stride] == h->slice_num;
  1764. deblock_top = h->top_type;
  1765. } else {
  1766. deblock_topleft = (h->mb_x > 0);
  1767. deblock_top = (h->mb_y > !!MB_FIELD);
  1768. }
  1769. src_y -= linesize + 1 + pixel_shift;
  1770. src_cb -= uvlinesize + 1 + pixel_shift;
  1771. src_cr -= uvlinesize + 1 + pixel_shift;
  1772. top_border_m1 = h->top_borders[top_idx][h->mb_x - 1];
  1773. top_border = h->top_borders[top_idx][h->mb_x];
  1774. #define XCHG(a, b, xchg) \
  1775. if (pixel_shift) { \
  1776. if (xchg) { \
  1777. AV_SWAP64(b + 0, a + 0); \
  1778. AV_SWAP64(b + 8, a + 8); \
  1779. } else { \
  1780. AV_COPY128(b, a); \
  1781. } \
  1782. } else if (xchg) \
  1783. AV_SWAP64(b, a); \
  1784. else \
  1785. AV_COPY64(b, a);
  1786. if (deblock_top) {
  1787. if (deblock_topleft) {
  1788. XCHG(top_border_m1 + (8 << pixel_shift),
  1789. src_y - (7 << pixel_shift), 1);
  1790. }
  1791. XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
  1792. XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
  1793. if (h->mb_x + 1 < h->mb_width) {
  1794. XCHG(h->top_borders[top_idx][h->mb_x + 1],
  1795. src_y + (17 << pixel_shift), 1);
  1796. }
  1797. }
  1798. if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
  1799. if (chroma444) {
  1800. if (deblock_topleft) {
  1801. XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
  1802. XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
  1803. }
  1804. XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
  1805. XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
  1806. XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
  1807. XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
  1808. if (h->mb_x + 1 < h->mb_width) {
  1809. XCHG(h->top_borders[top_idx][h->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
  1810. XCHG(h->top_borders[top_idx][h->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
  1811. }
  1812. } else {
  1813. if (deblock_top) {
  1814. if (deblock_topleft) {
  1815. XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
  1816. XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
  1817. }
  1818. XCHG(top_border + (16 << pixel_shift), src_cb + 1 + pixel_shift, 1);
  1819. XCHG(top_border + (24 << pixel_shift), src_cr + 1 + pixel_shift, 1);
  1820. }
  1821. }
  1822. }
  1823. }
  1824. static av_always_inline int dctcoef_get(int16_t *mb, int high_bit_depth,
  1825. int index)
  1826. {
  1827. if (high_bit_depth) {
  1828. return AV_RN32A(((int32_t *)mb) + index);
  1829. } else
  1830. return AV_RN16A(mb + index);
  1831. }
  1832. static av_always_inline void dctcoef_set(int16_t *mb, int high_bit_depth,
  1833. int index, int value)
  1834. {
  1835. if (high_bit_depth) {
  1836. AV_WN32A(((int32_t *)mb) + index, value);
  1837. } else
  1838. AV_WN16A(mb + index, value);
  1839. }
  1840. static av_always_inline void hl_decode_mb_predict_luma(H264Context *h,
  1841. int mb_type, int is_h264,
  1842. int simple,
  1843. int transform_bypass,
  1844. int pixel_shift,
  1845. int *block_offset,
  1846. int linesize,
  1847. uint8_t *dest_y, int p)
  1848. {
  1849. void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
  1850. void (*idct_dc_add)(uint8_t *dst, int16_t *block, int stride);
  1851. int i;
  1852. int qscale = p == 0 ? h->qscale : h->chroma_qp[p - 1];
  1853. block_offset += 16 * p;
  1854. if (IS_INTRA4x4(mb_type)) {
  1855. if (IS_8x8DCT(mb_type)) {
  1856. if (transform_bypass) {
  1857. idct_dc_add =
  1858. idct_add = h->h264dsp.h264_add_pixels8;
  1859. } else {
  1860. idct_dc_add = h->h264dsp.h264_idct8_dc_add;
  1861. idct_add = h->h264dsp.h264_idct8_add;
  1862. }
  1863. for (i = 0; i < 16; i += 4) {
  1864. uint8_t *const ptr = dest_y + block_offset[i];
  1865. const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
  1866. if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
  1867. h->hpc.pred8x8l_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  1868. } else {
  1869. const int nnz = h->non_zero_count_cache[scan8[i + p * 16]];
  1870. h->hpc.pred8x8l[dir](ptr, (h->topleft_samples_available << i) & 0x8000,
  1871. (h->topright_samples_available << i) & 0x4000, linesize);
  1872. if (nnz) {
  1873. if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
  1874. idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  1875. else
  1876. idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  1877. }
  1878. }
  1879. }
  1880. } else {
  1881. if (transform_bypass) {
  1882. idct_dc_add =
  1883. idct_add = h->h264dsp.h264_add_pixels4;
  1884. } else {
  1885. idct_dc_add = h->h264dsp.h264_idct_dc_add;
  1886. idct_add = h->h264dsp.h264_idct_add;
  1887. }
  1888. for (i = 0; i < 16; i++) {
  1889. uint8_t *const ptr = dest_y + block_offset[i];
  1890. const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
  1891. if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
  1892. h->hpc.pred4x4_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  1893. } else {
  1894. uint8_t *topright;
  1895. int nnz, tr;
  1896. uint64_t tr_high;
  1897. if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
  1898. const int topright_avail = (h->topright_samples_available << i) & 0x8000;
  1899. assert(h->mb_y || linesize <= block_offset[i]);
  1900. if (!topright_avail) {
  1901. if (pixel_shift) {
  1902. tr_high = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
  1903. topright = (uint8_t *)&tr_high;
  1904. } else {
  1905. tr = ptr[3 - linesize] * 0x01010101u;
  1906. topright = (uint8_t *)&tr;
  1907. }
  1908. } else
  1909. topright = ptr + (4 << pixel_shift) - linesize;
  1910. } else
  1911. topright = NULL;
  1912. h->hpc.pred4x4[dir](ptr, topright, linesize);
  1913. nnz = h->non_zero_count_cache[scan8[i + p * 16]];
  1914. if (nnz) {
  1915. if (is_h264) {
  1916. if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
  1917. idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  1918. else
  1919. idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  1920. } else if (CONFIG_SVQ3_DECODER)
  1921. ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize, qscale, 0);
  1922. }
  1923. }
  1924. }
  1925. }
  1926. } else {
  1927. h->hpc.pred16x16[h->intra16x16_pred_mode](dest_y, linesize);
  1928. if (is_h264) {
  1929. if (h->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {
  1930. if (!transform_bypass)
  1931. h->h264dsp.h264_luma_dc_dequant_idct(h->mb + (p * 256 << pixel_shift),
  1932. h->mb_luma_dc[p],
  1933. h->dequant4_coeff[p][qscale][0]);
  1934. else {
  1935. static const uint8_t dc_mapping[16] = {
  1936. 0 * 16, 1 * 16, 4 * 16, 5 * 16,
  1937. 2 * 16, 3 * 16, 6 * 16, 7 * 16,
  1938. 8 * 16, 9 * 16, 12 * 16, 13 * 16,
  1939. 10 * 16, 11 * 16, 14 * 16, 15 * 16 };
  1940. for (i = 0; i < 16; i++)
  1941. dctcoef_set(h->mb + (p * 256 << pixel_shift),
  1942. pixel_shift, dc_mapping[i],
  1943. dctcoef_get(h->mb_luma_dc[p],
  1944. pixel_shift, i));
  1945. }
  1946. }
  1947. } else if (CONFIG_SVQ3_DECODER)
  1948. ff_svq3_luma_dc_dequant_idct_c(h->mb + p * 256,
  1949. h->mb_luma_dc[p], qscale);
  1950. }
  1951. }
  1952. static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type,
  1953. int is_h264, int simple,
  1954. int transform_bypass,
  1955. int pixel_shift,
  1956. int *block_offset,
  1957. int linesize,
  1958. uint8_t *dest_y, int p)
  1959. {
  1960. void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
  1961. int i;
  1962. block_offset += 16 * p;
  1963. if (!IS_INTRA4x4(mb_type)) {
  1964. if (is_h264) {
  1965. if (IS_INTRA16x16(mb_type)) {
  1966. if (transform_bypass) {
  1967. if (h->sps.profile_idc == 244 &&
  1968. (h->intra16x16_pred_mode == VERT_PRED8x8 ||
  1969. h->intra16x16_pred_mode == HOR_PRED8x8)) {
  1970. h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset,
  1971. h->mb + (p * 256 << pixel_shift),
  1972. linesize);
  1973. } else {
  1974. for (i = 0; i < 16; i++)
  1975. if (h->non_zero_count_cache[scan8[i + p * 16]] ||
  1976. dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
  1977. h->h264dsp.h264_add_pixels4(dest_y + block_offset[i],
  1978. h->mb + (i * 16 + p * 256 << pixel_shift),
  1979. linesize);
  1980. }
  1981. } else {
  1982. h->h264dsp.h264_idct_add16intra(dest_y, block_offset,
  1983. h->mb + (p * 256 << pixel_shift),
  1984. linesize,
  1985. h->non_zero_count_cache + p * 5 * 8);
  1986. }
  1987. } else if (h->cbp & 15) {
  1988. if (transform_bypass) {
  1989. const int di = IS_8x8DCT(mb_type) ? 4 : 1;
  1990. idct_add = IS_8x8DCT(mb_type) ? h->h264dsp.h264_add_pixels8
  1991. : h->h264dsp.h264_add_pixels4;
  1992. for (i = 0; i < 16; i += di)
  1993. if (h->non_zero_count_cache[scan8[i + p * 16]])
  1994. idct_add(dest_y + block_offset[i],
  1995. h->mb + (i * 16 + p * 256 << pixel_shift),
  1996. linesize);
  1997. } else {
  1998. if (IS_8x8DCT(mb_type))
  1999. h->h264dsp.h264_idct8_add4(dest_y, block_offset,
  2000. h->mb + (p * 256 << pixel_shift),
  2001. linesize,
  2002. h->non_zero_count_cache + p * 5 * 8);
  2003. else
  2004. h->h264dsp.h264_idct_add16(dest_y, block_offset,
  2005. h->mb + (p * 256 << pixel_shift),
  2006. linesize,
  2007. h->non_zero_count_cache + p * 5 * 8);
  2008. }
  2009. }
  2010. } else if (CONFIG_SVQ3_DECODER) {
  2011. for (i = 0; i < 16; i++)
  2012. if (h->non_zero_count_cache[scan8[i + p * 16]] || h->mb[i * 16 + p * 256]) {
  2013. // FIXME benchmark weird rule, & below
  2014. uint8_t *const ptr = dest_y + block_offset[i];
  2015. ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize,
  2016. h->qscale, IS_INTRA(mb_type) ? 1 : 0);
  2017. }
  2018. }
  2019. }
  2020. }
  2021. #define BITS 8
  2022. #define SIMPLE 1
  2023. #include "h264_mb_template.c"
  2024. #undef BITS
  2025. #define BITS 16
  2026. #include "h264_mb_template.c"
  2027. #undef SIMPLE
  2028. #define SIMPLE 0
  2029. #include "h264_mb_template.c"
  2030. void ff_h264_hl_decode_mb(H264Context *h)
  2031. {
  2032. const int mb_xy = h->mb_xy;
  2033. const int mb_type = h->cur_pic.f.mb_type[mb_xy];
  2034. int is_complex = CONFIG_SMALL || h->is_complex || IS_INTRA_PCM(mb_type) || h->qscale == 0;
  2035. if (CHROMA444) {
  2036. if (is_complex || h->pixel_shift)
  2037. hl_decode_mb_444_complex(h);
  2038. else
  2039. hl_decode_mb_444_simple_8(h);
  2040. } else if (is_complex) {
  2041. hl_decode_mb_complex(h);
  2042. } else if (h->pixel_shift) {
  2043. hl_decode_mb_simple_16(h);
  2044. } else
  2045. hl_decode_mb_simple_8(h);
  2046. }
  2047. static int pred_weight_table(H264Context *h)
  2048. {
  2049. int list, i;
  2050. int luma_def, chroma_def;
  2051. h->use_weight = 0;
  2052. h->use_weight_chroma = 0;
  2053. h->luma_log2_weight_denom = get_ue_golomb(&h->gb);
  2054. if (h->sps.chroma_format_idc)
  2055. h->chroma_log2_weight_denom = get_ue_golomb(&h->gb);
  2056. luma_def = 1 << h->luma_log2_weight_denom;
  2057. chroma_def = 1 << h->chroma_log2_weight_denom;
  2058. for (list = 0; list < 2; list++) {
  2059. h->luma_weight_flag[list] = 0;
  2060. h->chroma_weight_flag[list] = 0;
  2061. for (i = 0; i < h->ref_count[list]; i++) {
  2062. int luma_weight_flag, chroma_weight_flag;
  2063. luma_weight_flag = get_bits1(&h->gb);
  2064. if (luma_weight_flag) {
  2065. h->luma_weight[i][list][0] = get_se_golomb(&h->gb);
  2066. h->luma_weight[i][list][1] = get_se_golomb(&h->gb);
  2067. if (h->luma_weight[i][list][0] != luma_def ||
  2068. h->luma_weight[i][list][1] != 0) {
  2069. h->use_weight = 1;
  2070. h->luma_weight_flag[list] = 1;
  2071. }
  2072. } else {
  2073. h->luma_weight[i][list][0] = luma_def;
  2074. h->luma_weight[i][list][1] = 0;
  2075. }
  2076. if (h->sps.chroma_format_idc) {
  2077. chroma_weight_flag = get_bits1(&h->gb);
  2078. if (chroma_weight_flag) {
  2079. int j;
  2080. for (j = 0; j < 2; j++) {
  2081. h->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
  2082. h->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
  2083. if (h->chroma_weight[i][list][j][0] != chroma_def ||
  2084. h->chroma_weight[i][list][j][1] != 0) {
  2085. h->use_weight_chroma = 1;
  2086. h->chroma_weight_flag[list] = 1;
  2087. }
  2088. }
  2089. } else {
  2090. int j;
  2091. for (j = 0; j < 2; j++) {
  2092. h->chroma_weight[i][list][j][0] = chroma_def;
  2093. h->chroma_weight[i][list][j][1] = 0;
  2094. }
  2095. }
  2096. }
  2097. }
  2098. if (h->slice_type_nos != AV_PICTURE_TYPE_B)
  2099. break;
  2100. }
  2101. h->use_weight = h->use_weight || h->use_weight_chroma;
  2102. return 0;
  2103. }
  2104. /**
  2105. * Initialize implicit_weight table.
  2106. * @param field 0/1 initialize the weight for interlaced MBAFF
  2107. * -1 initializes the rest
  2108. */
  2109. static void implicit_weight_table(H264Context *h, int field)
  2110. {
  2111. int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
  2112. for (i = 0; i < 2; i++) {
  2113. h->luma_weight_flag[i] = 0;
  2114. h->chroma_weight_flag[i] = 0;
  2115. }
  2116. if (field < 0) {
  2117. if (h->picture_structure == PICT_FRAME) {
  2118. cur_poc = h->cur_pic_ptr->poc;
  2119. } else {
  2120. cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];
  2121. }
  2122. if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF &&
  2123. h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) {
  2124. h->use_weight = 0;
  2125. h->use_weight_chroma = 0;
  2126. return;
  2127. }
  2128. ref_start = 0;
  2129. ref_count0 = h->ref_count[0];
  2130. ref_count1 = h->ref_count[1];
  2131. } else {
  2132. cur_poc = h->cur_pic_ptr->field_poc[field];
  2133. ref_start = 16;
  2134. ref_count0 = 16 + 2 * h->ref_count[0];
  2135. ref_count1 = 16 + 2 * h->ref_count[1];
  2136. }
  2137. h->use_weight = 2;
  2138. h->use_weight_chroma = 2;
  2139. h->luma_log2_weight_denom = 5;
  2140. h->chroma_log2_weight_denom = 5;
  2141. for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
  2142. int poc0 = h->ref_list[0][ref0].poc;
  2143. for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
  2144. int w = 32;
  2145. if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
  2146. int poc1 = h->ref_list[1][ref1].poc;
  2147. int td = av_clip(poc1 - poc0, -128, 127);
  2148. if (td) {
  2149. int tb = av_clip(cur_poc - poc0, -128, 127);
  2150. int tx = (16384 + (FFABS(td) >> 1)) / td;
  2151. int dist_scale_factor = (tb * tx + 32) >> 8;
  2152. if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
  2153. w = 64 - dist_scale_factor;
  2154. }
  2155. }
  2156. if (field < 0) {
  2157. h->implicit_weight[ref0][ref1][0] =
  2158. h->implicit_weight[ref0][ref1][1] = w;
  2159. } else {
  2160. h->implicit_weight[ref0][ref1][field] = w;
  2161. }
  2162. }
  2163. }
  2164. }
  2165. /**
  2166. * instantaneous decoder refresh.
  2167. */
  2168. static void idr(H264Context *h)
  2169. {
  2170. ff_h264_remove_all_refs(h);
  2171. h->prev_frame_num = 0;
  2172. h->prev_frame_num_offset = 0;
  2173. h->prev_poc_msb =
  2174. h->prev_poc_lsb = 0;
  2175. }
  2176. /* forget old pics after a seek */
  2177. static void flush_change(H264Context *h)
  2178. {
  2179. int i;
  2180. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  2181. h->last_pocs[i] = INT_MIN;
  2182. h->outputed_poc = h->next_outputed_poc = INT_MIN;
  2183. h->prev_interlaced_frame = 1;
  2184. idr(h);
  2185. if (h->cur_pic_ptr)
  2186. h->cur_pic_ptr->f.reference = 0;
  2187. h->first_field = 0;
  2188. memset(h->ref_list[0], 0, sizeof(h->ref_list[0]));
  2189. memset(h->ref_list[1], 0, sizeof(h->ref_list[1]));
  2190. memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0]));
  2191. memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1]));
  2192. ff_h264_reset_sei(h);
  2193. }
  2194. /* forget old pics after a seek */
  2195. static void flush_dpb(AVCodecContext *avctx)
  2196. {
  2197. H264Context *h = avctx->priv_data;
  2198. int i;
  2199. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
  2200. if (h->delayed_pic[i])
  2201. h->delayed_pic[i]->f.reference = 0;
  2202. h->delayed_pic[i] = NULL;
  2203. }
  2204. flush_change(h);
  2205. for (i = 0; i < h->picture_count; i++) {
  2206. if (h->DPB[i].f.data[0])
  2207. free_frame_buffer(h, &h->DPB[i]);
  2208. }
  2209. h->cur_pic_ptr = NULL;
  2210. h->mb_x = h->mb_y = 0;
  2211. h->parse_context.state = -1;
  2212. h->parse_context.frame_start_found = 0;
  2213. h->parse_context.overread = 0;
  2214. h->parse_context.overread_index = 0;
  2215. h->parse_context.index = 0;
  2216. h->parse_context.last_index = 0;
  2217. }
  2218. static int init_poc(H264Context *h)
  2219. {
  2220. const int max_frame_num = 1 << h->sps.log2_max_frame_num;
  2221. int field_poc[2];
  2222. Picture *cur = h->cur_pic_ptr;
  2223. h->frame_num_offset = h->prev_frame_num_offset;
  2224. if (h->frame_num < h->prev_frame_num)
  2225. h->frame_num_offset += max_frame_num;
  2226. if (h->sps.poc_type == 0) {
  2227. const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
  2228. 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 if (h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
  2231. h->poc_msb = h->prev_poc_msb - max_poc_lsb;
  2232. else
  2233. h->poc_msb = h->prev_poc_msb;
  2234. field_poc[0] =
  2235. field_poc[1] = h->poc_msb + h->poc_lsb;
  2236. if (h->picture_structure == PICT_FRAME)
  2237. field_poc[1] += h->delta_poc_bottom;
  2238. } else if (h->sps.poc_type == 1) {
  2239. int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
  2240. int i;
  2241. if (h->sps.poc_cycle_length != 0)
  2242. abs_frame_num = h->frame_num_offset + h->frame_num;
  2243. else
  2244. abs_frame_num = 0;
  2245. if (h->nal_ref_idc == 0 && abs_frame_num > 0)
  2246. abs_frame_num--;
  2247. expected_delta_per_poc_cycle = 0;
  2248. for (i = 0; i < h->sps.poc_cycle_length; i++)
  2249. // FIXME integrate during sps parse
  2250. expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
  2251. if (abs_frame_num > 0) {
  2252. int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
  2253. int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
  2254. expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
  2255. for (i = 0; i <= frame_num_in_poc_cycle; i++)
  2256. expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
  2257. } else
  2258. expectedpoc = 0;
  2259. if (h->nal_ref_idc == 0)
  2260. expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
  2261. field_poc[0] = expectedpoc + h->delta_poc[0];
  2262. field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
  2263. if (h->picture_structure == PICT_FRAME)
  2264. field_poc[1] += h->delta_poc[1];
  2265. } else {
  2266. int poc = 2 * (h->frame_num_offset + h->frame_num);
  2267. if (!h->nal_ref_idc)
  2268. poc--;
  2269. field_poc[0] = poc;
  2270. field_poc[1] = poc;
  2271. }
  2272. if (h->picture_structure != PICT_BOTTOM_FIELD)
  2273. h->cur_pic_ptr->field_poc[0] = field_poc[0];
  2274. if (h->picture_structure != PICT_TOP_FIELD)
  2275. h->cur_pic_ptr->field_poc[1] = field_poc[1];
  2276. cur->poc = FFMIN(cur->field_poc[0], cur->field_poc[1]);
  2277. return 0;
  2278. }
  2279. /**
  2280. * initialize scan tables
  2281. */
  2282. static void init_scan_tables(H264Context *h)
  2283. {
  2284. int i;
  2285. for (i = 0; i < 16; i++) {
  2286. #define T(x) (x >> 2) | ((x << 2) & 0xF)
  2287. h->zigzag_scan[i] = T(zigzag_scan[i]);
  2288. h->field_scan[i] = T(field_scan[i]);
  2289. #undef T
  2290. }
  2291. for (i = 0; i < 64; i++) {
  2292. #define T(x) (x >> 3) | ((x & 7) << 3)
  2293. h->zigzag_scan8x8[i] = T(ff_zigzag_direct[i]);
  2294. h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
  2295. h->field_scan8x8[i] = T(field_scan8x8[i]);
  2296. h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
  2297. #undef T
  2298. }
  2299. if (h->sps.transform_bypass) { // FIXME same ugly
  2300. h->zigzag_scan_q0 = zigzag_scan;
  2301. h->zigzag_scan8x8_q0 = ff_zigzag_direct;
  2302. h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;
  2303. h->field_scan_q0 = field_scan;
  2304. h->field_scan8x8_q0 = field_scan8x8;
  2305. h->field_scan8x8_cavlc_q0 = field_scan8x8_cavlc;
  2306. } else {
  2307. h->zigzag_scan_q0 = h->zigzag_scan;
  2308. h->zigzag_scan8x8_q0 = h->zigzag_scan8x8;
  2309. h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;
  2310. h->field_scan_q0 = h->field_scan;
  2311. h->field_scan8x8_q0 = h->field_scan8x8;
  2312. h->field_scan8x8_cavlc_q0 = h->field_scan8x8_cavlc;
  2313. }
  2314. }
  2315. static int field_end(H264Context *h, int in_setup)
  2316. {
  2317. AVCodecContext *const avctx = h->avctx;
  2318. int err = 0;
  2319. h->mb_y = 0;
  2320. if (!in_setup && !h->droppable)
  2321. ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX,
  2322. h->picture_structure == PICT_BOTTOM_FIELD);
  2323. if (CONFIG_H264_VDPAU_DECODER &&
  2324. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  2325. ff_vdpau_h264_set_reference_frames(h);
  2326. if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
  2327. if (!h->droppable) {
  2328. err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
  2329. h->prev_poc_msb = h->poc_msb;
  2330. h->prev_poc_lsb = h->poc_lsb;
  2331. }
  2332. h->prev_frame_num_offset = h->frame_num_offset;
  2333. h->prev_frame_num = h->frame_num;
  2334. h->outputed_poc = h->next_outputed_poc;
  2335. }
  2336. if (avctx->hwaccel) {
  2337. if (avctx->hwaccel->end_frame(avctx) < 0)
  2338. av_log(avctx, AV_LOG_ERROR,
  2339. "hardware accelerator failed to decode picture\n");
  2340. }
  2341. if (CONFIG_H264_VDPAU_DECODER &&
  2342. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  2343. ff_vdpau_h264_picture_complete(h);
  2344. /*
  2345. * FIXME: Error handling code does not seem to support interlaced
  2346. * when slices span multiple rows
  2347. * The ff_er_add_slice calls don't work right for bottom
  2348. * fields; they cause massive erroneous error concealing
  2349. * Error marking covers both fields (top and bottom).
  2350. * This causes a mismatched s->error_count
  2351. * and a bad error table. Further, the error count goes to
  2352. * INT_MAX when called for bottom field, because mb_y is
  2353. * past end by one (callers fault) and resync_mb_y != 0
  2354. * causes problems for the first MB line, too.
  2355. */
  2356. if (!FIELD_PICTURE) {
  2357. h->er.cur_pic = h->cur_pic_ptr;
  2358. h->er.last_pic = h->ref_count[0] ? &h->ref_list[0][0] : NULL;
  2359. h->er.next_pic = h->ref_count[1] ? &h->ref_list[1][0] : NULL;
  2360. ff_er_frame_end(&h->er);
  2361. }
  2362. emms_c();
  2363. h->current_slice = 0;
  2364. return err;
  2365. }
  2366. /**
  2367. * Replicate H264 "master" context to thread contexts.
  2368. */
  2369. static int clone_slice(H264Context *dst, H264Context *src)
  2370. {
  2371. memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
  2372. dst->cur_pic_ptr = src->cur_pic_ptr;
  2373. dst->cur_pic = src->cur_pic;
  2374. dst->linesize = src->linesize;
  2375. dst->uvlinesize = src->uvlinesize;
  2376. dst->first_field = src->first_field;
  2377. dst->prev_poc_msb = src->prev_poc_msb;
  2378. dst->prev_poc_lsb = src->prev_poc_lsb;
  2379. dst->prev_frame_num_offset = src->prev_frame_num_offset;
  2380. dst->prev_frame_num = src->prev_frame_num;
  2381. dst->short_ref_count = src->short_ref_count;
  2382. memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
  2383. memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
  2384. memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
  2385. memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
  2386. memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
  2387. return 0;
  2388. }
  2389. /**
  2390. * Compute profile from profile_idc and constraint_set?_flags.
  2391. *
  2392. * @param sps SPS
  2393. *
  2394. * @return profile as defined by FF_PROFILE_H264_*
  2395. */
  2396. int ff_h264_get_profile(SPS *sps)
  2397. {
  2398. int profile = sps->profile_idc;
  2399. switch (sps->profile_idc) {
  2400. case FF_PROFILE_H264_BASELINE:
  2401. // constraint_set1_flag set to 1
  2402. profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
  2403. break;
  2404. case FF_PROFILE_H264_HIGH_10:
  2405. case FF_PROFILE_H264_HIGH_422:
  2406. case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
  2407. // constraint_set3_flag set to 1
  2408. profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
  2409. break;
  2410. }
  2411. return profile;
  2412. }
  2413. static int h264_set_parameter_from_sps(H264Context *h)
  2414. {
  2415. if (h->flags & CODEC_FLAG_LOW_DELAY ||
  2416. (h->sps.bitstream_restriction_flag &&
  2417. !h->sps.num_reorder_frames)) {
  2418. if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
  2419. av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
  2420. "Reenabling low delay requires a codec flush.\n");
  2421. else
  2422. h->low_delay = 1;
  2423. }
  2424. if (h->avctx->has_b_frames < 2)
  2425. h->avctx->has_b_frames = !h->low_delay;
  2426. if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
  2427. h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
  2428. if (h->avctx->codec &&
  2429. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU &&
  2430. (h->sps.bit_depth_luma != 8 || h->sps.chroma_format_idc > 1)) {
  2431. av_log(h->avctx, AV_LOG_ERROR,
  2432. "VDPAU decoding does not support video colorspace.\n");
  2433. return AVERROR_INVALIDDATA;
  2434. }
  2435. if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 10) {
  2436. h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
  2437. h->cur_chroma_format_idc = h->sps.chroma_format_idc;
  2438. h->pixel_shift = h->sps.bit_depth_luma > 8;
  2439. ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
  2440. h->sps.chroma_format_idc);
  2441. ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
  2442. ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
  2443. ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
  2444. h->sps.chroma_format_idc);
  2445. h->dsp.dct_bits = h->sps.bit_depth_luma > 8 ? 32 : 16;
  2446. ff_dsputil_init(&h->dsp, h->avctx);
  2447. ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
  2448. } else {
  2449. av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth: %d\n",
  2450. h->sps.bit_depth_luma);
  2451. return AVERROR_INVALIDDATA;
  2452. }
  2453. }
  2454. return 0;
  2455. }
  2456. static enum PixelFormat get_pixel_format(H264Context *h)
  2457. {
  2458. switch (h->sps.bit_depth_luma) {
  2459. case 9:
  2460. if (CHROMA444) {
  2461. if (h->avctx->colorspace == AVCOL_SPC_RGB) {
  2462. return AV_PIX_FMT_GBRP9;
  2463. } else
  2464. return AV_PIX_FMT_YUV444P9;
  2465. } else if (CHROMA422)
  2466. return AV_PIX_FMT_YUV422P9;
  2467. else
  2468. return AV_PIX_FMT_YUV420P9;
  2469. break;
  2470. case 10:
  2471. if (CHROMA444) {
  2472. if (h->avctx->colorspace == AVCOL_SPC_RGB) {
  2473. return AV_PIX_FMT_GBRP10;
  2474. } else
  2475. return AV_PIX_FMT_YUV444P10;
  2476. } else if (CHROMA422)
  2477. return AV_PIX_FMT_YUV422P10;
  2478. else
  2479. return AV_PIX_FMT_YUV420P10;
  2480. break;
  2481. case 8:
  2482. if (CHROMA444) {
  2483. if (h->avctx->colorspace == AVCOL_SPC_RGB) {
  2484. return AV_PIX_FMT_GBRP;
  2485. } else
  2486. return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ444P
  2487. : AV_PIX_FMT_YUV444P;
  2488. } else if (CHROMA422) {
  2489. return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ422P
  2490. : AV_PIX_FMT_YUV422P;
  2491. } else {
  2492. return h->avctx->get_format(h->avctx, h->avctx->codec->pix_fmts ?
  2493. h->avctx->codec->pix_fmts :
  2494. h->avctx->color_range == AVCOL_RANGE_JPEG ?
  2495. hwaccel_pixfmt_list_h264_jpeg_420 :
  2496. ff_hwaccel_pixfmt_list_420);
  2497. }
  2498. break;
  2499. default:
  2500. av_log(h->avctx, AV_LOG_ERROR,
  2501. "Unsupported bit depth: %d\n", h->sps.bit_depth_luma);
  2502. return AVERROR_INVALIDDATA;
  2503. }
  2504. }
  2505. static int h264_slice_header_init(H264Context *h, int reinit)
  2506. {
  2507. int nb_slices = (HAVE_THREADS &&
  2508. h->avctx->active_thread_type & FF_THREAD_SLICE) ?
  2509. h->avctx->thread_count : 1;
  2510. int i;
  2511. avcodec_set_dimensions(h->avctx, h->width, h->height);
  2512. h->avctx->sample_aspect_ratio = h->sps.sar;
  2513. av_assert0(h->avctx->sample_aspect_ratio.den);
  2514. av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt,
  2515. &h->chroma_x_shift, &h->chroma_y_shift);
  2516. if (h->sps.timing_info_present_flag) {
  2517. int64_t den = h->sps.time_scale;
  2518. if (h->x264_build < 44U)
  2519. den *= 2;
  2520. av_reduce(&h->avctx->time_base.num, &h->avctx->time_base.den,
  2521. h->sps.num_units_in_tick, den, 1 << 30);
  2522. }
  2523. h->avctx->hwaccel = ff_find_hwaccel(h->avctx->codec->id, h->avctx->pix_fmt);
  2524. if (reinit)
  2525. free_tables(h, 0);
  2526. h->first_field = 0;
  2527. h->prev_interlaced_frame = 1;
  2528. init_scan_tables(h);
  2529. if (ff_h264_alloc_tables(h) < 0) {
  2530. av_log(h->avctx, AV_LOG_ERROR,
  2531. "Could not allocate memory for h264\n");
  2532. return AVERROR(ENOMEM);
  2533. }
  2534. if (nb_slices > MAX_THREADS || (nb_slices > h->mb_height && h->mb_height)) {
  2535. int max_slices;
  2536. if (h->mb_height)
  2537. max_slices = FFMIN(MAX_THREADS, h->mb_height);
  2538. else
  2539. max_slices = MAX_THREADS;
  2540. av_log(h->avctx, AV_LOG_WARNING, "too many threads/slices (%d),"
  2541. " reducing to %d\n", nb_slices, max_slices);
  2542. nb_slices = max_slices;
  2543. }
  2544. h->slice_context_count = nb_slices;
  2545. if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
  2546. if (context_init(h) < 0) {
  2547. av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
  2548. return -1;
  2549. }
  2550. } else {
  2551. for (i = 1; i < h->slice_context_count; i++) {
  2552. H264Context *c;
  2553. c = h->thread_context[i] = av_mallocz(sizeof(H264Context));
  2554. c->avctx = h->avctx;
  2555. c->dsp = h->dsp;
  2556. c->vdsp = h->vdsp;
  2557. c->h264dsp = h->h264dsp;
  2558. c->h264qpel = h->h264qpel;
  2559. c->h264chroma = h->h264chroma;
  2560. c->sps = h->sps;
  2561. c->pps = h->pps;
  2562. c->pixel_shift = h->pixel_shift;
  2563. c->width = h->width;
  2564. c->height = h->height;
  2565. c->linesize = h->linesize;
  2566. c->uvlinesize = h->uvlinesize;
  2567. c->chroma_x_shift = h->chroma_x_shift;
  2568. c->chroma_y_shift = h->chroma_y_shift;
  2569. c->qscale = h->qscale;
  2570. c->droppable = h->droppable;
  2571. c->data_partitioning = h->data_partitioning;
  2572. c->low_delay = h->low_delay;
  2573. c->mb_width = h->mb_width;
  2574. c->mb_height = h->mb_height;
  2575. c->mb_stride = h->mb_stride;
  2576. c->mb_num = h->mb_num;
  2577. c->flags = h->flags;
  2578. c->workaround_bugs = h->workaround_bugs;
  2579. c->pict_type = h->pict_type;
  2580. init_scan_tables(c);
  2581. clone_tables(c, h, i);
  2582. c->context_initialized = 1;
  2583. }
  2584. for (i = 0; i < h->slice_context_count; i++)
  2585. if (context_init(h->thread_context[i]) < 0) {
  2586. av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
  2587. return -1;
  2588. }
  2589. }
  2590. h->context_initialized = 1;
  2591. return 0;
  2592. }
  2593. /**
  2594. * Decode a slice header.
  2595. * This will also call ff_MPV_common_init() and frame_start() as needed.
  2596. *
  2597. * @param h h264context
  2598. * @param h0 h264 master context (differs from 'h' when doing sliced based
  2599. * parallel decoding)
  2600. *
  2601. * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
  2602. */
  2603. static int decode_slice_header(H264Context *h, H264Context *h0)
  2604. {
  2605. unsigned int first_mb_in_slice;
  2606. unsigned int pps_id;
  2607. int num_ref_idx_active_override_flag, max_refs, ret;
  2608. unsigned int slice_type, tmp, i, j;
  2609. int default_ref_list_done = 0;
  2610. int last_pic_structure, last_pic_droppable;
  2611. int needs_reinit = 0;
  2612. h->me.qpel_put = h->h264qpel.put_h264_qpel_pixels_tab;
  2613. h->me.qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab;
  2614. first_mb_in_slice = get_ue_golomb(&h->gb);
  2615. if (first_mb_in_slice == 0) { // FIXME better field boundary detection
  2616. if (h0->current_slice && FIELD_PICTURE) {
  2617. field_end(h, 1);
  2618. }
  2619. h0->current_slice = 0;
  2620. if (!h0->first_field) {
  2621. if (h->cur_pic_ptr && !h->droppable &&
  2622. h->cur_pic_ptr->owner2 == h) {
  2623. ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX,
  2624. h->picture_structure == PICT_BOTTOM_FIELD);
  2625. }
  2626. h->cur_pic_ptr = NULL;
  2627. }
  2628. }
  2629. slice_type = get_ue_golomb_31(&h->gb);
  2630. if (slice_type > 9) {
  2631. av_log(h->avctx, AV_LOG_ERROR,
  2632. "slice type too large (%d) at %d %d\n",
  2633. h->slice_type, h->mb_x, h->mb_y);
  2634. return -1;
  2635. }
  2636. if (slice_type > 4) {
  2637. slice_type -= 5;
  2638. h->slice_type_fixed = 1;
  2639. } else
  2640. h->slice_type_fixed = 0;
  2641. slice_type = golomb_to_pict_type[slice_type];
  2642. if (slice_type == AV_PICTURE_TYPE_I ||
  2643. (h0->current_slice != 0 && slice_type == h0->last_slice_type)) {
  2644. default_ref_list_done = 1;
  2645. }
  2646. h->slice_type = slice_type;
  2647. h->slice_type_nos = slice_type & 3;
  2648. // to make a few old functions happy, it's wrong though
  2649. h->pict_type = h->slice_type;
  2650. pps_id = get_ue_golomb(&h->gb);
  2651. if (pps_id >= MAX_PPS_COUNT) {
  2652. av_log(h->avctx, AV_LOG_ERROR, "pps_id out of range\n");
  2653. return -1;
  2654. }
  2655. if (!h0->pps_buffers[pps_id]) {
  2656. av_log(h->avctx, AV_LOG_ERROR,
  2657. "non-existing PPS %u referenced\n",
  2658. pps_id);
  2659. return -1;
  2660. }
  2661. h->pps = *h0->pps_buffers[pps_id];
  2662. if (!h0->sps_buffers[h->pps.sps_id]) {
  2663. av_log(h->avctx, AV_LOG_ERROR,
  2664. "non-existing SPS %u referenced\n",
  2665. h->pps.sps_id);
  2666. return -1;
  2667. }
  2668. if (h->pps.sps_id != h->current_sps_id ||
  2669. h0->sps_buffers[h->pps.sps_id]->new) {
  2670. h0->sps_buffers[h->pps.sps_id]->new = 0;
  2671. h->current_sps_id = h->pps.sps_id;
  2672. h->sps = *h0->sps_buffers[h->pps.sps_id];
  2673. if (h->bit_depth_luma != h->sps.bit_depth_luma ||
  2674. h->chroma_format_idc != h->sps.chroma_format_idc) {
  2675. h->bit_depth_luma = h->sps.bit_depth_luma;
  2676. h->chroma_format_idc = h->sps.chroma_format_idc;
  2677. needs_reinit = 1;
  2678. }
  2679. if ((ret = h264_set_parameter_from_sps(h)) < 0)
  2680. return ret;
  2681. }
  2682. h->avctx->profile = ff_h264_get_profile(&h->sps);
  2683. h->avctx->level = h->sps.level_idc;
  2684. h->avctx->refs = h->sps.ref_frame_count;
  2685. if (h->mb_width != h->sps.mb_width ||
  2686. h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag))
  2687. needs_reinit = 1;
  2688. h->mb_width = h->sps.mb_width;
  2689. h->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
  2690. h->mb_num = h->mb_width * h->mb_height;
  2691. h->mb_stride = h->mb_width + 1;
  2692. h->b_stride = h->mb_width * 4;
  2693. h->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
  2694. h->width = 16 * h->mb_width - (2 >> CHROMA444) * FFMIN(h->sps.crop_right, (8 << CHROMA444) - 1);
  2695. if (h->sps.frame_mbs_only_flag)
  2696. h->height = 16 * h->mb_height - (1 << h->chroma_y_shift) * FFMIN(h->sps.crop_bottom, (16 >> h->chroma_y_shift) - 1);
  2697. else
  2698. h->height = 16 * h->mb_height - (2 << h->chroma_y_shift) * FFMIN(h->sps.crop_bottom, (16 >> h->chroma_y_shift) - 1);
  2699. if (FFALIGN(h->avctx->width, 16) == h->width &&
  2700. FFALIGN(h->avctx->height, 16) == h->height) {
  2701. h->width = h->avctx->width;
  2702. h->height = h->avctx->height;
  2703. }
  2704. if (h->sps.video_signal_type_present_flag) {
  2705. h->avctx->color_range = h->sps.full_range ? AVCOL_RANGE_JPEG
  2706. : AVCOL_RANGE_MPEG;
  2707. if (h->sps.colour_description_present_flag) {
  2708. if (h->avctx->colorspace != h->sps.colorspace)
  2709. needs_reinit = 1;
  2710. h->avctx->color_primaries = h->sps.color_primaries;
  2711. h->avctx->color_trc = h->sps.color_trc;
  2712. h->avctx->colorspace = h->sps.colorspace;
  2713. }
  2714. }
  2715. if (h->context_initialized &&
  2716. (h->width != h->avctx->width ||
  2717. h->height != h->avctx->height ||
  2718. needs_reinit)) {
  2719. if (h != h0) {
  2720. av_log(h->avctx, AV_LOG_ERROR, "changing width/height on "
  2721. "slice %d\n", h0->current_slice + 1);
  2722. return AVERROR_INVALIDDATA;
  2723. }
  2724. flush_change(h);
  2725. if ((ret = get_pixel_format(h)) < 0)
  2726. return ret;
  2727. h->avctx->pix_fmt = ret;
  2728. av_log(h->avctx, AV_LOG_INFO, "Reinit context to %dx%d, "
  2729. "pix_fmt: %d\n", h->width, h->height, h->avctx->pix_fmt);
  2730. if ((ret = h264_slice_header_init(h, 1)) < 0) {
  2731. av_log(h->avctx, AV_LOG_ERROR,
  2732. "h264_slice_header_init() failed\n");
  2733. return ret;
  2734. }
  2735. }
  2736. if (!h->context_initialized) {
  2737. if (h != h0) {
  2738. av_log(h->avctx, AV_LOG_ERROR,
  2739. "Cannot (re-)initialize context during parallel decoding.\n");
  2740. return -1;
  2741. }
  2742. if ((ret = get_pixel_format(h)) < 0)
  2743. return ret;
  2744. h->avctx->pix_fmt = ret;
  2745. if ((ret = h264_slice_header_init(h, 0)) < 0) {
  2746. av_log(h->avctx, AV_LOG_ERROR,
  2747. "h264_slice_header_init() failed\n");
  2748. return ret;
  2749. }
  2750. }
  2751. if (h == h0 && h->dequant_coeff_pps != pps_id) {
  2752. h->dequant_coeff_pps = pps_id;
  2753. init_dequant_tables(h);
  2754. }
  2755. h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num);
  2756. h->mb_mbaff = 0;
  2757. h->mb_aff_frame = 0;
  2758. last_pic_structure = h0->picture_structure;
  2759. last_pic_droppable = h0->droppable;
  2760. h->droppable = h->nal_ref_idc == 0;
  2761. if (h->sps.frame_mbs_only_flag) {
  2762. h->picture_structure = PICT_FRAME;
  2763. } else {
  2764. if (get_bits1(&h->gb)) { // field_pic_flag
  2765. h->picture_structure = PICT_TOP_FIELD + get_bits1(&h->gb); // bottom_field_flag
  2766. } else {
  2767. h->picture_structure = PICT_FRAME;
  2768. h->mb_aff_frame = h->sps.mb_aff;
  2769. }
  2770. }
  2771. h->mb_field_decoding_flag = h->picture_structure != PICT_FRAME;
  2772. if (h0->current_slice != 0) {
  2773. if (last_pic_structure != h->picture_structure ||
  2774. last_pic_droppable != h->droppable) {
  2775. av_log(h->avctx, AV_LOG_ERROR,
  2776. "Changing field mode (%d -> %d) between slices is not allowed\n",
  2777. last_pic_structure, h->picture_structure);
  2778. h->picture_structure = last_pic_structure;
  2779. h->droppable = last_pic_droppable;
  2780. return AVERROR_INVALIDDATA;
  2781. } else if (!h0->cur_pic_ptr) {
  2782. av_log(h->avctx, AV_LOG_ERROR,
  2783. "unset cur_pic_ptr on %d. slice\n",
  2784. h0->current_slice + 1);
  2785. return AVERROR_INVALIDDATA;
  2786. }
  2787. } else {
  2788. /* Shorten frame num gaps so we don't have to allocate reference
  2789. * frames just to throw them away */
  2790. if (h->frame_num != h->prev_frame_num) {
  2791. int unwrap_prev_frame_num = h->prev_frame_num;
  2792. int max_frame_num = 1 << h->sps.log2_max_frame_num;
  2793. if (unwrap_prev_frame_num > h->frame_num)
  2794. unwrap_prev_frame_num -= max_frame_num;
  2795. if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
  2796. unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
  2797. if (unwrap_prev_frame_num < 0)
  2798. unwrap_prev_frame_num += max_frame_num;
  2799. h->prev_frame_num = unwrap_prev_frame_num;
  2800. }
  2801. }
  2802. /* See if we have a decoded first field looking for a pair...
  2803. * Here, we're using that to see if we should mark previously
  2804. * decode frames as "finished".
  2805. * We have to do that before the "dummy" in-between frame allocation,
  2806. * since that can modify s->current_picture_ptr. */
  2807. if (h0->first_field) {
  2808. assert(h0->cur_pic_ptr);
  2809. assert(h0->cur_pic_ptr->f.data[0]);
  2810. assert(h0->cur_pic_ptr->f.reference != DELAYED_PIC_REF);
  2811. /* Mark old field/frame as completed */
  2812. if (!last_pic_droppable && h0->cur_pic_ptr->owner2 == h0) {
  2813. ff_thread_report_progress(&h0->cur_pic_ptr->f, INT_MAX,
  2814. last_pic_structure == PICT_BOTTOM_FIELD);
  2815. }
  2816. /* figure out if we have a complementary field pair */
  2817. if (!FIELD_PICTURE || h->picture_structure == last_pic_structure) {
  2818. /* Previous field is unmatched. Don't display it, but let it
  2819. * remain for reference if marked as such. */
  2820. if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
  2821. ff_thread_report_progress(&h0->cur_pic_ptr->f, INT_MAX,
  2822. last_pic_structure == PICT_TOP_FIELD);
  2823. }
  2824. } else {
  2825. if (h0->cur_pic_ptr->frame_num != h->frame_num) {
  2826. /* This and previous field were reference, but had
  2827. * different frame_nums. Consider this field first in
  2828. * pair. Throw away previous field except for reference
  2829. * purposes. */
  2830. if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
  2831. ff_thread_report_progress(&h0->cur_pic_ptr->f, INT_MAX,
  2832. last_pic_structure == PICT_TOP_FIELD);
  2833. }
  2834. } else {
  2835. /* Second field in complementary pair */
  2836. if (!((last_pic_structure == PICT_TOP_FIELD &&
  2837. h->picture_structure == PICT_BOTTOM_FIELD) ||
  2838. (last_pic_structure == PICT_BOTTOM_FIELD &&
  2839. h->picture_structure == PICT_TOP_FIELD))) {
  2840. av_log(h->avctx, AV_LOG_ERROR,
  2841. "Invalid field mode combination %d/%d\n",
  2842. last_pic_structure, h->picture_structure);
  2843. h->picture_structure = last_pic_structure;
  2844. h->droppable = last_pic_droppable;
  2845. return AVERROR_INVALIDDATA;
  2846. } else if (last_pic_droppable != h->droppable) {
  2847. av_log(h->avctx, AV_LOG_ERROR,
  2848. "Cannot combine reference and non-reference fields in the same frame\n");
  2849. av_log_ask_for_sample(h->avctx, NULL);
  2850. h->picture_structure = last_pic_structure;
  2851. h->droppable = last_pic_droppable;
  2852. return AVERROR_PATCHWELCOME;
  2853. }
  2854. /* Take ownership of this buffer. Note that if another thread owned
  2855. * the first field of this buffer, we're not operating on that pointer,
  2856. * so the original thread is still responsible for reporting progress
  2857. * on that first field (or if that was us, we just did that above).
  2858. * By taking ownership, we assign responsibility to ourselves to
  2859. * report progress on the second field. */
  2860. h0->cur_pic_ptr->owner2 = h0;
  2861. }
  2862. }
  2863. }
  2864. while (h->frame_num != h->prev_frame_num &&
  2865. h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
  2866. Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
  2867. av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
  2868. h->frame_num, h->prev_frame_num);
  2869. if (ff_h264_frame_start(h) < 0)
  2870. return -1;
  2871. h->prev_frame_num++;
  2872. h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;
  2873. h->cur_pic_ptr->frame_num = h->prev_frame_num;
  2874. ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX, 0);
  2875. ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX, 1);
  2876. if ((ret = ff_generate_sliding_window_mmcos(h, 1)) < 0 &&
  2877. h->avctx->err_recognition & AV_EF_EXPLODE)
  2878. return ret;
  2879. if (ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index) < 0 &&
  2880. (h->avctx->err_recognition & AV_EF_EXPLODE))
  2881. return AVERROR_INVALIDDATA;
  2882. /* Error concealment: if a ref is missing, copy the previous ref in its place.
  2883. * FIXME: avoiding a memcpy would be nice, but ref handling makes many assumptions
  2884. * about there being no actual duplicates.
  2885. * FIXME: this doesn't copy padding for out-of-frame motion vectors. Given we're
  2886. * concealing a lost frame, this probably isn't noticeable by comparison, but it should
  2887. * be fixed. */
  2888. if (h->short_ref_count) {
  2889. if (prev) {
  2890. av_image_copy(h->short_ref[0]->f.data, h->short_ref[0]->f.linesize,
  2891. (const uint8_t **)prev->f.data, prev->f.linesize,
  2892. h->avctx->pix_fmt, h->mb_width * 16, h->mb_height * 16);
  2893. h->short_ref[0]->poc = prev->poc + 2;
  2894. }
  2895. h->short_ref[0]->frame_num = h->prev_frame_num;
  2896. }
  2897. }
  2898. /* See if we have a decoded first field looking for a pair...
  2899. * We're using that to see whether to continue decoding in that
  2900. * frame, or to allocate a new one. */
  2901. if (h0->first_field) {
  2902. assert(h0->cur_pic_ptr);
  2903. assert(h0->cur_pic_ptr->f.data[0]);
  2904. assert(h0->cur_pic_ptr->f.reference != DELAYED_PIC_REF);
  2905. /* figure out if we have a complementary field pair */
  2906. if (!FIELD_PICTURE || h->picture_structure == last_pic_structure) {
  2907. /* Previous field is unmatched. Don't display it, but let it
  2908. * remain for reference if marked as such. */
  2909. h0->cur_pic_ptr = NULL;
  2910. h0->first_field = FIELD_PICTURE;
  2911. } else {
  2912. if (h0->cur_pic_ptr->frame_num != h->frame_num) {
  2913. /* This and the previous field had different frame_nums.
  2914. * Consider this field first in pair. Throw away previous
  2915. * one except for reference purposes. */
  2916. h0->first_field = 1;
  2917. h0->cur_pic_ptr = NULL;
  2918. } else {
  2919. /* Second field in complementary pair */
  2920. h0->first_field = 0;
  2921. }
  2922. }
  2923. } else {
  2924. /* Frame or first field in a potentially complementary pair */
  2925. h0->first_field = FIELD_PICTURE;
  2926. }
  2927. if (!FIELD_PICTURE || h0->first_field) {
  2928. if (ff_h264_frame_start(h) < 0) {
  2929. h0->first_field = 0;
  2930. return -1;
  2931. }
  2932. } else {
  2933. release_unused_pictures(h, 0);
  2934. }
  2935. }
  2936. if (h != h0 && (ret = clone_slice(h, h0)) < 0)
  2937. return ret;
  2938. h->cur_pic_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
  2939. assert(h->mb_num == h->mb_width * h->mb_height);
  2940. if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= h->mb_num ||
  2941. first_mb_in_slice >= h->mb_num) {
  2942. av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
  2943. return -1;
  2944. }
  2945. h->resync_mb_x = h->mb_x = first_mb_in_slice % h->mb_width;
  2946. h->resync_mb_y = h->mb_y = (first_mb_in_slice / h->mb_width) << FIELD_OR_MBAFF_PICTURE;
  2947. if (h->picture_structure == PICT_BOTTOM_FIELD)
  2948. h->resync_mb_y = h->mb_y = h->mb_y + 1;
  2949. assert(h->mb_y < h->mb_height);
  2950. if (h->picture_structure == PICT_FRAME) {
  2951. h->curr_pic_num = h->frame_num;
  2952. h->max_pic_num = 1 << h->sps.log2_max_frame_num;
  2953. } else {
  2954. h->curr_pic_num = 2 * h->frame_num + 1;
  2955. h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1);
  2956. }
  2957. if (h->nal_unit_type == NAL_IDR_SLICE)
  2958. get_ue_golomb(&h->gb); /* idr_pic_id */
  2959. if (h->sps.poc_type == 0) {
  2960. h->poc_lsb = get_bits(&h->gb, h->sps.log2_max_poc_lsb);
  2961. if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
  2962. h->delta_poc_bottom = get_se_golomb(&h->gb);
  2963. }
  2964. if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {
  2965. h->delta_poc[0] = get_se_golomb(&h->gb);
  2966. if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
  2967. h->delta_poc[1] = get_se_golomb(&h->gb);
  2968. }
  2969. init_poc(h);
  2970. if (h->pps.redundant_pic_cnt_present)
  2971. h->redundant_pic_count = get_ue_golomb(&h->gb);
  2972. // set defaults, might be overridden a few lines later
  2973. h->ref_count[0] = h->pps.ref_count[0];
  2974. h->ref_count[1] = h->pps.ref_count[1];
  2975. if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
  2976. if (h->slice_type_nos == AV_PICTURE_TYPE_B)
  2977. h->direct_spatial_mv_pred = get_bits1(&h->gb);
  2978. num_ref_idx_active_override_flag = get_bits1(&h->gb);
  2979. if (num_ref_idx_active_override_flag) {
  2980. h->ref_count[0] = get_ue_golomb(&h->gb) + 1;
  2981. if (h->ref_count[0] < 1)
  2982. return AVERROR_INVALIDDATA;
  2983. if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
  2984. h->ref_count[1] = get_ue_golomb(&h->gb) + 1;
  2985. if (h->ref_count[1] < 1)
  2986. return AVERROR_INVALIDDATA;
  2987. }
  2988. }
  2989. if (h->slice_type_nos == AV_PICTURE_TYPE_B)
  2990. h->list_count = 2;
  2991. else
  2992. h->list_count = 1;
  2993. } else
  2994. h->list_count = 0;
  2995. max_refs = h->picture_structure == PICT_FRAME ? 16 : 32;
  2996. if (h->ref_count[0] > max_refs || h->ref_count[1] > max_refs) {
  2997. av_log(h->avctx, AV_LOG_ERROR, "reference overflow\n");
  2998. h->ref_count[0] = h->ref_count[1] = 1;
  2999. return AVERROR_INVALIDDATA;
  3000. }
  3001. if (!default_ref_list_done)
  3002. ff_h264_fill_default_ref_list(h);
  3003. if (h->slice_type_nos != AV_PICTURE_TYPE_I &&
  3004. ff_h264_decode_ref_pic_list_reordering(h) < 0) {
  3005. h->ref_count[1] = h->ref_count[0] = 0;
  3006. return -1;
  3007. }
  3008. if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||
  3009. (h->pps.weighted_bipred_idc == 1 &&
  3010. h->slice_type_nos == AV_PICTURE_TYPE_B))
  3011. pred_weight_table(h);
  3012. else if (h->pps.weighted_bipred_idc == 2 &&
  3013. h->slice_type_nos == AV_PICTURE_TYPE_B) {
  3014. implicit_weight_table(h, -1);
  3015. } else {
  3016. h->use_weight = 0;
  3017. for (i = 0; i < 2; i++) {
  3018. h->luma_weight_flag[i] = 0;
  3019. h->chroma_weight_flag[i] = 0;
  3020. }
  3021. }
  3022. // If frame-mt is enabled, only update mmco tables for the first slice
  3023. // in a field. Subsequent slices can temporarily clobber h->mmco_index
  3024. // or h->mmco, which will cause ref list mix-ups and decoding errors
  3025. // further down the line. This may break decoding if the first slice is
  3026. // corrupt, thus we only do this if frame-mt is enabled.
  3027. if (h->nal_ref_idc &&
  3028. ff_h264_decode_ref_pic_marking(h0, &h->gb,
  3029. !(h->avctx->active_thread_type & FF_THREAD_FRAME) ||
  3030. h0->current_slice == 0) < 0 &&
  3031. (h->avctx->err_recognition & AV_EF_EXPLODE))
  3032. return AVERROR_INVALIDDATA;
  3033. if (FRAME_MBAFF) {
  3034. ff_h264_fill_mbaff_ref_list(h);
  3035. if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) {
  3036. implicit_weight_table(h, 0);
  3037. implicit_weight_table(h, 1);
  3038. }
  3039. }
  3040. if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
  3041. ff_h264_direct_dist_scale_factor(h);
  3042. ff_h264_direct_ref_list_init(h);
  3043. if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {
  3044. tmp = get_ue_golomb_31(&h->gb);
  3045. if (tmp > 2) {
  3046. av_log(h->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
  3047. return -1;
  3048. }
  3049. h->cabac_init_idc = tmp;
  3050. }
  3051. h->last_qscale_diff = 0;
  3052. tmp = h->pps.init_qp + get_se_golomb(&h->gb);
  3053. if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {
  3054. av_log(h->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
  3055. return -1;
  3056. }
  3057. h->qscale = tmp;
  3058. h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
  3059. h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
  3060. // FIXME qscale / qp ... stuff
  3061. if (h->slice_type == AV_PICTURE_TYPE_SP)
  3062. get_bits1(&h->gb); /* sp_for_switch_flag */
  3063. if (h->slice_type == AV_PICTURE_TYPE_SP ||
  3064. h->slice_type == AV_PICTURE_TYPE_SI)
  3065. get_se_golomb(&h->gb); /* slice_qs_delta */
  3066. h->deblocking_filter = 1;
  3067. h->slice_alpha_c0_offset = 52;
  3068. h->slice_beta_offset = 52;
  3069. if (h->pps.deblocking_filter_parameters_present) {
  3070. tmp = get_ue_golomb_31(&h->gb);
  3071. if (tmp > 2) {
  3072. av_log(h->avctx, AV_LOG_ERROR,
  3073. "deblocking_filter_idc %u out of range\n", tmp);
  3074. return -1;
  3075. }
  3076. h->deblocking_filter = tmp;
  3077. if (h->deblocking_filter < 2)
  3078. h->deblocking_filter ^= 1; // 1<->0
  3079. if (h->deblocking_filter) {
  3080. h->slice_alpha_c0_offset += get_se_golomb(&h->gb) << 1;
  3081. h->slice_beta_offset += get_se_golomb(&h->gb) << 1;
  3082. if (h->slice_alpha_c0_offset > 104U ||
  3083. h->slice_beta_offset > 104U) {
  3084. av_log(h->avctx, AV_LOG_ERROR,
  3085. "deblocking filter parameters %d %d out of range\n",
  3086. h->slice_alpha_c0_offset, h->slice_beta_offset);
  3087. return -1;
  3088. }
  3089. }
  3090. }
  3091. if (h->avctx->skip_loop_filter >= AVDISCARD_ALL ||
  3092. (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
  3093. h->slice_type_nos != AV_PICTURE_TYPE_I) ||
  3094. (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&
  3095. h->slice_type_nos == AV_PICTURE_TYPE_B) ||
  3096. (h->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
  3097. h->nal_ref_idc == 0))
  3098. h->deblocking_filter = 0;
  3099. if (h->deblocking_filter == 1 && h0->max_contexts > 1) {
  3100. if (h->avctx->flags2 & CODEC_FLAG2_FAST) {
  3101. /* Cheat slightly for speed:
  3102. * Do not bother to deblock across slices. */
  3103. h->deblocking_filter = 2;
  3104. } else {
  3105. h0->max_contexts = 1;
  3106. if (!h0->single_decode_warning) {
  3107. av_log(h->avctx, AV_LOG_INFO,
  3108. "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
  3109. h0->single_decode_warning = 1;
  3110. }
  3111. if (h != h0) {
  3112. av_log(h->avctx, AV_LOG_ERROR,
  3113. "Deblocking switched inside frame.\n");
  3114. return 1;
  3115. }
  3116. }
  3117. }
  3118. h->qp_thresh = 15 + 52 -
  3119. FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) -
  3120. FFMAX3(0,
  3121. h->pps.chroma_qp_index_offset[0],
  3122. h->pps.chroma_qp_index_offset[1]) +
  3123. 6 * (h->sps.bit_depth_luma - 8);
  3124. h0->last_slice_type = slice_type;
  3125. h->slice_num = ++h0->current_slice;
  3126. if (h->slice_num >= MAX_SLICES) {
  3127. av_log(h->avctx, AV_LOG_ERROR,
  3128. "Too many slices, increase MAX_SLICES and recompile\n");
  3129. }
  3130. for (j = 0; j < 2; j++) {
  3131. int id_list[16];
  3132. int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j];
  3133. for (i = 0; i < 16; i++) {
  3134. id_list[i] = 60;
  3135. if (h->ref_list[j][i].f.data[0]) {
  3136. int k;
  3137. uint8_t *base = h->ref_list[j][i].f.base[0];
  3138. for (k = 0; k < h->short_ref_count; k++)
  3139. if (h->short_ref[k]->f.base[0] == base) {
  3140. id_list[i] = k;
  3141. break;
  3142. }
  3143. for (k = 0; k < h->long_ref_count; k++)
  3144. if (h->long_ref[k] && h->long_ref[k]->f.base[0] == base) {
  3145. id_list[i] = h->short_ref_count + k;
  3146. break;
  3147. }
  3148. }
  3149. }
  3150. ref2frm[0] =
  3151. ref2frm[1] = -1;
  3152. for (i = 0; i < 16; i++)
  3153. ref2frm[i + 2] = 4 * id_list[i] +
  3154. (h->ref_list[j][i].f.reference & 3);
  3155. ref2frm[18 + 0] =
  3156. ref2frm[18 + 1] = -1;
  3157. for (i = 16; i < 48; i++)
  3158. ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
  3159. (h->ref_list[j][i].f.reference & 3);
  3160. }
  3161. if (h->avctx->debug & FF_DEBUG_PICT_INFO) {
  3162. av_log(h->avctx, AV_LOG_DEBUG,
  3163. "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",
  3164. h->slice_num,
  3165. (h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
  3166. first_mb_in_slice,
  3167. av_get_picture_type_char(h->slice_type),
  3168. h->slice_type_fixed ? " fix" : "",
  3169. h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
  3170. pps_id, h->frame_num,
  3171. h->cur_pic_ptr->field_poc[0],
  3172. h->cur_pic_ptr->field_poc[1],
  3173. h->ref_count[0], h->ref_count[1],
  3174. h->qscale,
  3175. h->deblocking_filter,
  3176. h->slice_alpha_c0_offset / 2 - 26, h->slice_beta_offset / 2 - 26,
  3177. h->use_weight,
  3178. h->use_weight == 1 && h->use_weight_chroma ? "c" : "",
  3179. h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
  3180. }
  3181. return 0;
  3182. }
  3183. int ff_h264_get_slice_type(const H264Context *h)
  3184. {
  3185. switch (h->slice_type) {
  3186. case AV_PICTURE_TYPE_P:
  3187. return 0;
  3188. case AV_PICTURE_TYPE_B:
  3189. return 1;
  3190. case AV_PICTURE_TYPE_I:
  3191. return 2;
  3192. case AV_PICTURE_TYPE_SP:
  3193. return 3;
  3194. case AV_PICTURE_TYPE_SI:
  3195. return 4;
  3196. default:
  3197. return -1;
  3198. }
  3199. }
  3200. static av_always_inline void fill_filter_caches_inter(H264Context *h,
  3201. int mb_type, int top_xy,
  3202. int left_xy[LEFT_MBS],
  3203. int top_type,
  3204. int left_type[LEFT_MBS],
  3205. int mb_xy, int list)
  3206. {
  3207. int b_stride = h->b_stride;
  3208. int16_t(*mv_dst)[2] = &h->mv_cache[list][scan8[0]];
  3209. int8_t *ref_cache = &h->ref_cache[list][scan8[0]];
  3210. if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
  3211. if (USES_LIST(top_type, list)) {
  3212. const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride;
  3213. const int b8_xy = 4 * top_xy + 2;
  3214. int (*ref2frm)[64] = h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2);
  3215. AV_COPY128(mv_dst - 1 * 8, h->cur_pic.f.motion_val[list][b_xy + 0]);
  3216. ref_cache[0 - 1 * 8] =
  3217. ref_cache[1 - 1 * 8] = ref2frm[list][h->cur_pic.f.ref_index[list][b8_xy + 0]];
  3218. ref_cache[2 - 1 * 8] =
  3219. ref_cache[3 - 1 * 8] = ref2frm[list][h->cur_pic.f.ref_index[list][b8_xy + 1]];
  3220. } else {
  3221. AV_ZERO128(mv_dst - 1 * 8);
  3222. AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  3223. }
  3224. if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
  3225. if (USES_LIST(left_type[LTOP], list)) {
  3226. const int b_xy = h->mb2b_xy[left_xy[LTOP]] + 3;
  3227. const int b8_xy = 4 * left_xy[LTOP] + 1;
  3228. int (*ref2frm)[64] = h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2);
  3229. AV_COPY32(mv_dst - 1 + 0, h->cur_pic.f.motion_val[list][b_xy + b_stride * 0]);
  3230. AV_COPY32(mv_dst - 1 + 8, h->cur_pic.f.motion_val[list][b_xy + b_stride * 1]);
  3231. AV_COPY32(mv_dst - 1 + 16, h->cur_pic.f.motion_val[list][b_xy + b_stride * 2]);
  3232. AV_COPY32(mv_dst - 1 + 24, h->cur_pic.f.motion_val[list][b_xy + b_stride * 3]);
  3233. ref_cache[-1 + 0] =
  3234. ref_cache[-1 + 8] = ref2frm[list][h->cur_pic.f.ref_index[list][b8_xy + 2 * 0]];
  3235. ref_cache[-1 + 16] =
  3236. ref_cache[-1 + 24] = ref2frm[list][h->cur_pic.f.ref_index[list][b8_xy + 2 * 1]];
  3237. } else {
  3238. AV_ZERO32(mv_dst - 1 + 0);
  3239. AV_ZERO32(mv_dst - 1 + 8);
  3240. AV_ZERO32(mv_dst - 1 + 16);
  3241. AV_ZERO32(mv_dst - 1 + 24);
  3242. ref_cache[-1 + 0] =
  3243. ref_cache[-1 + 8] =
  3244. ref_cache[-1 + 16] =
  3245. ref_cache[-1 + 24] = LIST_NOT_USED;
  3246. }
  3247. }
  3248. }
  3249. if (!USES_LIST(mb_type, list)) {
  3250. fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
  3251. AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  3252. AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  3253. AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  3254. AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  3255. return;
  3256. }
  3257. {
  3258. int8_t *ref = &h->cur_pic.f.ref_index[list][4 * mb_xy];
  3259. int (*ref2frm)[64] = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2);
  3260. uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]], ref2frm[list][ref[1]]) & 0x00FF00FF) * 0x0101;
  3261. uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]], ref2frm[list][ref[3]]) & 0x00FF00FF) * 0x0101;
  3262. AV_WN32A(&ref_cache[0 * 8], ref01);
  3263. AV_WN32A(&ref_cache[1 * 8], ref01);
  3264. AV_WN32A(&ref_cache[2 * 8], ref23);
  3265. AV_WN32A(&ref_cache[3 * 8], ref23);
  3266. }
  3267. {
  3268. int16_t(*mv_src)[2] = &h->cur_pic.f.motion_val[list][4 * h->mb_x + 4 * h->mb_y * b_stride];
  3269. AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
  3270. AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
  3271. AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
  3272. AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
  3273. }
  3274. }
  3275. /**
  3276. *
  3277. * @return non zero if the loop filter can be skipped
  3278. */
  3279. static int fill_filter_caches(H264Context *h, int mb_type)
  3280. {
  3281. const int mb_xy = h->mb_xy;
  3282. int top_xy, left_xy[LEFT_MBS];
  3283. int top_type, left_type[LEFT_MBS];
  3284. uint8_t *nnz;
  3285. uint8_t *nnz_cache;
  3286. top_xy = mb_xy - (h->mb_stride << MB_FIELD);
  3287. /* Wow, what a mess, why didn't they simplify the interlacing & intra
  3288. * stuff, I can't imagine that these complex rules are worth it. */
  3289. left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
  3290. if (FRAME_MBAFF) {
  3291. const int left_mb_field_flag = IS_INTERLACED(h->cur_pic.f.mb_type[mb_xy - 1]);
  3292. const int curr_mb_field_flag = IS_INTERLACED(mb_type);
  3293. if (h->mb_y & 1) {
  3294. if (left_mb_field_flag != curr_mb_field_flag)
  3295. left_xy[LTOP] -= h->mb_stride;
  3296. } else {
  3297. if (curr_mb_field_flag)
  3298. top_xy += h->mb_stride &
  3299. (((h->cur_pic.f.mb_type[top_xy] >> 7) & 1) - 1);
  3300. if (left_mb_field_flag != curr_mb_field_flag)
  3301. left_xy[LBOT] += h->mb_stride;
  3302. }
  3303. }
  3304. h->top_mb_xy = top_xy;
  3305. h->left_mb_xy[LTOP] = left_xy[LTOP];
  3306. h->left_mb_xy[LBOT] = left_xy[LBOT];
  3307. {
  3308. /* For sufficiently low qp, filtering wouldn't do anything.
  3309. * This is a conservative estimate: could also check beta_offset
  3310. * and more accurate chroma_qp. */
  3311. int qp_thresh = h->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
  3312. int qp = h->cur_pic.f.qscale_table[mb_xy];
  3313. if (qp <= qp_thresh &&
  3314. (left_xy[LTOP] < 0 ||
  3315. ((qp + h->cur_pic.f.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
  3316. (top_xy < 0 ||
  3317. ((qp + h->cur_pic.f.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
  3318. if (!FRAME_MBAFF)
  3319. return 1;
  3320. if ((left_xy[LTOP] < 0 ||
  3321. ((qp + h->cur_pic.f.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
  3322. (top_xy < h->mb_stride ||
  3323. ((qp + h->cur_pic.f.qscale_table[top_xy - h->mb_stride] + 1) >> 1) <= qp_thresh))
  3324. return 1;
  3325. }
  3326. }
  3327. top_type = h->cur_pic.f.mb_type[top_xy];
  3328. left_type[LTOP] = h->cur_pic.f.mb_type[left_xy[LTOP]];
  3329. left_type[LBOT] = h->cur_pic.f.mb_type[left_xy[LBOT]];
  3330. if (h->deblocking_filter == 2) {
  3331. if (h->slice_table[top_xy] != h->slice_num)
  3332. top_type = 0;
  3333. if (h->slice_table[left_xy[LBOT]] != h->slice_num)
  3334. left_type[LTOP] = left_type[LBOT] = 0;
  3335. } else {
  3336. if (h->slice_table[top_xy] == 0xFFFF)
  3337. top_type = 0;
  3338. if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
  3339. left_type[LTOP] = left_type[LBOT] = 0;
  3340. }
  3341. h->top_type = top_type;
  3342. h->left_type[LTOP] = left_type[LTOP];
  3343. h->left_type[LBOT] = left_type[LBOT];
  3344. if (IS_INTRA(mb_type))
  3345. return 0;
  3346. fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
  3347. top_type, left_type, mb_xy, 0);
  3348. if (h->list_count == 2)
  3349. fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
  3350. top_type, left_type, mb_xy, 1);
  3351. nnz = h->non_zero_count[mb_xy];
  3352. nnz_cache = h->non_zero_count_cache;
  3353. AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
  3354. AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
  3355. AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
  3356. AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
  3357. h->cbp = h->cbp_table[mb_xy];
  3358. if (top_type) {
  3359. nnz = h->non_zero_count[top_xy];
  3360. AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
  3361. }
  3362. if (left_type[LTOP]) {
  3363. nnz = h->non_zero_count[left_xy[LTOP]];
  3364. nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
  3365. nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
  3366. nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
  3367. nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
  3368. }
  3369. /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
  3370. * from what the loop filter needs */
  3371. if (!CABAC && h->pps.transform_8x8_mode) {
  3372. if (IS_8x8DCT(top_type)) {
  3373. nnz_cache[4 + 8 * 0] =
  3374. nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
  3375. nnz_cache[6 + 8 * 0] =
  3376. nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
  3377. }
  3378. if (IS_8x8DCT(left_type[LTOP])) {
  3379. nnz_cache[3 + 8 * 1] =
  3380. nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
  3381. }
  3382. if (IS_8x8DCT(left_type[LBOT])) {
  3383. nnz_cache[3 + 8 * 3] =
  3384. nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
  3385. }
  3386. if (IS_8x8DCT(mb_type)) {
  3387. nnz_cache[scan8[0]] =
  3388. nnz_cache[scan8[1]] =
  3389. nnz_cache[scan8[2]] =
  3390. nnz_cache[scan8[3]] = (h->cbp & 0x1000) >> 12;
  3391. nnz_cache[scan8[0 + 4]] =
  3392. nnz_cache[scan8[1 + 4]] =
  3393. nnz_cache[scan8[2 + 4]] =
  3394. nnz_cache[scan8[3 + 4]] = (h->cbp & 0x2000) >> 12;
  3395. nnz_cache[scan8[0 + 8]] =
  3396. nnz_cache[scan8[1 + 8]] =
  3397. nnz_cache[scan8[2 + 8]] =
  3398. nnz_cache[scan8[3 + 8]] = (h->cbp & 0x4000) >> 12;
  3399. nnz_cache[scan8[0 + 12]] =
  3400. nnz_cache[scan8[1 + 12]] =
  3401. nnz_cache[scan8[2 + 12]] =
  3402. nnz_cache[scan8[3 + 12]] = (h->cbp & 0x8000) >> 12;
  3403. }
  3404. }
  3405. return 0;
  3406. }
  3407. static void loop_filter(H264Context *h, int start_x, int end_x)
  3408. {
  3409. uint8_t *dest_y, *dest_cb, *dest_cr;
  3410. int linesize, uvlinesize, mb_x, mb_y;
  3411. const int end_mb_y = h->mb_y + FRAME_MBAFF;
  3412. const int old_slice_type = h->slice_type;
  3413. const int pixel_shift = h->pixel_shift;
  3414. const int block_h = 16 >> h->chroma_y_shift;
  3415. if (h->deblocking_filter) {
  3416. for (mb_x = start_x; mb_x < end_x; mb_x++)
  3417. for (mb_y = end_mb_y - FRAME_MBAFF; mb_y <= end_mb_y; mb_y++) {
  3418. int mb_xy, mb_type;
  3419. mb_xy = h->mb_xy = mb_x + mb_y * h->mb_stride;
  3420. h->slice_num = h->slice_table[mb_xy];
  3421. mb_type = h->cur_pic.f.mb_type[mb_xy];
  3422. h->list_count = h->list_counts[mb_xy];
  3423. if (FRAME_MBAFF)
  3424. h->mb_mbaff =
  3425. h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
  3426. h->mb_x = mb_x;
  3427. h->mb_y = mb_y;
  3428. dest_y = h->cur_pic.f.data[0] +
  3429. ((mb_x << pixel_shift) + mb_y * h->linesize) * 16;
  3430. dest_cb = h->cur_pic.f.data[1] +
  3431. (mb_x << pixel_shift) * (8 << CHROMA444) +
  3432. mb_y * h->uvlinesize * block_h;
  3433. dest_cr = h->cur_pic.f.data[2] +
  3434. (mb_x << pixel_shift) * (8 << CHROMA444) +
  3435. mb_y * h->uvlinesize * block_h;
  3436. // FIXME simplify above
  3437. if (MB_FIELD) {
  3438. linesize = h->mb_linesize = h->linesize * 2;
  3439. uvlinesize = h->mb_uvlinesize = h->uvlinesize * 2;
  3440. if (mb_y & 1) { // FIXME move out of this function?
  3441. dest_y -= h->linesize * 15;
  3442. dest_cb -= h->uvlinesize * (block_h - 1);
  3443. dest_cr -= h->uvlinesize * (block_h - 1);
  3444. }
  3445. } else {
  3446. linesize = h->mb_linesize = h->linesize;
  3447. uvlinesize = h->mb_uvlinesize = h->uvlinesize;
  3448. }
  3449. backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize,
  3450. uvlinesize, 0);
  3451. if (fill_filter_caches(h, mb_type))
  3452. continue;
  3453. h->chroma_qp[0] = get_chroma_qp(h, 0, h->cur_pic.f.qscale_table[mb_xy]);
  3454. h->chroma_qp[1] = get_chroma_qp(h, 1, h->cur_pic.f.qscale_table[mb_xy]);
  3455. if (FRAME_MBAFF) {
  3456. ff_h264_filter_mb(h, mb_x, mb_y, dest_y, dest_cb, dest_cr,
  3457. linesize, uvlinesize);
  3458. } else {
  3459. ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb,
  3460. dest_cr, linesize, uvlinesize);
  3461. }
  3462. }
  3463. }
  3464. h->slice_type = old_slice_type;
  3465. h->mb_x = end_x;
  3466. h->mb_y = end_mb_y - FRAME_MBAFF;
  3467. h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
  3468. h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
  3469. }
  3470. static void predict_field_decoding_flag(H264Context *h)
  3471. {
  3472. const int mb_xy = h->mb_x + h->mb_y * h->mb_stride;
  3473. int mb_type = (h->slice_table[mb_xy - 1] == h->slice_num) ?
  3474. h->cur_pic.f.mb_type[mb_xy - 1] :
  3475. (h->slice_table[mb_xy - h->mb_stride] == h->slice_num) ?
  3476. h->cur_pic.f.mb_type[mb_xy - h->mb_stride] : 0;
  3477. h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
  3478. }
  3479. /**
  3480. * Draw edges and report progress for the last MB row.
  3481. */
  3482. static void decode_finish_row(H264Context *h)
  3483. {
  3484. int top = 16 * (h->mb_y >> FIELD_PICTURE);
  3485. int pic_height = 16 * h->mb_height >> FIELD_PICTURE;
  3486. int height = 16 << FRAME_MBAFF;
  3487. int deblock_border = (16 + 4) << FRAME_MBAFF;
  3488. if (h->deblocking_filter) {
  3489. if ((top + height) >= pic_height)
  3490. height += deblock_border;
  3491. top -= deblock_border;
  3492. }
  3493. if (top >= pic_height || (top + height) < 0)
  3494. return;
  3495. height = FFMIN(height, pic_height - top);
  3496. if (top < 0) {
  3497. height = top + height;
  3498. top = 0;
  3499. }
  3500. ff_h264_draw_horiz_band(h, top, height);
  3501. if (h->droppable)
  3502. return;
  3503. ff_thread_report_progress(&h->cur_pic_ptr->f, top + height - 1,
  3504. h->picture_structure == PICT_BOTTOM_FIELD);
  3505. }
  3506. static void er_add_slice(H264Context *h, int startx, int starty,
  3507. int endx, int endy, int status)
  3508. {
  3509. ERContext *er = &h->er;
  3510. er->ref_count = h->ref_count[0];
  3511. ff_er_add_slice(er, startx, starty, endx, endy, status);
  3512. }
  3513. static int decode_slice(struct AVCodecContext *avctx, void *arg)
  3514. {
  3515. H264Context *h = *(void **)arg;
  3516. int lf_x_start = h->mb_x;
  3517. h->mb_skip_run = -1;
  3518. h->is_complex = FRAME_MBAFF || h->picture_structure != PICT_FRAME ||
  3519. avctx->codec_id != AV_CODEC_ID_H264 ||
  3520. (CONFIG_GRAY && (h->flags & CODEC_FLAG_GRAY));
  3521. if (h->pps.cabac) {
  3522. /* realign */
  3523. align_get_bits(&h->gb);
  3524. /* init cabac */
  3525. ff_init_cabac_states(&h->cabac);
  3526. ff_init_cabac_decoder(&h->cabac,
  3527. h->gb.buffer + get_bits_count(&h->gb) / 8,
  3528. (get_bits_left(&h->gb) + 7) / 8);
  3529. ff_h264_init_cabac_states(h);
  3530. for (;;) {
  3531. // START_TIMER
  3532. int ret = ff_h264_decode_mb_cabac(h);
  3533. int eos;
  3534. // STOP_TIMER("decode_mb_cabac")
  3535. if (ret >= 0)
  3536. ff_h264_hl_decode_mb(h);
  3537. // FIXME optimal? or let mb_decode decode 16x32 ?
  3538. if (ret >= 0 && FRAME_MBAFF) {
  3539. h->mb_y++;
  3540. ret = ff_h264_decode_mb_cabac(h);
  3541. if (ret >= 0)
  3542. ff_h264_hl_decode_mb(h);
  3543. h->mb_y--;
  3544. }
  3545. eos = get_cabac_terminate(&h->cabac);
  3546. if ((h->workaround_bugs & FF_BUG_TRUNCATED) &&
  3547. h->cabac.bytestream > h->cabac.bytestream_end + 2) {
  3548. er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
  3549. h->mb_y, ER_MB_END);
  3550. if (h->mb_x >= lf_x_start)
  3551. loop_filter(h, lf_x_start, h->mb_x + 1);
  3552. return 0;
  3553. }
  3554. if (ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 2) {
  3555. av_log(h->avctx, AV_LOG_ERROR,
  3556. "error while decoding MB %d %d, bytestream (%td)\n",
  3557. h->mb_x, h->mb_y,
  3558. h->cabac.bytestream_end - h->cabac.bytestream);
  3559. er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
  3560. h->mb_y, ER_MB_ERROR);
  3561. return -1;
  3562. }
  3563. if (++h->mb_x >= h->mb_width) {
  3564. loop_filter(h, lf_x_start, h->mb_x);
  3565. h->mb_x = lf_x_start = 0;
  3566. decode_finish_row(h);
  3567. ++h->mb_y;
  3568. if (FIELD_OR_MBAFF_PICTURE) {
  3569. ++h->mb_y;
  3570. if (FRAME_MBAFF && h->mb_y < h->mb_height)
  3571. predict_field_decoding_flag(h);
  3572. }
  3573. }
  3574. if (eos || h->mb_y >= h->mb_height) {
  3575. tprintf(h->avctx, "slice end %d %d\n",
  3576. get_bits_count(&h->gb), h->gb.size_in_bits);
  3577. er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
  3578. h->mb_y, ER_MB_END);
  3579. if (h->mb_x > lf_x_start)
  3580. loop_filter(h, lf_x_start, h->mb_x);
  3581. return 0;
  3582. }
  3583. }
  3584. } else {
  3585. for (;;) {
  3586. int ret = ff_h264_decode_mb_cavlc(h);
  3587. if (ret >= 0)
  3588. ff_h264_hl_decode_mb(h);
  3589. // FIXME optimal? or let mb_decode decode 16x32 ?
  3590. if (ret >= 0 && FRAME_MBAFF) {
  3591. h->mb_y++;
  3592. ret = ff_h264_decode_mb_cavlc(h);
  3593. if (ret >= 0)
  3594. ff_h264_hl_decode_mb(h);
  3595. h->mb_y--;
  3596. }
  3597. if (ret < 0) {
  3598. av_log(h->avctx, AV_LOG_ERROR,
  3599. "error while decoding MB %d %d\n", h->mb_x, h->mb_y);
  3600. er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
  3601. h->mb_y, ER_MB_ERROR);
  3602. return -1;
  3603. }
  3604. if (++h->mb_x >= h->mb_width) {
  3605. loop_filter(h, lf_x_start, h->mb_x);
  3606. h->mb_x = lf_x_start = 0;
  3607. decode_finish_row(h);
  3608. ++h->mb_y;
  3609. if (FIELD_OR_MBAFF_PICTURE) {
  3610. ++h->mb_y;
  3611. if (FRAME_MBAFF && h->mb_y < h->mb_height)
  3612. predict_field_decoding_flag(h);
  3613. }
  3614. if (h->mb_y >= h->mb_height) {
  3615. tprintf(h->avctx, "slice end %d %d\n",
  3616. get_bits_count(&h->gb), h->gb.size_in_bits);
  3617. if (get_bits_left(&h->gb) == 0) {
  3618. er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
  3619. h->mb_x - 1, h->mb_y,
  3620. ER_MB_END);
  3621. return 0;
  3622. } else {
  3623. er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
  3624. h->mb_x - 1, h->mb_y,
  3625. ER_MB_END);
  3626. return -1;
  3627. }
  3628. }
  3629. }
  3630. if (get_bits_left(&h->gb) <= 0 && h->mb_skip_run <= 0) {
  3631. tprintf(h->avctx, "slice end %d %d\n",
  3632. get_bits_count(&h->gb), h->gb.size_in_bits);
  3633. if (get_bits_left(&h->gb) == 0) {
  3634. er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
  3635. h->mb_x - 1, h->mb_y,
  3636. ER_MB_END);
  3637. if (h->mb_x > lf_x_start)
  3638. loop_filter(h, lf_x_start, h->mb_x);
  3639. return 0;
  3640. } else {
  3641. er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
  3642. h->mb_y, ER_MB_ERROR);
  3643. return -1;
  3644. }
  3645. }
  3646. }
  3647. }
  3648. }
  3649. /**
  3650. * Call decode_slice() for each context.
  3651. *
  3652. * @param h h264 master context
  3653. * @param context_count number of contexts to execute
  3654. */
  3655. static int execute_decode_slices(H264Context *h, int context_count)
  3656. {
  3657. AVCodecContext *const avctx = h->avctx;
  3658. H264Context *hx;
  3659. int i;
  3660. if (h->avctx->hwaccel ||
  3661. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  3662. return 0;
  3663. if (context_count == 1) {
  3664. return decode_slice(avctx, &h);
  3665. } else {
  3666. for (i = 1; i < context_count; i++) {
  3667. hx = h->thread_context[i];
  3668. hx->er.error_count = 0;
  3669. }
  3670. avctx->execute(avctx, decode_slice, h->thread_context,
  3671. NULL, context_count, sizeof(void *));
  3672. /* pull back stuff from slices to master context */
  3673. hx = h->thread_context[context_count - 1];
  3674. h->mb_x = hx->mb_x;
  3675. h->mb_y = hx->mb_y;
  3676. h->droppable = hx->droppable;
  3677. h->picture_structure = hx->picture_structure;
  3678. for (i = 1; i < context_count; i++)
  3679. h->er.error_count += h->thread_context[i]->er.error_count;
  3680. }
  3681. return 0;
  3682. }
  3683. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
  3684. int parse_extradata)
  3685. {
  3686. AVCodecContext *const avctx = h->avctx;
  3687. H264Context *hx; ///< thread context
  3688. int buf_index;
  3689. int context_count;
  3690. int next_avc;
  3691. int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);
  3692. int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
  3693. int nal_index;
  3694. h->max_contexts = h->slice_context_count;
  3695. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
  3696. h->current_slice = 0;
  3697. if (!h->first_field)
  3698. h->cur_pic_ptr = NULL;
  3699. ff_h264_reset_sei(h);
  3700. }
  3701. for (; pass <= 1; pass++) {
  3702. buf_index = 0;
  3703. context_count = 0;
  3704. next_avc = h->is_avc ? 0 : buf_size;
  3705. nal_index = 0;
  3706. for (;;) {
  3707. int consumed;
  3708. int dst_length;
  3709. int bit_length;
  3710. const uint8_t *ptr;
  3711. int i, nalsize = 0;
  3712. int err;
  3713. if (buf_index >= next_avc) {
  3714. if (buf_index >= buf_size - h->nal_length_size)
  3715. break;
  3716. nalsize = 0;
  3717. for (i = 0; i < h->nal_length_size; i++)
  3718. nalsize = (nalsize << 8) | buf[buf_index++];
  3719. if (nalsize <= 0 || nalsize > buf_size - buf_index) {
  3720. av_log(h->avctx, AV_LOG_ERROR,
  3721. "AVC: nal size %d\n", nalsize);
  3722. break;
  3723. }
  3724. next_avc = buf_index + nalsize;
  3725. } else {
  3726. // start code prefix search
  3727. for (; buf_index + 3 < next_avc; buf_index++)
  3728. // This should always succeed in the first iteration.
  3729. if (buf[buf_index] == 0 &&
  3730. buf[buf_index + 1] == 0 &&
  3731. buf[buf_index + 2] == 1)
  3732. break;
  3733. if (buf_index + 3 >= buf_size) {
  3734. buf_index = buf_size;
  3735. break;
  3736. }
  3737. buf_index += 3;
  3738. if (buf_index >= next_avc)
  3739. continue;
  3740. }
  3741. hx = h->thread_context[context_count];
  3742. ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
  3743. &consumed, next_avc - buf_index);
  3744. if (ptr == NULL || dst_length < 0) {
  3745. buf_index = -1;
  3746. goto end;
  3747. }
  3748. i = buf_index + consumed;
  3749. if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
  3750. buf[i] == 0x00 && buf[i + 1] == 0x00 &&
  3751. buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
  3752. h->workaround_bugs |= FF_BUG_TRUNCATED;
  3753. if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
  3754. while (ptr[dst_length - 1] == 0 && dst_length > 0)
  3755. dst_length--;
  3756. bit_length = !dst_length ? 0
  3757. : (8 * dst_length -
  3758. decode_rbsp_trailing(h, ptr + dst_length - 1));
  3759. if (h->avctx->debug & FF_DEBUG_STARTCODE)
  3760. av_log(h->avctx, AV_LOG_DEBUG,
  3761. "NAL %d at %d/%d length %d\n",
  3762. hx->nal_unit_type, buf_index, buf_size, dst_length);
  3763. if (h->is_avc && (nalsize != consumed) && nalsize)
  3764. av_log(h->avctx, AV_LOG_DEBUG,
  3765. "AVC: Consumed only %d bytes instead of %d\n",
  3766. consumed, nalsize);
  3767. buf_index += consumed;
  3768. nal_index++;
  3769. if (pass == 0) {
  3770. /* packets can sometimes contain multiple PPS/SPS,
  3771. * e.g. two PAFF field pictures in one packet, or a demuxer
  3772. * which splits NALs strangely if so, when frame threading we
  3773. * can't start the next thread until we've read all of them */
  3774. switch (hx->nal_unit_type) {
  3775. case NAL_SPS:
  3776. case NAL_PPS:
  3777. nals_needed = nal_index;
  3778. break;
  3779. case NAL_DPA:
  3780. case NAL_IDR_SLICE:
  3781. case NAL_SLICE:
  3782. init_get_bits(&hx->gb, ptr, bit_length);
  3783. if (!get_ue_golomb(&hx->gb))
  3784. nals_needed = nal_index;
  3785. }
  3786. continue;
  3787. }
  3788. // FIXME do not discard SEI id
  3789. if (avctx->skip_frame >= AVDISCARD_NONREF && h->nal_ref_idc == 0)
  3790. continue;
  3791. again:
  3792. /* Ignore every NAL unit type except PPS and SPS during extradata
  3793. * parsing. Decoding slices is not possible in codec init
  3794. * with frame-mt */
  3795. if (parse_extradata && HAVE_THREADS &&
  3796. (h->avctx->active_thread_type & FF_THREAD_FRAME) &&
  3797. (hx->nal_unit_type != NAL_PPS &&
  3798. hx->nal_unit_type != NAL_SPS)) {
  3799. av_log(avctx, AV_LOG_INFO, "Ignoring NAL unit %d during "
  3800. "extradata parsing\n", hx->nal_unit_type);
  3801. hx->nal_unit_type = NAL_FF_IGNORE;
  3802. }
  3803. err = 0;
  3804. switch (hx->nal_unit_type) {
  3805. case NAL_IDR_SLICE:
  3806. if (h->nal_unit_type != NAL_IDR_SLICE) {
  3807. av_log(h->avctx, AV_LOG_ERROR,
  3808. "Invalid mix of idr and non-idr slices\n");
  3809. buf_index = -1;
  3810. goto end;
  3811. }
  3812. idr(h); // FIXME ensure we don't lose some frames if there is reordering
  3813. case NAL_SLICE:
  3814. init_get_bits(&hx->gb, ptr, bit_length);
  3815. hx->intra_gb_ptr =
  3816. hx->inter_gb_ptr = &hx->gb;
  3817. hx->data_partitioning = 0;
  3818. if ((err = decode_slice_header(hx, h)))
  3819. break;
  3820. h->cur_pic_ptr->f.key_frame |=
  3821. (hx->nal_unit_type == NAL_IDR_SLICE) ||
  3822. (h->sei_recovery_frame_cnt >= 0);
  3823. if (h->current_slice == 1) {
  3824. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
  3825. decode_postinit(h, nal_index >= nals_needed);
  3826. if (h->avctx->hwaccel &&
  3827. h->avctx->hwaccel->start_frame(h->avctx, NULL, 0) < 0)
  3828. return -1;
  3829. if (CONFIG_H264_VDPAU_DECODER &&
  3830. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  3831. ff_vdpau_h264_picture_start(h);
  3832. }
  3833. if (hx->redundant_pic_count == 0 &&
  3834. (avctx->skip_frame < AVDISCARD_NONREF ||
  3835. hx->nal_ref_idc) &&
  3836. (avctx->skip_frame < AVDISCARD_BIDIR ||
  3837. hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
  3838. (avctx->skip_frame < AVDISCARD_NONKEY ||
  3839. hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
  3840. avctx->skip_frame < AVDISCARD_ALL) {
  3841. if (avctx->hwaccel) {
  3842. if (avctx->hwaccel->decode_slice(avctx,
  3843. &buf[buf_index - consumed],
  3844. consumed) < 0)
  3845. return -1;
  3846. } else if (CONFIG_H264_VDPAU_DECODER &&
  3847. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
  3848. static const uint8_t start_code[] = {
  3849. 0x00, 0x00, 0x01 };
  3850. ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0], start_code,
  3851. sizeof(start_code));
  3852. ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0], &buf[buf_index - consumed],
  3853. consumed);
  3854. } else
  3855. context_count++;
  3856. }
  3857. break;
  3858. case NAL_DPA:
  3859. init_get_bits(&hx->gb, ptr, bit_length);
  3860. hx->intra_gb_ptr =
  3861. hx->inter_gb_ptr = NULL;
  3862. if ((err = decode_slice_header(hx, h)) < 0)
  3863. break;
  3864. hx->data_partitioning = 1;
  3865. break;
  3866. case NAL_DPB:
  3867. init_get_bits(&hx->intra_gb, ptr, bit_length);
  3868. hx->intra_gb_ptr = &hx->intra_gb;
  3869. break;
  3870. case NAL_DPC:
  3871. init_get_bits(&hx->inter_gb, ptr, bit_length);
  3872. hx->inter_gb_ptr = &hx->inter_gb;
  3873. if (hx->redundant_pic_count == 0 &&
  3874. hx->intra_gb_ptr &&
  3875. hx->data_partitioning &&
  3876. h->cur_pic_ptr && h->context_initialized &&
  3877. (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
  3878. (avctx->skip_frame < AVDISCARD_BIDIR ||
  3879. hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
  3880. (avctx->skip_frame < AVDISCARD_NONKEY ||
  3881. hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
  3882. avctx->skip_frame < AVDISCARD_ALL)
  3883. context_count++;
  3884. break;
  3885. case NAL_SEI:
  3886. init_get_bits(&h->gb, ptr, bit_length);
  3887. ff_h264_decode_sei(h);
  3888. break;
  3889. case NAL_SPS:
  3890. init_get_bits(&h->gb, ptr, bit_length);
  3891. if (ff_h264_decode_seq_parameter_set(h) < 0 &&
  3892. h->is_avc && (nalsize != consumed) && nalsize) {
  3893. av_log(h->avctx, AV_LOG_DEBUG,
  3894. "SPS decoding failure, trying again with the complete NAL\n");
  3895. init_get_bits(&h->gb, buf + buf_index + 1 - consumed,
  3896. 8 * (nalsize - 1));
  3897. ff_h264_decode_seq_parameter_set(h);
  3898. }
  3899. if (h264_set_parameter_from_sps(h) < 0) {
  3900. buf_index = -1;
  3901. goto end;
  3902. }
  3903. break;
  3904. case NAL_PPS:
  3905. init_get_bits(&h->gb, ptr, bit_length);
  3906. ff_h264_decode_picture_parameter_set(h, bit_length);
  3907. break;
  3908. case NAL_AUD:
  3909. case NAL_END_SEQUENCE:
  3910. case NAL_END_STREAM:
  3911. case NAL_FILLER_DATA:
  3912. case NAL_SPS_EXT:
  3913. case NAL_AUXILIARY_SLICE:
  3914. break;
  3915. case NAL_FF_IGNORE:
  3916. break;
  3917. default:
  3918. av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
  3919. hx->nal_unit_type, bit_length);
  3920. }
  3921. if (context_count == h->max_contexts) {
  3922. execute_decode_slices(h, context_count);
  3923. context_count = 0;
  3924. }
  3925. if (err < 0)
  3926. av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
  3927. else if (err == 1) {
  3928. /* Slice could not be decoded in parallel mode, copy down
  3929. * NAL unit stuff to context 0 and restart. Note that
  3930. * rbsp_buffer is not transferred, but since we no longer
  3931. * run in parallel mode this should not be an issue. */
  3932. h->nal_unit_type = hx->nal_unit_type;
  3933. h->nal_ref_idc = hx->nal_ref_idc;
  3934. hx = h;
  3935. goto again;
  3936. }
  3937. }
  3938. }
  3939. if (context_count)
  3940. execute_decode_slices(h, context_count);
  3941. end:
  3942. /* clean up */
  3943. if (h->cur_pic_ptr && h->cur_pic_ptr->owner2 == h &&
  3944. !h->droppable) {
  3945. ff_thread_report_progress(&h->cur_pic_ptr->f, INT_MAX,
  3946. h->picture_structure == PICT_BOTTOM_FIELD);
  3947. }
  3948. return buf_index;
  3949. }
  3950. /**
  3951. * Return the number of bytes consumed for building the current frame.
  3952. */
  3953. static int get_consumed_bytes(int pos, int buf_size)
  3954. {
  3955. if (pos == 0)
  3956. pos = 1; // avoid infinite loops (i doubt that is needed but ...)
  3957. if (pos + 10 > buf_size)
  3958. pos = buf_size; // oops ;)
  3959. return pos;
  3960. }
  3961. static int decode_frame(AVCodecContext *avctx, void *data,
  3962. int *got_frame, AVPacket *avpkt)
  3963. {
  3964. const uint8_t *buf = avpkt->data;
  3965. int buf_size = avpkt->size;
  3966. H264Context *h = avctx->priv_data;
  3967. AVFrame *pict = data;
  3968. int buf_index = 0;
  3969. h->flags = avctx->flags;
  3970. /* end of stream, output what is still in the buffers */
  3971. out:
  3972. if (buf_size == 0) {
  3973. Picture *out;
  3974. int i, out_idx;
  3975. h->cur_pic_ptr = NULL;
  3976. // FIXME factorize this with the output code below
  3977. out = h->delayed_pic[0];
  3978. out_idx = 0;
  3979. for (i = 1;
  3980. h->delayed_pic[i] &&
  3981. !h->delayed_pic[i]->f.key_frame &&
  3982. !h->delayed_pic[i]->mmco_reset;
  3983. i++)
  3984. if (h->delayed_pic[i]->poc < out->poc) {
  3985. out = h->delayed_pic[i];
  3986. out_idx = i;
  3987. }
  3988. for (i = out_idx; h->delayed_pic[i]; i++)
  3989. h->delayed_pic[i] = h->delayed_pic[i + 1];
  3990. if (out) {
  3991. *got_frame = 1;
  3992. *pict = out->f;
  3993. }
  3994. return buf_index;
  3995. }
  3996. buf_index = decode_nal_units(h, buf, buf_size, 0);
  3997. if (buf_index < 0)
  3998. return -1;
  3999. if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
  4000. buf_size = 0;
  4001. goto out;
  4002. }
  4003. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
  4004. if (avctx->skip_frame >= AVDISCARD_NONREF)
  4005. return 0;
  4006. av_log(avctx, AV_LOG_ERROR, "no frame!\n");
  4007. return -1;
  4008. }
  4009. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
  4010. (h->mb_y >= h->mb_height && h->mb_height)) {
  4011. if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
  4012. decode_postinit(h, 1);
  4013. field_end(h, 0);
  4014. if (!h->next_output_pic) {
  4015. /* Wait for second field. */
  4016. *got_frame = 0;
  4017. } else {
  4018. *got_frame = 1;
  4019. *pict = h->next_output_pic->f;
  4020. }
  4021. }
  4022. assert(pict->data[0] || !*got_frame);
  4023. return get_consumed_bytes(buf_index, buf_size);
  4024. }
  4025. av_cold void ff_h264_free_context(H264Context *h)
  4026. {
  4027. int i;
  4028. free_tables(h, 1); // FIXME cleanup init stuff perhaps
  4029. for (i = 0; i < MAX_SPS_COUNT; i++)
  4030. av_freep(h->sps_buffers + i);
  4031. for (i = 0; i < MAX_PPS_COUNT; i++)
  4032. av_freep(h->pps_buffers + i);
  4033. }
  4034. static av_cold int h264_decode_end(AVCodecContext *avctx)
  4035. {
  4036. H264Context *h = avctx->priv_data;
  4037. int i;
  4038. ff_h264_free_context(h);
  4039. if (h->DPB && !h->avctx->internal->is_copy) {
  4040. for (i = 0; i < h->picture_count; i++) {
  4041. free_picture(h, &h->DPB[i]);
  4042. }
  4043. }
  4044. av_freep(&h->DPB);
  4045. return 0;
  4046. }
  4047. static const AVProfile profiles[] = {
  4048. { FF_PROFILE_H264_BASELINE, "Baseline" },
  4049. { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
  4050. { FF_PROFILE_H264_MAIN, "Main" },
  4051. { FF_PROFILE_H264_EXTENDED, "Extended" },
  4052. { FF_PROFILE_H264_HIGH, "High" },
  4053. { FF_PROFILE_H264_HIGH_10, "High 10" },
  4054. { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
  4055. { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
  4056. { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
  4057. { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
  4058. { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
  4059. { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
  4060. { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
  4061. { FF_PROFILE_UNKNOWN },
  4062. };
  4063. AVCodec ff_h264_decoder = {
  4064. .name = "h264",
  4065. .type = AVMEDIA_TYPE_VIDEO,
  4066. .id = AV_CODEC_ID_H264,
  4067. .priv_data_size = sizeof(H264Context),
  4068. .init = ff_h264_decode_init,
  4069. .close = h264_decode_end,
  4070. .decode = decode_frame,
  4071. .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
  4072. CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
  4073. CODEC_CAP_FRAME_THREADS,
  4074. .flush = flush_dpb,
  4075. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
  4076. .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
  4077. .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
  4078. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  4079. };
  4080. #if CONFIG_H264_VDPAU_DECODER
  4081. AVCodec ff_h264_vdpau_decoder = {
  4082. .name = "h264_vdpau",
  4083. .type = AVMEDIA_TYPE_VIDEO,
  4084. .id = AV_CODEC_ID_H264,
  4085. .priv_data_size = sizeof(H264Context),
  4086. .init = ff_h264_decode_init,
  4087. .close = h264_decode_end,
  4088. .decode = decode_frame,
  4089. .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
  4090. .flush = flush_dpb,
  4091. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
  4092. .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
  4093. AV_PIX_FMT_NONE},
  4094. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  4095. };
  4096. #endif