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.

2020 lines
68KB

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