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.

4773 lines
177KB

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