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.

5077 lines
189KB

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