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.

5125 lines
191KB

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