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.

1794 lines
59KB

  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/avassert.h"
  27. #include "libavutil/display.h"
  28. #include "libavutil/imgutils.h"
  29. #include "libavutil/opt.h"
  30. #include "libavutil/stereo3d.h"
  31. #include "libavutil/timer.h"
  32. #include "internal.h"
  33. #include "cabac.h"
  34. #include "cabac_functions.h"
  35. #include "error_resilience.h"
  36. #include "avcodec.h"
  37. #include "h264.h"
  38. #include "h264data.h"
  39. #include "h264chroma.h"
  40. #include "h264_mvpred.h"
  41. #include "golomb.h"
  42. #include "mathops.h"
  43. #include "me_cmp.h"
  44. #include "mpegutils.h"
  45. #include "profiles.h"
  46. #include "rectangle.h"
  47. #include "svq3.h"
  48. #include "thread.h"
  49. #include <assert.h>
  50. const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
  51. static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
  52. int (*mv)[2][4][2],
  53. int mb_x, int mb_y, int mb_intra, int mb_skipped)
  54. {
  55. H264Context *h = opaque;
  56. H264SliceContext *sl = &h->slice_ctx[0];
  57. sl->mb_x = mb_x;
  58. sl->mb_y = mb_y;
  59. sl->mb_xy = mb_x + mb_y * h->mb_stride;
  60. memset(sl->non_zero_count_cache, 0, sizeof(sl->non_zero_count_cache));
  61. assert(ref >= 0);
  62. /* FIXME: It is possible albeit uncommon that slice references
  63. * differ between slices. We take the easy approach and ignore
  64. * it for now. If this turns out to have any relevance in
  65. * practice then correct remapping should be added. */
  66. if (ref >= sl->ref_count[0])
  67. ref = 0;
  68. fill_rectangle(&h->cur_pic.ref_index[0][4 * sl->mb_xy],
  69. 2, 2, 2, ref, 1);
  70. fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
  71. fill_rectangle(sl->mv_cache[0][scan8[0]], 4, 4, 8,
  72. pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
  73. assert(!FRAME_MBAFF(h));
  74. ff_h264_hl_decode_mb(h, &h->slice_ctx[0]);
  75. }
  76. void ff_h264_draw_horiz_band(const H264Context *h, H264SliceContext *sl,
  77. int y, int height)
  78. {
  79. AVCodecContext *avctx = h->avctx;
  80. const AVFrame *src = h->cur_pic.f;
  81. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
  82. int vshift = desc->log2_chroma_h;
  83. const int field_pic = h->picture_structure != PICT_FRAME;
  84. if (field_pic) {
  85. height <<= 1;
  86. y <<= 1;
  87. }
  88. height = FFMIN(height, avctx->height - y);
  89. if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
  90. return;
  91. if (avctx->draw_horiz_band) {
  92. int offset[AV_NUM_DATA_POINTERS];
  93. int i;
  94. offset[0] = y * src->linesize[0];
  95. offset[1] =
  96. offset[2] = (y >> vshift) * src->linesize[1];
  97. for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
  98. offset[i] = 0;
  99. emms_c();
  100. avctx->draw_horiz_band(avctx, src, offset,
  101. y, h->picture_structure, height);
  102. }
  103. }
  104. /**
  105. * Check if the top & left blocks are available if needed and
  106. * change the dc mode so it only uses the available blocks.
  107. */
  108. int ff_h264_check_intra4x4_pred_mode(const H264Context *h, H264SliceContext *sl)
  109. {
  110. static const int8_t top[12] = {
  111. -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
  112. };
  113. static const int8_t left[12] = {
  114. 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
  115. };
  116. int i;
  117. if (!(sl->top_samples_available & 0x8000)) {
  118. for (i = 0; i < 4; i++) {
  119. int status = top[sl->intra4x4_pred_mode_cache[scan8[0] + i]];
  120. if (status < 0) {
  121. av_log(h->avctx, AV_LOG_ERROR,
  122. "top block unavailable for requested intra4x4 mode %d at %d %d\n",
  123. status, sl->mb_x, sl->mb_y);
  124. return AVERROR_INVALIDDATA;
  125. } else if (status) {
  126. sl->intra4x4_pred_mode_cache[scan8[0] + i] = status;
  127. }
  128. }
  129. }
  130. if ((sl->left_samples_available & 0x8888) != 0x8888) {
  131. static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
  132. for (i = 0; i < 4; i++)
  133. if (!(sl->left_samples_available & mask[i])) {
  134. int status = left[sl->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
  135. if (status < 0) {
  136. av_log(h->avctx, AV_LOG_ERROR,
  137. "left block unavailable for requested intra4x4 mode %d at %d %d\n",
  138. status, sl->mb_x, sl->mb_y);
  139. return AVERROR_INVALIDDATA;
  140. } else if (status) {
  141. sl->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
  142. }
  143. }
  144. }
  145. return 0;
  146. } // FIXME cleanup like ff_h264_check_intra_pred_mode
  147. /**
  148. * Check if the top & left blocks are available if needed and
  149. * change the dc mode so it only uses the available blocks.
  150. */
  151. int ff_h264_check_intra_pred_mode(const H264Context *h, H264SliceContext *sl,
  152. int mode, int is_chroma)
  153. {
  154. static const int8_t top[4] = { LEFT_DC_PRED8x8, 1, -1, -1 };
  155. static const int8_t left[5] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
  156. if (mode > 3U) {
  157. av_log(h->avctx, AV_LOG_ERROR,
  158. "out of range intra chroma pred mode at %d %d\n",
  159. sl->mb_x, sl->mb_y);
  160. return AVERROR_INVALIDDATA;
  161. }
  162. if (!(sl->top_samples_available & 0x8000)) {
  163. mode = top[mode];
  164. if (mode < 0) {
  165. av_log(h->avctx, AV_LOG_ERROR,
  166. "top block unavailable for requested intra mode at %d %d\n",
  167. sl->mb_x, sl->mb_y);
  168. return AVERROR_INVALIDDATA;
  169. }
  170. }
  171. if ((sl->left_samples_available & 0x8080) != 0x8080) {
  172. mode = left[mode];
  173. if (is_chroma && (sl->left_samples_available & 0x8080)) {
  174. // mad cow disease mode, aka MBAFF + constrained_intra_pred
  175. mode = ALZHEIMER_DC_L0T_PRED8x8 +
  176. (!(sl->left_samples_available & 0x8000)) +
  177. 2 * (mode == DC_128_PRED8x8);
  178. }
  179. if (mode < 0) {
  180. av_log(h->avctx, AV_LOG_ERROR,
  181. "left block unavailable for requested intra mode at %d %d\n",
  182. sl->mb_x, sl->mb_y);
  183. return AVERROR_INVALIDDATA;
  184. }
  185. }
  186. return mode;
  187. }
  188. const uint8_t *ff_h264_decode_nal(H264Context *h, H264SliceContext *sl,
  189. const uint8_t *src,
  190. int *dst_length, int *consumed, int length)
  191. {
  192. int i, si, di;
  193. uint8_t *dst;
  194. // src[0]&0x80; // forbidden bit
  195. h->nal_ref_idc = src[0] >> 5;
  196. h->nal_unit_type = src[0] & 0x1F;
  197. src++;
  198. length--;
  199. #define STARTCODE_TEST \
  200. if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
  201. if (src[i + 2] != 3) { \
  202. /* startcode, so we must be past the end */ \
  203. length = i; \
  204. } \
  205. break; \
  206. }
  207. #if HAVE_FAST_UNALIGNED
  208. #define FIND_FIRST_ZERO \
  209. if (i > 0 && !src[i]) \
  210. i--; \
  211. while (src[i]) \
  212. i++
  213. #if HAVE_FAST_64BIT
  214. for (i = 0; i + 1 < length; i += 9) {
  215. if (!((~AV_RN64A(src + i) &
  216. (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
  217. 0x8000800080008080ULL))
  218. continue;
  219. FIND_FIRST_ZERO;
  220. STARTCODE_TEST;
  221. i -= 7;
  222. }
  223. #else
  224. for (i = 0; i + 1 < length; i += 5) {
  225. if (!((~AV_RN32A(src + i) &
  226. (AV_RN32A(src + i) - 0x01000101U)) &
  227. 0x80008080U))
  228. continue;
  229. FIND_FIRST_ZERO;
  230. STARTCODE_TEST;
  231. i -= 3;
  232. }
  233. #endif
  234. #else
  235. for (i = 0; i + 1 < length; i += 2) {
  236. if (src[i])
  237. continue;
  238. if (i > 0 && src[i - 1] == 0)
  239. i--;
  240. STARTCODE_TEST;
  241. }
  242. #endif
  243. if (i >= length - 1) { // no escaped 0
  244. *dst_length = length;
  245. *consumed = length + 1; // +1 for the header
  246. return src;
  247. }
  248. av_fast_malloc(&sl->rbsp_buffer, &sl->rbsp_buffer_size,
  249. length + AV_INPUT_BUFFER_PADDING_SIZE);
  250. dst = sl->rbsp_buffer;
  251. if (!dst)
  252. return NULL;
  253. memcpy(dst, src, i);
  254. si = di = i;
  255. while (si + 2 < length) {
  256. // remove escapes (very rare 1:2^22)
  257. if (src[si + 2] > 3) {
  258. dst[di++] = src[si++];
  259. dst[di++] = src[si++];
  260. } else if (src[si] == 0 && src[si + 1] == 0) {
  261. if (src[si + 2] == 3) { // escape
  262. dst[di++] = 0;
  263. dst[di++] = 0;
  264. si += 3;
  265. continue;
  266. } else // next start code
  267. goto nsc;
  268. }
  269. dst[di++] = src[si++];
  270. }
  271. while (si < length)
  272. dst[di++] = src[si++];
  273. nsc:
  274. memset(dst + di, 0, AV_INPUT_BUFFER_PADDING_SIZE);
  275. *dst_length = di;
  276. *consumed = si + 1; // +1 for the header
  277. /* FIXME store exact number of bits in the getbitcontext
  278. * (it is needed for decoding) */
  279. return dst;
  280. }
  281. /**
  282. * Identify the exact end of the bitstream
  283. * @return the length of the trailing, or 0 if damaged
  284. */
  285. static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
  286. {
  287. int v = *src;
  288. int r;
  289. ff_tlog(h->avctx, "rbsp trailing %X\n", v);
  290. for (r = 1; r < 9; r++) {
  291. if (v & 1)
  292. return r;
  293. v >>= 1;
  294. }
  295. return 0;
  296. }
  297. void ff_h264_free_tables(H264Context *h)
  298. {
  299. int i;
  300. av_freep(&h->intra4x4_pred_mode);
  301. av_freep(&h->chroma_pred_mode_table);
  302. av_freep(&h->cbp_table);
  303. av_freep(&h->mvd_table[0]);
  304. av_freep(&h->mvd_table[1]);
  305. av_freep(&h->direct_table);
  306. av_freep(&h->non_zero_count);
  307. av_freep(&h->slice_table_base);
  308. h->slice_table = NULL;
  309. av_freep(&h->list_counts);
  310. av_freep(&h->mb2b_xy);
  311. av_freep(&h->mb2br_xy);
  312. av_buffer_pool_uninit(&h->qscale_table_pool);
  313. av_buffer_pool_uninit(&h->mb_type_pool);
  314. av_buffer_pool_uninit(&h->motion_val_pool);
  315. av_buffer_pool_uninit(&h->ref_index_pool);
  316. for (i = 0; i < h->nb_slice_ctx; i++) {
  317. H264SliceContext *sl = &h->slice_ctx[i];
  318. av_freep(&sl->dc_val_base);
  319. av_freep(&sl->er.mb_index2xy);
  320. av_freep(&sl->er.error_status_table);
  321. av_freep(&sl->er.er_temp_buffer);
  322. av_freep(&sl->bipred_scratchpad);
  323. av_freep(&sl->edge_emu_buffer);
  324. av_freep(&sl->top_borders[0]);
  325. av_freep(&sl->top_borders[1]);
  326. sl->bipred_scratchpad_allocated = 0;
  327. sl->edge_emu_buffer_allocated = 0;
  328. sl->top_borders_allocated[0] = 0;
  329. sl->top_borders_allocated[1] = 0;
  330. }
  331. }
  332. int ff_h264_alloc_tables(H264Context *h)
  333. {
  334. const int big_mb_num = h->mb_stride * (h->mb_height + 1);
  335. const int row_mb_num = h->mb_stride * 2 * h->avctx->thread_count;
  336. int x, y;
  337. FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
  338. row_mb_num * 8 * sizeof(uint8_t), fail)
  339. h->slice_ctx[0].intra4x4_pred_mode = h->intra4x4_pred_mode;
  340. FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
  341. big_mb_num * 48 * sizeof(uint8_t), fail)
  342. FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
  343. (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
  344. FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
  345. big_mb_num * sizeof(uint16_t), fail)
  346. FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
  347. big_mb_num * sizeof(uint8_t), fail)
  348. FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
  349. 16 * row_mb_num * sizeof(uint8_t), fail);
  350. FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
  351. 16 * row_mb_num * sizeof(uint8_t), fail);
  352. h->slice_ctx[0].mvd_table[0] = h->mvd_table[0];
  353. h->slice_ctx[0].mvd_table[1] = h->mvd_table[1];
  354. FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
  355. 4 * big_mb_num * sizeof(uint8_t), fail);
  356. FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
  357. big_mb_num * sizeof(uint8_t), fail)
  358. memset(h->slice_table_base, -1,
  359. (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
  360. h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
  361. FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
  362. big_mb_num * sizeof(uint32_t), fail);
  363. FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
  364. big_mb_num * sizeof(uint32_t), fail);
  365. for (y = 0; y < h->mb_height; y++)
  366. for (x = 0; x < h->mb_width; x++) {
  367. const int mb_xy = x + y * h->mb_stride;
  368. const int b_xy = 4 * x + 4 * y * h->b_stride;
  369. h->mb2b_xy[mb_xy] = b_xy;
  370. h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
  371. }
  372. if (!h->dequant4_coeff[0])
  373. h264_init_dequant_tables(h);
  374. return 0;
  375. fail:
  376. ff_h264_free_tables(h);
  377. return AVERROR(ENOMEM);
  378. }
  379. /**
  380. * Init context
  381. * Allocate buffers which are not shared amongst multiple threads.
  382. */
  383. int ff_h264_slice_context_init(H264Context *h, H264SliceContext *sl)
  384. {
  385. ERContext *er = &sl->er;
  386. int mb_array_size = h->mb_height * h->mb_stride;
  387. int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
  388. int c_size = h->mb_stride * (h->mb_height + 1);
  389. int yc_size = y_size + 2 * c_size;
  390. int x, y, i;
  391. sl->ref_cache[0][scan8[5] + 1] =
  392. sl->ref_cache[0][scan8[7] + 1] =
  393. sl->ref_cache[0][scan8[13] + 1] =
  394. sl->ref_cache[1][scan8[5] + 1] =
  395. sl->ref_cache[1][scan8[7] + 1] =
  396. sl->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
  397. if (CONFIG_ERROR_RESILIENCE) {
  398. /* init ER */
  399. er->avctx = h->avctx;
  400. er->decode_mb = h264_er_decode_mb;
  401. er->opaque = h;
  402. er->quarter_sample = 1;
  403. er->mb_num = h->mb_num;
  404. er->mb_width = h->mb_width;
  405. er->mb_height = h->mb_height;
  406. er->mb_stride = h->mb_stride;
  407. er->b8_stride = h->mb_width * 2 + 1;
  408. // error resilience code looks cleaner with this
  409. FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
  410. (h->mb_num + 1) * sizeof(int), fail);
  411. for (y = 0; y < h->mb_height; y++)
  412. for (x = 0; x < h->mb_width; x++)
  413. er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
  414. er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
  415. h->mb_stride + h->mb_width;
  416. FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
  417. mb_array_size * sizeof(uint8_t), fail);
  418. FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
  419. h->mb_height * h->mb_stride, fail);
  420. FF_ALLOCZ_OR_GOTO(h->avctx, sl->dc_val_base,
  421. yc_size * sizeof(int16_t), fail);
  422. er->dc_val[0] = sl->dc_val_base + h->mb_width * 2 + 2;
  423. er->dc_val[1] = sl->dc_val_base + y_size + h->mb_stride + 1;
  424. er->dc_val[2] = er->dc_val[1] + c_size;
  425. for (i = 0; i < yc_size; i++)
  426. sl->dc_val_base[i] = 1024;
  427. }
  428. return 0;
  429. fail:
  430. return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
  431. }
  432. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
  433. int parse_extradata);
  434. int ff_h264_decode_extradata(H264Context *h)
  435. {
  436. AVCodecContext *avctx = h->avctx;
  437. int ret;
  438. if (avctx->extradata[0] == 1) {
  439. int i, cnt, nalsize;
  440. unsigned char *p = avctx->extradata;
  441. h->is_avc = 1;
  442. if (avctx->extradata_size < 7) {
  443. av_log(avctx, AV_LOG_ERROR,
  444. "avcC %d too short\n", avctx->extradata_size);
  445. return AVERROR_INVALIDDATA;
  446. }
  447. /* sps and pps in the avcC always have length coded with 2 bytes,
  448. * so put a fake nal_length_size = 2 while parsing them */
  449. h->nal_length_size = 2;
  450. // Decode sps from avcC
  451. cnt = *(p + 5) & 0x1f; // Number of sps
  452. p += 6;
  453. for (i = 0; i < cnt; i++) {
  454. nalsize = AV_RB16(p) + 2;
  455. if (p - avctx->extradata + nalsize > avctx->extradata_size)
  456. return AVERROR_INVALIDDATA;
  457. ret = decode_nal_units(h, p, nalsize, 1);
  458. if (ret < 0) {
  459. av_log(avctx, AV_LOG_ERROR,
  460. "Decoding sps %d from avcC failed\n", i);
  461. return ret;
  462. }
  463. p += nalsize;
  464. }
  465. // Decode pps from avcC
  466. cnt = *(p++); // Number of pps
  467. for (i = 0; i < cnt; i++) {
  468. nalsize = AV_RB16(p) + 2;
  469. if (p - avctx->extradata + nalsize > avctx->extradata_size)
  470. return AVERROR_INVALIDDATA;
  471. ret = decode_nal_units(h, p, nalsize, 1);
  472. if (ret < 0) {
  473. av_log(avctx, AV_LOG_ERROR,
  474. "Decoding pps %d from avcC failed\n", i);
  475. return ret;
  476. }
  477. p += nalsize;
  478. }
  479. // Store right nal length size that will be used to parse all other nals
  480. h->nal_length_size = (avctx->extradata[4] & 0x03) + 1;
  481. } else {
  482. h->is_avc = 0;
  483. ret = decode_nal_units(h, avctx->extradata, avctx->extradata_size, 1);
  484. if (ret < 0)
  485. return ret;
  486. }
  487. return 0;
  488. }
  489. static int h264_init_context(AVCodecContext *avctx, H264Context *h)
  490. {
  491. int i;
  492. h->avctx = avctx;
  493. h->dequant_coeff_pps = -1;
  494. h->picture_structure = PICT_FRAME;
  495. h->slice_context_count = 1;
  496. h->workaround_bugs = avctx->workaround_bugs;
  497. h->flags = avctx->flags;
  498. h->prev_poc_msb = 1 << 16;
  499. h->x264_build = -1;
  500. h->recovery_frame = -1;
  501. h->frame_recovered = 0;
  502. h->next_outputed_poc = INT_MIN;
  503. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  504. h->last_pocs[i] = INT_MIN;
  505. ff_h264_reset_sei(h);
  506. avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
  507. h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? H264_MAX_THREADS : 1;
  508. h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
  509. if (!h->slice_ctx) {
  510. h->nb_slice_ctx = 0;
  511. return AVERROR(ENOMEM);
  512. }
  513. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
  514. h->DPB[i].f = av_frame_alloc();
  515. if (!h->DPB[i].f)
  516. return AVERROR(ENOMEM);
  517. }
  518. h->cur_pic.f = av_frame_alloc();
  519. if (!h->cur_pic.f)
  520. return AVERROR(ENOMEM);
  521. for (i = 0; i < h->nb_slice_ctx; i++)
  522. h->slice_ctx[i].h264 = h;
  523. return 0;
  524. }
  525. static AVOnce h264_vlc_init = AV_ONCE_INIT;
  526. av_cold int ff_h264_decode_init(AVCodecContext *avctx)
  527. {
  528. H264Context *h = avctx->priv_data;
  529. int ret;
  530. ret = h264_init_context(avctx, h);
  531. if (ret < 0)
  532. return ret;
  533. /* set defaults */
  534. if (!avctx->has_b_frames)
  535. h->low_delay = 1;
  536. ret = ff_thread_once(&h264_vlc_init, ff_h264_decode_init_vlc);
  537. if (ret != 0) {
  538. av_log(avctx, AV_LOG_ERROR, "pthread_once has failed.");
  539. return AVERROR_UNKNOWN;
  540. }
  541. if (avctx->codec_id == AV_CODEC_ID_H264) {
  542. if (avctx->ticks_per_frame == 1)
  543. h->avctx->framerate.num *= 2;
  544. avctx->ticks_per_frame = 2;
  545. }
  546. if (avctx->extradata_size > 0 && avctx->extradata) {
  547. ret = ff_h264_decode_extradata(h);
  548. if (ret < 0) {
  549. ff_h264_free_context(h);
  550. return ret;
  551. }
  552. }
  553. if (h->sps.bitstream_restriction_flag &&
  554. h->avctx->has_b_frames < h->sps.num_reorder_frames) {
  555. h->avctx->has_b_frames = h->sps.num_reorder_frames;
  556. h->low_delay = 0;
  557. }
  558. avctx->internal->allocate_progress = 1;
  559. if (h->enable_er) {
  560. av_log(avctx, AV_LOG_WARNING,
  561. "Error resilience is enabled. It is unsafe and unsupported and may crash. "
  562. "Use it at your own risk\n");
  563. }
  564. return 0;
  565. }
  566. static int decode_init_thread_copy(AVCodecContext *avctx)
  567. {
  568. H264Context *h = avctx->priv_data;
  569. int ret;
  570. if (!avctx->internal->is_copy)
  571. return 0;
  572. memset(h, 0, sizeof(*h));
  573. ret = h264_init_context(avctx, h);
  574. if (ret < 0)
  575. return ret;
  576. h->context_initialized = 0;
  577. return 0;
  578. }
  579. /**
  580. * Run setup operations that must be run after slice header decoding.
  581. * This includes finding the next displayed frame.
  582. *
  583. * @param h h264 master context
  584. * @param setup_finished enough NALs have been read that we can call
  585. * ff_thread_finish_setup()
  586. */
  587. static void decode_postinit(H264Context *h, int setup_finished)
  588. {
  589. H264Picture *out = h->cur_pic_ptr;
  590. H264Picture *cur = h->cur_pic_ptr;
  591. int i, pics, out_of_order, out_idx;
  592. int invalid = 0, cnt = 0;
  593. h->cur_pic_ptr->f->pict_type = h->pict_type;
  594. if (h->next_output_pic)
  595. return;
  596. if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
  597. /* FIXME: if we have two PAFF fields in one packet, we can't start
  598. * the next thread here. If we have one field per packet, we can.
  599. * The check in decode_nal_units() is not good enough to find this
  600. * yet, so we assume the worst for now. */
  601. // if (setup_finished)
  602. // ff_thread_finish_setup(h->avctx);
  603. return;
  604. }
  605. cur->f->interlaced_frame = 0;
  606. cur->f->repeat_pict = 0;
  607. /* Signal interlacing information externally. */
  608. /* Prioritize picture timing SEI information over used
  609. * decoding process if it exists. */
  610. if (h->sps.pic_struct_present_flag) {
  611. switch (h->sei_pic_struct) {
  612. case SEI_PIC_STRUCT_FRAME:
  613. break;
  614. case SEI_PIC_STRUCT_TOP_FIELD:
  615. case SEI_PIC_STRUCT_BOTTOM_FIELD:
  616. cur->f->interlaced_frame = 1;
  617. break;
  618. case SEI_PIC_STRUCT_TOP_BOTTOM:
  619. case SEI_PIC_STRUCT_BOTTOM_TOP:
  620. if (FIELD_OR_MBAFF_PICTURE(h))
  621. cur->f->interlaced_frame = 1;
  622. else
  623. // try to flag soft telecine progressive
  624. cur->f->interlaced_frame = h->prev_interlaced_frame;
  625. break;
  626. case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
  627. case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
  628. /* Signal the possibility of telecined film externally
  629. * (pic_struct 5,6). From these hints, let the applications
  630. * decide if they apply deinterlacing. */
  631. cur->f->repeat_pict = 1;
  632. break;
  633. case SEI_PIC_STRUCT_FRAME_DOUBLING:
  634. cur->f->repeat_pict = 2;
  635. break;
  636. case SEI_PIC_STRUCT_FRAME_TRIPLING:
  637. cur->f->repeat_pict = 4;
  638. break;
  639. }
  640. if ((h->sei_ct_type & 3) &&
  641. h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
  642. cur->f->interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
  643. } else {
  644. /* Derive interlacing flag from used decoding process. */
  645. cur->f->interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
  646. }
  647. h->prev_interlaced_frame = cur->f->interlaced_frame;
  648. if (cur->field_poc[0] != cur->field_poc[1]) {
  649. /* Derive top_field_first from field pocs. */
  650. cur->f->top_field_first = cur->field_poc[0] < cur->field_poc[1];
  651. } else {
  652. if (cur->f->interlaced_frame || h->sps.pic_struct_present_flag) {
  653. /* Use picture timing SEI information. Even if it is a
  654. * information of a past frame, better than nothing. */
  655. if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
  656. h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
  657. cur->f->top_field_first = 1;
  658. else
  659. cur->f->top_field_first = 0;
  660. } else {
  661. /* Most likely progressive */
  662. cur->f->top_field_first = 0;
  663. }
  664. }
  665. if (h->sei_frame_packing_present &&
  666. h->frame_packing_arrangement_type >= 0 &&
  667. h->frame_packing_arrangement_type <= 6 &&
  668. h->content_interpretation_type > 0 &&
  669. h->content_interpretation_type < 3) {
  670. AVStereo3D *stereo = av_stereo3d_create_side_data(cur->f);
  671. if (!stereo)
  672. return;
  673. switch (h->frame_packing_arrangement_type) {
  674. case 0:
  675. stereo->type = AV_STEREO3D_CHECKERBOARD;
  676. break;
  677. case 1:
  678. stereo->type = AV_STEREO3D_COLUMNS;
  679. break;
  680. case 2:
  681. stereo->type = AV_STEREO3D_LINES;
  682. break;
  683. case 3:
  684. if (h->quincunx_subsampling)
  685. stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
  686. else
  687. stereo->type = AV_STEREO3D_SIDEBYSIDE;
  688. break;
  689. case 4:
  690. stereo->type = AV_STEREO3D_TOPBOTTOM;
  691. break;
  692. case 5:
  693. stereo->type = AV_STEREO3D_FRAMESEQUENCE;
  694. break;
  695. case 6:
  696. stereo->type = AV_STEREO3D_2D;
  697. break;
  698. }
  699. if (h->content_interpretation_type == 2)
  700. stereo->flags = AV_STEREO3D_FLAG_INVERT;
  701. }
  702. if (h->sei_display_orientation_present &&
  703. (h->sei_anticlockwise_rotation || h->sei_hflip || h->sei_vflip)) {
  704. double angle = h->sei_anticlockwise_rotation * 360 / (double) (1 << 16);
  705. AVFrameSideData *rotation = av_frame_new_side_data(cur->f,
  706. AV_FRAME_DATA_DISPLAYMATRIX,
  707. sizeof(int32_t) * 9);
  708. if (!rotation)
  709. return;
  710. av_display_rotation_set((int32_t *)rotation->data, angle);
  711. av_display_matrix_flip((int32_t *)rotation->data,
  712. h->sei_hflip, h->sei_vflip);
  713. }
  714. if (h->sei_reguserdata_afd_present) {
  715. AVFrameSideData *sd = av_frame_new_side_data(cur->f, AV_FRAME_DATA_AFD,
  716. sizeof(uint8_t));
  717. if (!sd)
  718. return;
  719. *sd->data = h->active_format_description;
  720. h->sei_reguserdata_afd_present = 0;
  721. }
  722. if (h->a53_caption) {
  723. AVFrameSideData *sd = av_frame_new_side_data(cur->f,
  724. AV_FRAME_DATA_A53_CC,
  725. h->a53_caption_size);
  726. if (!sd)
  727. return;
  728. memcpy(sd->data, h->a53_caption, h->a53_caption_size);
  729. av_freep(&h->a53_caption);
  730. h->a53_caption_size = 0;
  731. }
  732. // FIXME do something with unavailable reference frames
  733. /* Sort B-frames into display order */
  734. if (h->sps.bitstream_restriction_flag ||
  735. h->avctx->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
  736. h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, h->sps.num_reorder_frames);
  737. }
  738. h->low_delay = !h->avctx->has_b_frames;
  739. pics = 0;
  740. while (h->delayed_pic[pics])
  741. pics++;
  742. assert(pics <= MAX_DELAYED_PIC_COUNT);
  743. h->delayed_pic[pics++] = cur;
  744. if (cur->reference == 0)
  745. cur->reference = DELAYED_PIC_REF;
  746. /* Frame reordering. This code takes pictures from coding order and sorts
  747. * them by their incremental POC value into display order. It supports POC
  748. * gaps, MMCO reset codes and random resets.
  749. * A "display group" can start either with a IDR frame (f.key_frame = 1),
  750. * and/or can be closed down with a MMCO reset code. In sequences where
  751. * there is no delay, we can't detect that (since the frame was already
  752. * output to the user), so we also set h->mmco_reset to detect the MMCO
  753. * reset code.
  754. * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
  755. * we increase the delay between input and output. All frames affected by
  756. * the lag (e.g. those that should have been output before another frame
  757. * that we already returned to the user) will be dropped. This is a bug
  758. * that we will fix later. */
  759. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
  760. cnt += out->poc < h->last_pocs[i];
  761. invalid += out->poc == INT_MIN;
  762. }
  763. if (!h->mmco_reset && !cur->f->key_frame &&
  764. cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
  765. h->mmco_reset = 2;
  766. if (pics > 1)
  767. h->delayed_pic[pics - 2]->mmco_reset = 2;
  768. }
  769. if (h->mmco_reset || cur->f->key_frame) {
  770. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  771. h->last_pocs[i] = INT_MIN;
  772. cnt = 0;
  773. invalid = MAX_DELAYED_PIC_COUNT;
  774. }
  775. out = h->delayed_pic[0];
  776. out_idx = 0;
  777. for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
  778. h->delayed_pic[i] &&
  779. !h->delayed_pic[i - 1]->mmco_reset &&
  780. !h->delayed_pic[i]->f->key_frame;
  781. i++)
  782. if (h->delayed_pic[i]->poc < out->poc) {
  783. out = h->delayed_pic[i];
  784. out_idx = i;
  785. }
  786. if (h->avctx->has_b_frames == 0 &&
  787. (h->delayed_pic[0]->f->key_frame || h->mmco_reset))
  788. h->next_outputed_poc = INT_MIN;
  789. out_of_order = !out->f->key_frame && !h->mmco_reset &&
  790. (out->poc < h->next_outputed_poc);
  791. if (h->sps.bitstream_restriction_flag &&
  792. h->avctx->has_b_frames >= h->sps.num_reorder_frames) {
  793. } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
  794. h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
  795. if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
  796. h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
  797. }
  798. h->low_delay = 0;
  799. } else if (h->low_delay &&
  800. ((h->next_outputed_poc != INT_MIN &&
  801. out->poc > h->next_outputed_poc + 2) ||
  802. cur->f->pict_type == AV_PICTURE_TYPE_B)) {
  803. h->low_delay = 0;
  804. h->avctx->has_b_frames++;
  805. }
  806. if (pics > h->avctx->has_b_frames) {
  807. out->reference &= ~DELAYED_PIC_REF;
  808. // for frame threading, the owner must be the second field's thread or
  809. // else the first thread can release the picture and reuse it unsafely
  810. for (i = out_idx; h->delayed_pic[i]; i++)
  811. h->delayed_pic[i] = h->delayed_pic[i + 1];
  812. }
  813. memmove(h->last_pocs, &h->last_pocs[1],
  814. sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
  815. h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
  816. if (!out_of_order && pics > h->avctx->has_b_frames) {
  817. h->next_output_pic = out;
  818. if (out->mmco_reset) {
  819. if (out_idx > 0) {
  820. h->next_outputed_poc = out->poc;
  821. h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
  822. } else {
  823. h->next_outputed_poc = INT_MIN;
  824. }
  825. } else {
  826. if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f->key_frame) {
  827. h->next_outputed_poc = INT_MIN;
  828. } else {
  829. h->next_outputed_poc = out->poc;
  830. }
  831. }
  832. h->mmco_reset = 0;
  833. } else {
  834. av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
  835. }
  836. if (h->next_output_pic) {
  837. if (h->next_output_pic->recovered) {
  838. // We have reached an recovery point and all frames after it in
  839. // display order are "recovered".
  840. h->frame_recovered |= FRAME_RECOVERED_SEI;
  841. }
  842. h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
  843. }
  844. if (setup_finished && !h->avctx->hwaccel) {
  845. ff_thread_finish_setup(h->avctx);
  846. if (h->avctx->active_thread_type & FF_THREAD_FRAME)
  847. h->setup_finished = 1;
  848. }
  849. }
  850. int ff_pred_weight_table(H264Context *h, H264SliceContext *sl)
  851. {
  852. int list, i;
  853. int luma_def, chroma_def;
  854. sl->use_weight = 0;
  855. sl->use_weight_chroma = 0;
  856. sl->luma_log2_weight_denom = get_ue_golomb(&sl->gb);
  857. if (h->sps.chroma_format_idc)
  858. sl->chroma_log2_weight_denom = get_ue_golomb(&sl->gb);
  859. luma_def = 1 << sl->luma_log2_weight_denom;
  860. chroma_def = 1 << sl->chroma_log2_weight_denom;
  861. for (list = 0; list < 2; list++) {
  862. sl->luma_weight_flag[list] = 0;
  863. sl->chroma_weight_flag[list] = 0;
  864. for (i = 0; i < sl->ref_count[list]; i++) {
  865. int luma_weight_flag, chroma_weight_flag;
  866. luma_weight_flag = get_bits1(&sl->gb);
  867. if (luma_weight_flag) {
  868. sl->luma_weight[i][list][0] = get_se_golomb(&sl->gb);
  869. sl->luma_weight[i][list][1] = get_se_golomb(&sl->gb);
  870. if (sl->luma_weight[i][list][0] != luma_def ||
  871. sl->luma_weight[i][list][1] != 0) {
  872. sl->use_weight = 1;
  873. sl->luma_weight_flag[list] = 1;
  874. }
  875. } else {
  876. sl->luma_weight[i][list][0] = luma_def;
  877. sl->luma_weight[i][list][1] = 0;
  878. }
  879. if (h->sps.chroma_format_idc) {
  880. chroma_weight_flag = get_bits1(&sl->gb);
  881. if (chroma_weight_flag) {
  882. int j;
  883. for (j = 0; j < 2; j++) {
  884. sl->chroma_weight[i][list][j][0] = get_se_golomb(&sl->gb);
  885. sl->chroma_weight[i][list][j][1] = get_se_golomb(&sl->gb);
  886. if (sl->chroma_weight[i][list][j][0] != chroma_def ||
  887. sl->chroma_weight[i][list][j][1] != 0) {
  888. sl->use_weight_chroma = 1;
  889. sl->chroma_weight_flag[list] = 1;
  890. }
  891. }
  892. } else {
  893. int j;
  894. for (j = 0; j < 2; j++) {
  895. sl->chroma_weight[i][list][j][0] = chroma_def;
  896. sl->chroma_weight[i][list][j][1] = 0;
  897. }
  898. }
  899. }
  900. }
  901. if (sl->slice_type_nos != AV_PICTURE_TYPE_B)
  902. break;
  903. }
  904. sl->use_weight = sl->use_weight || sl->use_weight_chroma;
  905. return 0;
  906. }
  907. /**
  908. * instantaneous decoder refresh.
  909. */
  910. static void idr(H264Context *h)
  911. {
  912. ff_h264_remove_all_refs(h);
  913. h->prev_frame_num =
  914. h->prev_frame_num_offset =
  915. h->prev_poc_msb =
  916. h->prev_poc_lsb = 0;
  917. }
  918. /* forget old pics after a seek */
  919. void ff_h264_flush_change(H264Context *h)
  920. {
  921. int i;
  922. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  923. h->last_pocs[i] = INT_MIN;
  924. h->next_outputed_poc = INT_MIN;
  925. h->prev_interlaced_frame = 1;
  926. idr(h);
  927. if (h->cur_pic_ptr)
  928. h->cur_pic_ptr->reference = 0;
  929. h->first_field = 0;
  930. ff_h264_reset_sei(h);
  931. h->recovery_frame = -1;
  932. h->frame_recovered = 0;
  933. }
  934. /* forget old pics after a seek */
  935. static void flush_dpb(AVCodecContext *avctx)
  936. {
  937. H264Context *h = avctx->priv_data;
  938. int i;
  939. memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
  940. ff_h264_flush_change(h);
  941. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
  942. ff_h264_unref_picture(h, &h->DPB[i]);
  943. h->cur_pic_ptr = NULL;
  944. ff_h264_unref_picture(h, &h->cur_pic);
  945. h->mb_y = 0;
  946. ff_h264_free_tables(h);
  947. h->context_initialized = 0;
  948. }
  949. int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
  950. {
  951. const int max_frame_num = 1 << h->sps.log2_max_frame_num;
  952. int field_poc[2];
  953. h->frame_num_offset = h->prev_frame_num_offset;
  954. if (h->frame_num < h->prev_frame_num)
  955. h->frame_num_offset += max_frame_num;
  956. if (h->sps.poc_type == 0) {
  957. const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
  958. if (h->poc_lsb < h->prev_poc_lsb &&
  959. h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
  960. h->poc_msb = h->prev_poc_msb + max_poc_lsb;
  961. else if (h->poc_lsb > h->prev_poc_lsb &&
  962. h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
  963. h->poc_msb = h->prev_poc_msb - max_poc_lsb;
  964. else
  965. h->poc_msb = h->prev_poc_msb;
  966. field_poc[0] =
  967. field_poc[1] = h->poc_msb + h->poc_lsb;
  968. if (h->picture_structure == PICT_FRAME)
  969. field_poc[1] += h->delta_poc_bottom;
  970. } else if (h->sps.poc_type == 1) {
  971. int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
  972. int i;
  973. if (h->sps.poc_cycle_length != 0)
  974. abs_frame_num = h->frame_num_offset + h->frame_num;
  975. else
  976. abs_frame_num = 0;
  977. if (h->nal_ref_idc == 0 && abs_frame_num > 0)
  978. abs_frame_num--;
  979. expected_delta_per_poc_cycle = 0;
  980. for (i = 0; i < h->sps.poc_cycle_length; i++)
  981. // FIXME integrate during sps parse
  982. expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
  983. if (abs_frame_num > 0) {
  984. int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
  985. int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
  986. expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
  987. for (i = 0; i <= frame_num_in_poc_cycle; i++)
  988. expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
  989. } else
  990. expectedpoc = 0;
  991. if (h->nal_ref_idc == 0)
  992. expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
  993. field_poc[0] = expectedpoc + h->delta_poc[0];
  994. field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
  995. if (h->picture_structure == PICT_FRAME)
  996. field_poc[1] += h->delta_poc[1];
  997. } else {
  998. int poc = 2 * (h->frame_num_offset + h->frame_num);
  999. if (!h->nal_ref_idc)
  1000. poc--;
  1001. field_poc[0] = poc;
  1002. field_poc[1] = poc;
  1003. }
  1004. if (h->picture_structure != PICT_BOTTOM_FIELD)
  1005. pic_field_poc[0] = field_poc[0];
  1006. if (h->picture_structure != PICT_TOP_FIELD)
  1007. pic_field_poc[1] = field_poc[1];
  1008. *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
  1009. return 0;
  1010. }
  1011. /**
  1012. * Compute profile from profile_idc and constraint_set?_flags.
  1013. *
  1014. * @param sps SPS
  1015. *
  1016. * @return profile as defined by FF_PROFILE_H264_*
  1017. */
  1018. int ff_h264_get_profile(SPS *sps)
  1019. {
  1020. int profile = sps->profile_idc;
  1021. switch (sps->profile_idc) {
  1022. case FF_PROFILE_H264_BASELINE:
  1023. // constraint_set1_flag set to 1
  1024. profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
  1025. break;
  1026. case FF_PROFILE_H264_HIGH_10:
  1027. case FF_PROFILE_H264_HIGH_422:
  1028. case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
  1029. // constraint_set3_flag set to 1
  1030. profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
  1031. break;
  1032. }
  1033. return profile;
  1034. }
  1035. int ff_set_ref_count(H264Context *h, H264SliceContext *sl)
  1036. {
  1037. int ref_count[2], list_count;
  1038. int num_ref_idx_active_override_flag, max_refs;
  1039. // set defaults, might be overridden a few lines later
  1040. ref_count[0] = h->pps.ref_count[0];
  1041. ref_count[1] = h->pps.ref_count[1];
  1042. if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
  1043. if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
  1044. sl->direct_spatial_mv_pred = get_bits1(&sl->gb);
  1045. num_ref_idx_active_override_flag = get_bits1(&sl->gb);
  1046. if (num_ref_idx_active_override_flag) {
  1047. ref_count[0] = get_ue_golomb(&sl->gb) + 1;
  1048. if (ref_count[0] < 1)
  1049. return AVERROR_INVALIDDATA;
  1050. if (sl->slice_type_nos == AV_PICTURE_TYPE_B) {
  1051. ref_count[1] = get_ue_golomb(&sl->gb) + 1;
  1052. if (ref_count[1] < 1)
  1053. return AVERROR_INVALIDDATA;
  1054. }
  1055. }
  1056. if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
  1057. list_count = 2;
  1058. else
  1059. list_count = 1;
  1060. } else {
  1061. list_count = 0;
  1062. ref_count[0] = ref_count[1] = 0;
  1063. }
  1064. max_refs = h->picture_structure == PICT_FRAME ? 16 : 32;
  1065. if (ref_count[0] > max_refs || ref_count[1] > max_refs) {
  1066. av_log(h->avctx, AV_LOG_ERROR, "reference overflow\n");
  1067. sl->ref_count[0] = sl->ref_count[1] = 0;
  1068. return AVERROR_INVALIDDATA;
  1069. }
  1070. if (list_count != sl->list_count ||
  1071. ref_count[0] != sl->ref_count[0] ||
  1072. ref_count[1] != sl->ref_count[1]) {
  1073. sl->ref_count[0] = ref_count[0];
  1074. sl->ref_count[1] = ref_count[1];
  1075. sl->list_count = list_count;
  1076. return 1;
  1077. }
  1078. return 0;
  1079. }
  1080. static int find_start_code(const uint8_t *buf, int buf_size,
  1081. int buf_index, int next_avc)
  1082. {
  1083. // start code prefix search
  1084. for (; buf_index + 3 < next_avc; buf_index++)
  1085. // This should always succeed in the first iteration.
  1086. if (buf[buf_index] == 0 &&
  1087. buf[buf_index + 1] == 0 &&
  1088. buf[buf_index + 2] == 1)
  1089. break;
  1090. if (buf_index + 3 >= buf_size)
  1091. return buf_size;
  1092. return buf_index + 3;
  1093. }
  1094. static int get_avc_nalsize(H264Context *h, const uint8_t *buf,
  1095. int buf_size, int *buf_index)
  1096. {
  1097. int i, nalsize = 0;
  1098. if (*buf_index >= buf_size - h->nal_length_size) {
  1099. // the end of the buffer is reached, refill it.
  1100. return AVERROR(EAGAIN);
  1101. }
  1102. for (i = 0; i < h->nal_length_size; i++)
  1103. nalsize = (nalsize << 8) | buf[(*buf_index)++];
  1104. if (nalsize <= 0 || nalsize > buf_size - *buf_index) {
  1105. av_log(h->avctx, AV_LOG_ERROR,
  1106. "AVC: nal size %d\n", nalsize);
  1107. return AVERROR_INVALIDDATA;
  1108. }
  1109. return nalsize;
  1110. }
  1111. static int get_bit_length(H264Context *h, const uint8_t *buf,
  1112. const uint8_t *ptr, int dst_length,
  1113. int i, int next_avc)
  1114. {
  1115. if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
  1116. buf[i] == 0x00 && buf[i + 1] == 0x00 &&
  1117. buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
  1118. h->workaround_bugs |= FF_BUG_TRUNCATED;
  1119. if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
  1120. while (dst_length > 0 && ptr[dst_length - 1] == 0)
  1121. dst_length--;
  1122. if (!dst_length)
  1123. return 0;
  1124. return 8 * dst_length - decode_rbsp_trailing(h, ptr + dst_length - 1);
  1125. }
  1126. static int get_last_needed_nal(H264Context *h, const uint8_t *buf, int buf_size)
  1127. {
  1128. int next_avc = h->is_avc ? 0 : buf_size;
  1129. int nal_index = 0;
  1130. int buf_index = 0;
  1131. int nals_needed = 0;
  1132. while(1) {
  1133. GetBitContext gb;
  1134. int nalsize = 0;
  1135. int dst_length, bit_length, consumed;
  1136. const uint8_t *ptr;
  1137. if (buf_index >= next_avc) {
  1138. nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
  1139. if (nalsize < 0)
  1140. break;
  1141. next_avc = buf_index + nalsize;
  1142. } else {
  1143. buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
  1144. if (buf_index >= buf_size)
  1145. break;
  1146. }
  1147. ptr = ff_h264_decode_nal(h, &h->slice_ctx[0], buf + buf_index, &dst_length, &consumed,
  1148. next_avc - buf_index);
  1149. if (!ptr || dst_length < 0)
  1150. return AVERROR_INVALIDDATA;
  1151. buf_index += consumed;
  1152. bit_length = get_bit_length(h, buf, ptr, dst_length,
  1153. buf_index, next_avc);
  1154. nal_index++;
  1155. /* packets can sometimes contain multiple PPS/SPS,
  1156. * e.g. two PAFF field pictures in one packet, or a demuxer
  1157. * which splits NALs strangely if so, when frame threading we
  1158. * can't start the next thread until we've read all of them */
  1159. switch (h->nal_unit_type) {
  1160. case NAL_SPS:
  1161. case NAL_PPS:
  1162. nals_needed = nal_index;
  1163. break;
  1164. case NAL_DPA:
  1165. case NAL_IDR_SLICE:
  1166. case NAL_SLICE:
  1167. init_get_bits(&gb, ptr, bit_length);
  1168. if (!get_ue_golomb(&gb))
  1169. nals_needed = nal_index;
  1170. }
  1171. }
  1172. return nals_needed;
  1173. }
  1174. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
  1175. int parse_extradata)
  1176. {
  1177. AVCodecContext *const avctx = h->avctx;
  1178. H264SliceContext *sl;
  1179. int buf_index;
  1180. unsigned context_count;
  1181. int next_avc;
  1182. int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
  1183. int nal_index;
  1184. int ret = 0;
  1185. h->max_contexts = h->slice_context_count;
  1186. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)) {
  1187. h->current_slice = 0;
  1188. if (!h->first_field)
  1189. h->cur_pic_ptr = NULL;
  1190. ff_h264_reset_sei(h);
  1191. }
  1192. if (avctx->active_thread_type & FF_THREAD_FRAME)
  1193. nals_needed = get_last_needed_nal(h, buf, buf_size);
  1194. {
  1195. buf_index = 0;
  1196. context_count = 0;
  1197. next_avc = h->is_avc ? 0 : buf_size;
  1198. nal_index = 0;
  1199. for (;;) {
  1200. int consumed;
  1201. int dst_length;
  1202. int bit_length;
  1203. const uint8_t *ptr;
  1204. int nalsize = 0;
  1205. int err;
  1206. if (buf_index >= next_avc) {
  1207. nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
  1208. if (nalsize < 0)
  1209. break;
  1210. next_avc = buf_index + nalsize;
  1211. } else {
  1212. buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
  1213. if (buf_index >= buf_size)
  1214. break;
  1215. if (buf_index >= next_avc)
  1216. continue;
  1217. }
  1218. sl = &h->slice_ctx[context_count];
  1219. ptr = ff_h264_decode_nal(h, sl, buf + buf_index, &dst_length,
  1220. &consumed, next_avc - buf_index);
  1221. if (!ptr || dst_length < 0) {
  1222. ret = -1;
  1223. goto end;
  1224. }
  1225. bit_length = get_bit_length(h, buf, ptr, dst_length,
  1226. buf_index + consumed, next_avc);
  1227. if (h->avctx->debug & FF_DEBUG_STARTCODE)
  1228. av_log(h->avctx, AV_LOG_DEBUG,
  1229. "NAL %d at %d/%d length %d\n",
  1230. h->nal_unit_type, buf_index, buf_size, dst_length);
  1231. if (h->is_avc && (nalsize != consumed) && nalsize)
  1232. av_log(h->avctx, AV_LOG_DEBUG,
  1233. "AVC: Consumed only %d bytes instead of %d\n",
  1234. consumed, nalsize);
  1235. buf_index += consumed;
  1236. nal_index++;
  1237. if (avctx->skip_frame >= AVDISCARD_NONREF &&
  1238. h->nal_ref_idc == 0 &&
  1239. h->nal_unit_type != NAL_SEI)
  1240. continue;
  1241. again:
  1242. /* Ignore every NAL unit type except PPS and SPS during extradata
  1243. * parsing. Decoding slices is not possible in codec init
  1244. * with frame-mt */
  1245. if (parse_extradata && HAVE_THREADS &&
  1246. (h->avctx->active_thread_type & FF_THREAD_FRAME) &&
  1247. (h->nal_unit_type != NAL_PPS &&
  1248. h->nal_unit_type != NAL_SPS)) {
  1249. if (h->nal_unit_type < NAL_AUD ||
  1250. h->nal_unit_type > NAL_AUXILIARY_SLICE)
  1251. av_log(avctx, AV_LOG_INFO,
  1252. "Ignoring NAL unit %d during extradata parsing\n",
  1253. h->nal_unit_type);
  1254. h->nal_unit_type = NAL_FF_IGNORE;
  1255. }
  1256. err = 0;
  1257. switch (h->nal_unit_type) {
  1258. case NAL_IDR_SLICE:
  1259. if (h->nal_unit_type != NAL_IDR_SLICE) {
  1260. av_log(h->avctx, AV_LOG_ERROR,
  1261. "Invalid mix of idr and non-idr slices\n");
  1262. ret = -1;
  1263. goto end;
  1264. }
  1265. idr(h); // FIXME ensure we don't lose some frames if there is reordering
  1266. case NAL_SLICE:
  1267. init_get_bits(&sl->gb, ptr, bit_length);
  1268. if ((err = ff_h264_decode_slice_header(h, sl)))
  1269. break;
  1270. if (h->sei_recovery_frame_cnt >= 0 && h->recovery_frame < 0) {
  1271. h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) &
  1272. ((1 << h->sps.log2_max_frame_num) - 1);
  1273. }
  1274. h->cur_pic_ptr->f->key_frame |=
  1275. (h->nal_unit_type == NAL_IDR_SLICE) ||
  1276. (h->sei_recovery_frame_cnt >= 0);
  1277. if (h->nal_unit_type == NAL_IDR_SLICE ||
  1278. h->recovery_frame == h->frame_num) {
  1279. h->recovery_frame = -1;
  1280. h->cur_pic_ptr->recovered = 1;
  1281. }
  1282. // If we have an IDR, all frames after it in decoded order are
  1283. // "recovered".
  1284. if (h->nal_unit_type == NAL_IDR_SLICE)
  1285. h->frame_recovered |= FRAME_RECOVERED_IDR;
  1286. h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
  1287. if (h->current_slice == 1) {
  1288. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS))
  1289. decode_postinit(h, nal_index >= nals_needed);
  1290. if (h->avctx->hwaccel &&
  1291. (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
  1292. return ret;
  1293. }
  1294. if (sl->redundant_pic_count == 0 &&
  1295. (avctx->skip_frame < AVDISCARD_NONREF ||
  1296. h->nal_ref_idc) &&
  1297. (avctx->skip_frame < AVDISCARD_BIDIR ||
  1298. sl->slice_type_nos != AV_PICTURE_TYPE_B) &&
  1299. (avctx->skip_frame < AVDISCARD_NONKEY ||
  1300. h->cur_pic_ptr->f->key_frame) &&
  1301. avctx->skip_frame < AVDISCARD_ALL) {
  1302. if (avctx->hwaccel) {
  1303. ret = avctx->hwaccel->decode_slice(avctx,
  1304. &buf[buf_index - consumed],
  1305. consumed);
  1306. if (ret < 0)
  1307. return ret;
  1308. } else
  1309. context_count++;
  1310. }
  1311. break;
  1312. case NAL_DPA:
  1313. case NAL_DPB:
  1314. case NAL_DPC:
  1315. avpriv_request_sample(avctx, "data partitioning");
  1316. ret = AVERROR(ENOSYS);
  1317. goto end;
  1318. break;
  1319. case NAL_SEI:
  1320. init_get_bits(&h->gb, ptr, bit_length);
  1321. ret = ff_h264_decode_sei(h);
  1322. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1323. goto end;
  1324. break;
  1325. case NAL_SPS:
  1326. init_get_bits(&h->gb, ptr, bit_length);
  1327. ret = ff_h264_decode_seq_parameter_set(h);
  1328. if (ret < 0 && h->is_avc && (nalsize != consumed) && nalsize) {
  1329. av_log(h->avctx, AV_LOG_DEBUG,
  1330. "SPS decoding failure, trying again with the complete NAL\n");
  1331. init_get_bits(&h->gb, buf + buf_index + 1 - consumed,
  1332. 8 * (nalsize - 1));
  1333. ff_h264_decode_seq_parameter_set(h);
  1334. }
  1335. break;
  1336. case NAL_PPS:
  1337. init_get_bits(&h->gb, ptr, bit_length);
  1338. ret = ff_h264_decode_picture_parameter_set(h, bit_length);
  1339. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1340. goto end;
  1341. break;
  1342. case NAL_AUD:
  1343. case NAL_END_SEQUENCE:
  1344. case NAL_END_STREAM:
  1345. case NAL_FILLER_DATA:
  1346. case NAL_SPS_EXT:
  1347. case NAL_AUXILIARY_SLICE:
  1348. break;
  1349. case NAL_FF_IGNORE:
  1350. break;
  1351. default:
  1352. av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
  1353. h->nal_unit_type, bit_length);
  1354. }
  1355. if (context_count == h->max_contexts) {
  1356. ret = ff_h264_execute_decode_slices(h, context_count);
  1357. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1358. goto end;
  1359. context_count = 0;
  1360. }
  1361. if (err < 0) {
  1362. av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
  1363. sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
  1364. } else if (err == 1) {
  1365. /* Slice could not be decoded in parallel mode, restart. Note
  1366. * that rbsp_buffer is not transferred, but since we no longer
  1367. * run in parallel mode this should not be an issue. */
  1368. sl = &h->slice_ctx[0];
  1369. goto again;
  1370. }
  1371. }
  1372. }
  1373. if (context_count) {
  1374. ret = ff_h264_execute_decode_slices(h, context_count);
  1375. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1376. goto end;
  1377. }
  1378. ret = 0;
  1379. end:
  1380. /* clean up */
  1381. if (h->cur_pic_ptr && !h->droppable) {
  1382. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
  1383. h->picture_structure == PICT_BOTTOM_FIELD);
  1384. }
  1385. return (ret < 0) ? ret : buf_index;
  1386. }
  1387. /**
  1388. * Return the number of bytes consumed for building the current frame.
  1389. */
  1390. static int get_consumed_bytes(int pos, int buf_size)
  1391. {
  1392. if (pos == 0)
  1393. pos = 1; // avoid infinite loops (I doubt that is needed but...)
  1394. if (pos + 10 > buf_size)
  1395. pos = buf_size; // oops ;)
  1396. return pos;
  1397. }
  1398. static int output_frame(H264Context *h, AVFrame *dst, AVFrame *src)
  1399. {
  1400. int i;
  1401. int ret = av_frame_ref(dst, src);
  1402. if (ret < 0)
  1403. return ret;
  1404. if (!h->sps.crop)
  1405. return 0;
  1406. for (i = 0; i < 3; i++) {
  1407. int hshift = (i > 0) ? h->chroma_x_shift : 0;
  1408. int vshift = (i > 0) ? h->chroma_y_shift : 0;
  1409. int off = ((h->sps.crop_left >> hshift) << h->pixel_shift) +
  1410. (h->sps.crop_top >> vshift) * dst->linesize[i];
  1411. dst->data[i] += off;
  1412. }
  1413. return 0;
  1414. }
  1415. static int h264_decode_frame(AVCodecContext *avctx, void *data,
  1416. int *got_frame, AVPacket *avpkt)
  1417. {
  1418. const uint8_t *buf = avpkt->data;
  1419. int buf_size = avpkt->size;
  1420. H264Context *h = avctx->priv_data;
  1421. AVFrame *pict = data;
  1422. int buf_index = 0;
  1423. int ret;
  1424. h->flags = avctx->flags;
  1425. h->setup_finished = 0;
  1426. /* end of stream, output what is still in the buffers */
  1427. out:
  1428. if (buf_size == 0) {
  1429. H264Picture *out;
  1430. int i, out_idx;
  1431. h->cur_pic_ptr = NULL;
  1432. // FIXME factorize this with the output code below
  1433. out = h->delayed_pic[0];
  1434. out_idx = 0;
  1435. for (i = 1;
  1436. h->delayed_pic[i] &&
  1437. !h->delayed_pic[i]->f->key_frame &&
  1438. !h->delayed_pic[i]->mmco_reset;
  1439. i++)
  1440. if (h->delayed_pic[i]->poc < out->poc) {
  1441. out = h->delayed_pic[i];
  1442. out_idx = i;
  1443. }
  1444. for (i = out_idx; h->delayed_pic[i]; i++)
  1445. h->delayed_pic[i] = h->delayed_pic[i + 1];
  1446. if (out) {
  1447. ret = output_frame(h, pict, out->f);
  1448. if (ret < 0)
  1449. return ret;
  1450. *got_frame = 1;
  1451. }
  1452. return buf_index;
  1453. }
  1454. buf_index = decode_nal_units(h, buf, buf_size, 0);
  1455. if (buf_index < 0)
  1456. return AVERROR_INVALIDDATA;
  1457. if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
  1458. buf_size = 0;
  1459. goto out;
  1460. }
  1461. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
  1462. if (avctx->skip_frame >= AVDISCARD_NONREF)
  1463. return 0;
  1464. av_log(avctx, AV_LOG_ERROR, "no frame!\n");
  1465. return AVERROR_INVALIDDATA;
  1466. }
  1467. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) ||
  1468. (h->mb_y >= h->mb_height && h->mb_height)) {
  1469. if (avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)
  1470. decode_postinit(h, 1);
  1471. ff_h264_field_end(h, &h->slice_ctx[0], 0);
  1472. *got_frame = 0;
  1473. if (h->next_output_pic && ((avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT) ||
  1474. h->next_output_pic->recovered)) {
  1475. if (!h->next_output_pic->recovered)
  1476. h->next_output_pic->f->flags |= AV_FRAME_FLAG_CORRUPT;
  1477. ret = output_frame(h, pict, h->next_output_pic->f);
  1478. if (ret < 0)
  1479. return ret;
  1480. *got_frame = 1;
  1481. }
  1482. }
  1483. assert(pict->buf[0] || !*got_frame);
  1484. return get_consumed_bytes(buf_index, buf_size);
  1485. }
  1486. av_cold void ff_h264_free_context(H264Context *h)
  1487. {
  1488. int i;
  1489. ff_h264_free_tables(h);
  1490. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
  1491. ff_h264_unref_picture(h, &h->DPB[i]);
  1492. av_frame_free(&h->DPB[i].f);
  1493. }
  1494. h->cur_pic_ptr = NULL;
  1495. for (i = 0; i < h->nb_slice_ctx; i++)
  1496. av_freep(&h->slice_ctx[i].rbsp_buffer);
  1497. av_freep(&h->slice_ctx);
  1498. h->nb_slice_ctx = 0;
  1499. for (i = 0; i < MAX_SPS_COUNT; i++)
  1500. av_freep(h->sps_buffers + i);
  1501. for (i = 0; i < MAX_PPS_COUNT; i++)
  1502. av_freep(h->pps_buffers + i);
  1503. }
  1504. static av_cold int h264_decode_end(AVCodecContext *avctx)
  1505. {
  1506. H264Context *h = avctx->priv_data;
  1507. ff_h264_free_context(h);
  1508. ff_h264_unref_picture(h, &h->cur_pic);
  1509. av_frame_free(&h->cur_pic.f);
  1510. return 0;
  1511. }
  1512. #define OFFSET(x) offsetof(H264Context, x)
  1513. #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  1514. static const AVOption h264_options[] = {
  1515. { "enable_er", "Enable error resilience on damaged frames (unsafe)", OFFSET(enable_er), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD },
  1516. { NULL },
  1517. };
  1518. static const AVClass h264_class = {
  1519. .class_name = "h264",
  1520. .item_name = av_default_item_name,
  1521. .option = h264_options,
  1522. .version = LIBAVUTIL_VERSION_INT,
  1523. };
  1524. AVCodec ff_h264_decoder = {
  1525. .name = "h264",
  1526. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
  1527. .type = AVMEDIA_TYPE_VIDEO,
  1528. .id = AV_CODEC_ID_H264,
  1529. .priv_data_size = sizeof(H264Context),
  1530. .init = ff_h264_decode_init,
  1531. .close = h264_decode_end,
  1532. .decode = h264_decode_frame,
  1533. .capabilities = /*AV_CODEC_CAP_DRAW_HORIZ_BAND |*/ AV_CODEC_CAP_DR1 |
  1534. AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS |
  1535. AV_CODEC_CAP_FRAME_THREADS,
  1536. .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
  1537. .flush = flush_dpb,
  1538. .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
  1539. .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
  1540. .profiles = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
  1541. .priv_class = &h264_class,
  1542. };