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.

5041 lines
188KB

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