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.

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