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.

5124 lines
191KB

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