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.

5036 lines
188KB

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