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.

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