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.

4808 lines
178KB

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