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.

5090 lines
190KB

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