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.

4700 lines
175KB

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