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.

2027 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. static AVOnce h264_vlc_init = AV_ONCE_INIT;
  559. av_cold int ff_h264_decode_init(AVCodecContext *avctx)
  560. {
  561. H264Context *h = avctx->priv_data;
  562. int ret;
  563. ret = h264_init_context(avctx, h);
  564. if (ret < 0)
  565. return ret;
  566. /* set defaults */
  567. if (!avctx->has_b_frames)
  568. h->low_delay = 1;
  569. ret = ff_thread_once(&h264_vlc_init, ff_h264_decode_init_vlc);
  570. if (ret != 0) {
  571. av_log(avctx, AV_LOG_ERROR, "pthread_once has failed.");
  572. return AVERROR_UNKNOWN;
  573. }
  574. if (avctx->codec_id == AV_CODEC_ID_H264) {
  575. if (avctx->ticks_per_frame == 1) {
  576. if(h->avctx->time_base.den < INT_MAX/2) {
  577. h->avctx->time_base.den *= 2;
  578. } else
  579. h->avctx->time_base.num /= 2;
  580. }
  581. avctx->ticks_per_frame = 2;
  582. }
  583. if (avctx->extradata_size > 0 && avctx->extradata) {
  584. ret = ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size);
  585. if (ret < 0) {
  586. ff_h264_free_context(h);
  587. return ret;
  588. }
  589. }
  590. if (h->sps.bitstream_restriction_flag &&
  591. h->avctx->has_b_frames < h->sps.num_reorder_frames) {
  592. h->avctx->has_b_frames = h->sps.num_reorder_frames;
  593. h->low_delay = 0;
  594. }
  595. avctx->internal->allocate_progress = 1;
  596. ff_h264_flush_change(h);
  597. if (h->enable_er < 0 && (avctx->active_thread_type & FF_THREAD_SLICE))
  598. h->enable_er = 0;
  599. if (h->enable_er && (avctx->active_thread_type & FF_THREAD_SLICE)) {
  600. av_log(avctx, AV_LOG_WARNING,
  601. "Error resilience with slice threads is enabled. It is unsafe and unsupported and may crash. "
  602. "Use it at your own risk\n");
  603. }
  604. return 0;
  605. }
  606. #if HAVE_THREADS
  607. static int decode_init_thread_copy(AVCodecContext *avctx)
  608. {
  609. H264Context *h = avctx->priv_data;
  610. int ret;
  611. if (!avctx->internal->is_copy)
  612. return 0;
  613. memset(h, 0, sizeof(*h));
  614. ret = h264_init_context(avctx, h);
  615. if (ret < 0)
  616. return ret;
  617. h->context_initialized = 0;
  618. return 0;
  619. }
  620. #endif
  621. /**
  622. * Run setup operations that must be run after slice header decoding.
  623. * This includes finding the next displayed frame.
  624. *
  625. * @param h h264 master context
  626. * @param setup_finished enough NALs have been read that we can call
  627. * ff_thread_finish_setup()
  628. */
  629. static void decode_postinit(H264Context *h, int setup_finished)
  630. {
  631. H264Picture *out = h->cur_pic_ptr;
  632. H264Picture *cur = h->cur_pic_ptr;
  633. int i, pics, out_of_order, out_idx;
  634. h->cur_pic_ptr->f->pict_type = h->pict_type;
  635. if (h->next_output_pic)
  636. return;
  637. if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
  638. /* FIXME: if we have two PAFF fields in one packet, we can't start
  639. * the next thread here. If we have one field per packet, we can.
  640. * The check in decode_nal_units() is not good enough to find this
  641. * yet, so we assume the worst for now. */
  642. // if (setup_finished)
  643. // ff_thread_finish_setup(h->avctx);
  644. if (cur->field_poc[0] == INT_MAX && cur->field_poc[1] == INT_MAX)
  645. return;
  646. if (h->avctx->hwaccel || h->missing_fields <=1)
  647. return;
  648. }
  649. cur->f->interlaced_frame = 0;
  650. cur->f->repeat_pict = 0;
  651. /* Signal interlacing information externally. */
  652. /* Prioritize picture timing SEI information over used
  653. * decoding process if it exists. */
  654. if (h->sps.pic_struct_present_flag) {
  655. switch (h->sei_pic_struct) {
  656. case SEI_PIC_STRUCT_FRAME:
  657. break;
  658. case SEI_PIC_STRUCT_TOP_FIELD:
  659. case SEI_PIC_STRUCT_BOTTOM_FIELD:
  660. cur->f->interlaced_frame = 1;
  661. break;
  662. case SEI_PIC_STRUCT_TOP_BOTTOM:
  663. case SEI_PIC_STRUCT_BOTTOM_TOP:
  664. if (FIELD_OR_MBAFF_PICTURE(h))
  665. cur->f->interlaced_frame = 1;
  666. else
  667. // try to flag soft telecine progressive
  668. cur->f->interlaced_frame = h->prev_interlaced_frame;
  669. break;
  670. case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
  671. case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
  672. /* Signal the possibility of telecined film externally
  673. * (pic_struct 5,6). From these hints, let the applications
  674. * decide if they apply deinterlacing. */
  675. cur->f->repeat_pict = 1;
  676. break;
  677. case SEI_PIC_STRUCT_FRAME_DOUBLING:
  678. cur->f->repeat_pict = 2;
  679. break;
  680. case SEI_PIC_STRUCT_FRAME_TRIPLING:
  681. cur->f->repeat_pict = 4;
  682. break;
  683. }
  684. if ((h->sei_ct_type & 3) &&
  685. h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
  686. cur->f->interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
  687. } else {
  688. /* Derive interlacing flag from used decoding process. */
  689. cur->f->interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
  690. }
  691. h->prev_interlaced_frame = cur->f->interlaced_frame;
  692. if (cur->field_poc[0] != cur->field_poc[1]) {
  693. /* Derive top_field_first from field pocs. */
  694. cur->f->top_field_first = cur->field_poc[0] < cur->field_poc[1];
  695. } else {
  696. if (h->sps.pic_struct_present_flag) {
  697. /* Use picture timing SEI information. Even if it is a
  698. * information of a past frame, better than nothing. */
  699. if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
  700. h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
  701. cur->f->top_field_first = 1;
  702. else
  703. cur->f->top_field_first = 0;
  704. } else if (cur->f->interlaced_frame) {
  705. /* Default to top field first when pic_struct_present_flag
  706. * is not set but interlaced frame detected */
  707. cur->f->top_field_first = 1;
  708. } else {
  709. /* Most likely progressive */
  710. cur->f->top_field_first = 0;
  711. }
  712. }
  713. if (h->sei_frame_packing_present &&
  714. h->frame_packing_arrangement_type >= 0 &&
  715. h->frame_packing_arrangement_type <= 6 &&
  716. h->content_interpretation_type > 0 &&
  717. h->content_interpretation_type < 3) {
  718. AVStereo3D *stereo = av_stereo3d_create_side_data(cur->f);
  719. if (stereo) {
  720. switch (h->frame_packing_arrangement_type) {
  721. case 0:
  722. stereo->type = AV_STEREO3D_CHECKERBOARD;
  723. break;
  724. case 1:
  725. stereo->type = AV_STEREO3D_COLUMNS;
  726. break;
  727. case 2:
  728. stereo->type = AV_STEREO3D_LINES;
  729. break;
  730. case 3:
  731. if (h->quincunx_subsampling)
  732. stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
  733. else
  734. stereo->type = AV_STEREO3D_SIDEBYSIDE;
  735. break;
  736. case 4:
  737. stereo->type = AV_STEREO3D_TOPBOTTOM;
  738. break;
  739. case 5:
  740. stereo->type = AV_STEREO3D_FRAMESEQUENCE;
  741. break;
  742. case 6:
  743. stereo->type = AV_STEREO3D_2D;
  744. break;
  745. }
  746. if (h->content_interpretation_type == 2)
  747. stereo->flags = AV_STEREO3D_FLAG_INVERT;
  748. }
  749. }
  750. if (h->sei_display_orientation_present &&
  751. (h->sei_anticlockwise_rotation || h->sei_hflip || h->sei_vflip)) {
  752. double angle = h->sei_anticlockwise_rotation * 360 / (double) (1 << 16);
  753. AVFrameSideData *rotation = av_frame_new_side_data(cur->f,
  754. AV_FRAME_DATA_DISPLAYMATRIX,
  755. sizeof(int32_t) * 9);
  756. if (rotation) {
  757. av_display_rotation_set((int32_t *)rotation->data, angle);
  758. av_display_matrix_flip((int32_t *)rotation->data,
  759. h->sei_hflip, h->sei_vflip);
  760. }
  761. }
  762. if (h->sei_reguserdata_afd_present) {
  763. AVFrameSideData *sd = av_frame_new_side_data(cur->f, AV_FRAME_DATA_AFD,
  764. sizeof(uint8_t));
  765. if (sd) {
  766. *sd->data = h->active_format_description;
  767. h->sei_reguserdata_afd_present = 0;
  768. }
  769. }
  770. if (h->a53_caption) {
  771. AVFrameSideData *sd = av_frame_new_side_data(cur->f,
  772. AV_FRAME_DATA_A53_CC,
  773. h->a53_caption_size);
  774. if (sd)
  775. memcpy(sd->data, h->a53_caption, h->a53_caption_size);
  776. av_freep(&h->a53_caption);
  777. h->a53_caption_size = 0;
  778. h->avctx->properties |= FF_CODEC_PROPERTY_CLOSED_CAPTIONS;
  779. }
  780. cur->mmco_reset = h->mmco_reset;
  781. h->mmco_reset = 0;
  782. // FIXME do something with unavailable reference frames
  783. /* Sort B-frames into display order */
  784. if (h->sps.bitstream_restriction_flag ||
  785. h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
  786. h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, h->sps.num_reorder_frames);
  787. }
  788. h->low_delay = !h->avctx->has_b_frames;
  789. for (i = 0; 1; i++) {
  790. if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
  791. if(i)
  792. h->last_pocs[i-1] = cur->poc;
  793. break;
  794. } else if(i) {
  795. h->last_pocs[i-1]= h->last_pocs[i];
  796. }
  797. }
  798. out_of_order = MAX_DELAYED_PIC_COUNT - i;
  799. if( cur->f->pict_type == AV_PICTURE_TYPE_B
  800. || (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))
  801. out_of_order = FFMAX(out_of_order, 1);
  802. if (out_of_order == MAX_DELAYED_PIC_COUNT) {
  803. av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
  804. for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
  805. h->last_pocs[i] = INT_MIN;
  806. h->last_pocs[0] = cur->poc;
  807. cur->mmco_reset = 1;
  808. } else if(h->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
  809. av_log(h->avctx, AV_LOG_VERBOSE, "Increasing reorder buffer to %d\n", out_of_order);
  810. h->avctx->has_b_frames = out_of_order;
  811. h->low_delay = 0;
  812. }
  813. pics = 0;
  814. while (h->delayed_pic[pics])
  815. pics++;
  816. av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
  817. h->delayed_pic[pics++] = cur;
  818. if (cur->reference == 0)
  819. cur->reference = DELAYED_PIC_REF;
  820. out = h->delayed_pic[0];
  821. out_idx = 0;
  822. for (i = 1; h->delayed_pic[i] &&
  823. !h->delayed_pic[i]->f->key_frame &&
  824. !h->delayed_pic[i]->mmco_reset;
  825. i++)
  826. if (h->delayed_pic[i]->poc < out->poc) {
  827. out = h->delayed_pic[i];
  828. out_idx = i;
  829. }
  830. if (h->avctx->has_b_frames == 0 &&
  831. (h->delayed_pic[0]->f->key_frame || h->delayed_pic[0]->mmco_reset))
  832. h->next_outputed_poc = INT_MIN;
  833. out_of_order = out->poc < h->next_outputed_poc;
  834. if (out_of_order || pics > h->avctx->has_b_frames) {
  835. out->reference &= ~DELAYED_PIC_REF;
  836. // for frame threading, the owner must be the second field's thread or
  837. // else the first thread can release the picture and reuse it unsafely
  838. for (i = out_idx; h->delayed_pic[i]; i++)
  839. h->delayed_pic[i] = h->delayed_pic[i + 1];
  840. }
  841. if (!out_of_order && pics > h->avctx->has_b_frames) {
  842. h->next_output_pic = out;
  843. if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f->key_frame || h->delayed_pic[0]->mmco_reset)) {
  844. h->next_outputed_poc = INT_MIN;
  845. } else
  846. h->next_outputed_poc = out->poc;
  847. } else {
  848. av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
  849. }
  850. if (h->next_output_pic) {
  851. if (h->next_output_pic->recovered) {
  852. // We have reached an recovery point and all frames after it in
  853. // display order are "recovered".
  854. h->frame_recovered |= FRAME_RECOVERED_SEI;
  855. }
  856. h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
  857. }
  858. if (setup_finished && !h->avctx->hwaccel) {
  859. ff_thread_finish_setup(h->avctx);
  860. if (h->avctx->active_thread_type & FF_THREAD_FRAME)
  861. h->setup_finished = 1;
  862. }
  863. }
  864. int ff_pred_weight_table(H264Context *h, H264SliceContext *sl)
  865. {
  866. int list, i;
  867. int luma_def, chroma_def;
  868. sl->use_weight = 0;
  869. sl->use_weight_chroma = 0;
  870. sl->luma_log2_weight_denom = get_ue_golomb(&sl->gb);
  871. if (h->sps.chroma_format_idc)
  872. sl->chroma_log2_weight_denom = get_ue_golomb(&sl->gb);
  873. if (sl->luma_log2_weight_denom > 7U) {
  874. av_log(h->avctx, AV_LOG_ERROR, "luma_log2_weight_denom %d is out of range\n", sl->luma_log2_weight_denom);
  875. sl->luma_log2_weight_denom = 0;
  876. }
  877. if (sl->chroma_log2_weight_denom > 7U) {
  878. av_log(h->avctx, AV_LOG_ERROR, "chroma_log2_weight_denom %d is out of range\n", sl->chroma_log2_weight_denom);
  879. sl->chroma_log2_weight_denom = 0;
  880. }
  881. luma_def = 1 << sl->luma_log2_weight_denom;
  882. chroma_def = 1 << sl->chroma_log2_weight_denom;
  883. for (list = 0; list < 2; list++) {
  884. sl->luma_weight_flag[list] = 0;
  885. sl->chroma_weight_flag[list] = 0;
  886. for (i = 0; i < sl->ref_count[list]; i++) {
  887. int luma_weight_flag, chroma_weight_flag;
  888. luma_weight_flag = get_bits1(&sl->gb);
  889. if (luma_weight_flag) {
  890. sl->luma_weight[i][list][0] = get_se_golomb(&sl->gb);
  891. sl->luma_weight[i][list][1] = get_se_golomb(&sl->gb);
  892. if (sl->luma_weight[i][list][0] != luma_def ||
  893. sl->luma_weight[i][list][1] != 0) {
  894. sl->use_weight = 1;
  895. sl->luma_weight_flag[list] = 1;
  896. }
  897. } else {
  898. sl->luma_weight[i][list][0] = luma_def;
  899. sl->luma_weight[i][list][1] = 0;
  900. }
  901. if (h->sps.chroma_format_idc) {
  902. chroma_weight_flag = get_bits1(&sl->gb);
  903. if (chroma_weight_flag) {
  904. int j;
  905. for (j = 0; j < 2; j++) {
  906. sl->chroma_weight[i][list][j][0] = get_se_golomb(&sl->gb);
  907. sl->chroma_weight[i][list][j][1] = get_se_golomb(&sl->gb);
  908. if (sl->chroma_weight[i][list][j][0] != chroma_def ||
  909. sl->chroma_weight[i][list][j][1] != 0) {
  910. sl->use_weight_chroma = 1;
  911. sl->chroma_weight_flag[list] = 1;
  912. }
  913. }
  914. } else {
  915. int j;
  916. for (j = 0; j < 2; j++) {
  917. sl->chroma_weight[i][list][j][0] = chroma_def;
  918. sl->chroma_weight[i][list][j][1] = 0;
  919. }
  920. }
  921. }
  922. }
  923. if (sl->slice_type_nos != AV_PICTURE_TYPE_B)
  924. break;
  925. }
  926. sl->use_weight = sl->use_weight || sl->use_weight_chroma;
  927. return 0;
  928. }
  929. /**
  930. * instantaneous decoder refresh.
  931. */
  932. static void idr(H264Context *h)
  933. {
  934. int i;
  935. ff_h264_remove_all_refs(h);
  936. h->prev_frame_num =
  937. h->prev_frame_num_offset = 0;
  938. h->prev_poc_msb = 1<<16;
  939. h->prev_poc_lsb = 0;
  940. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  941. h->last_pocs[i] = INT_MIN;
  942. }
  943. /* forget old pics after a seek */
  944. void ff_h264_flush_change(H264Context *h)
  945. {
  946. int i, j;
  947. h->next_outputed_poc = INT_MIN;
  948. h->prev_interlaced_frame = 1;
  949. idr(h);
  950. h->prev_frame_num = -1;
  951. if (h->cur_pic_ptr) {
  952. h->cur_pic_ptr->reference = 0;
  953. for (j=i=0; h->delayed_pic[i]; i++)
  954. if (h->delayed_pic[i] != h->cur_pic_ptr)
  955. h->delayed_pic[j++] = h->delayed_pic[i];
  956. h->delayed_pic[j] = NULL;
  957. }
  958. ff_h264_unref_picture(h, &h->last_pic_for_ec);
  959. h->first_field = 0;
  960. ff_h264_reset_sei(h);
  961. h->recovery_frame = -1;
  962. h->frame_recovered = 0;
  963. h->current_slice = 0;
  964. h->mmco_reset = 1;
  965. for (i = 0; i < h->nb_slice_ctx; i++)
  966. h->slice_ctx[i].list_count = 0;
  967. }
  968. /* forget old pics after a seek */
  969. static void flush_dpb(AVCodecContext *avctx)
  970. {
  971. H264Context *h = avctx->priv_data;
  972. int i;
  973. memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
  974. ff_h264_flush_change(h);
  975. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
  976. ff_h264_unref_picture(h, &h->DPB[i]);
  977. h->cur_pic_ptr = NULL;
  978. ff_h264_unref_picture(h, &h->cur_pic);
  979. h->mb_y = 0;
  980. ff_h264_free_tables(h);
  981. h->context_initialized = 0;
  982. }
  983. int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
  984. {
  985. const int max_frame_num = 1 << h->sps.log2_max_frame_num;
  986. int field_poc[2];
  987. h->frame_num_offset = h->prev_frame_num_offset;
  988. if (h->frame_num < h->prev_frame_num)
  989. h->frame_num_offset += max_frame_num;
  990. if (h->sps.poc_type == 0) {
  991. const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
  992. if (h->poc_lsb < h->prev_poc_lsb &&
  993. h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
  994. h->poc_msb = h->prev_poc_msb + max_poc_lsb;
  995. else if (h->poc_lsb > h->prev_poc_lsb &&
  996. h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
  997. h->poc_msb = h->prev_poc_msb - max_poc_lsb;
  998. else
  999. h->poc_msb = h->prev_poc_msb;
  1000. field_poc[0] =
  1001. field_poc[1] = h->poc_msb + h->poc_lsb;
  1002. if (h->picture_structure == PICT_FRAME)
  1003. field_poc[1] += h->delta_poc_bottom;
  1004. } else if (h->sps.poc_type == 1) {
  1005. int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
  1006. int i;
  1007. if (h->sps.poc_cycle_length != 0)
  1008. abs_frame_num = h->frame_num_offset + h->frame_num;
  1009. else
  1010. abs_frame_num = 0;
  1011. if (h->nal_ref_idc == 0 && abs_frame_num > 0)
  1012. abs_frame_num--;
  1013. expected_delta_per_poc_cycle = 0;
  1014. for (i = 0; i < h->sps.poc_cycle_length; i++)
  1015. // FIXME integrate during sps parse
  1016. expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
  1017. if (abs_frame_num > 0) {
  1018. int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
  1019. int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
  1020. expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
  1021. for (i = 0; i <= frame_num_in_poc_cycle; i++)
  1022. expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
  1023. } else
  1024. expectedpoc = 0;
  1025. if (h->nal_ref_idc == 0)
  1026. expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
  1027. field_poc[0] = expectedpoc + h->delta_poc[0];
  1028. field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
  1029. if (h->picture_structure == PICT_FRAME)
  1030. field_poc[1] += h->delta_poc[1];
  1031. } else {
  1032. int poc = 2 * (h->frame_num_offset + h->frame_num);
  1033. if (!h->nal_ref_idc)
  1034. poc--;
  1035. field_poc[0] = poc;
  1036. field_poc[1] = poc;
  1037. }
  1038. if (h->picture_structure != PICT_BOTTOM_FIELD)
  1039. pic_field_poc[0] = field_poc[0];
  1040. if (h->picture_structure != PICT_TOP_FIELD)
  1041. pic_field_poc[1] = field_poc[1];
  1042. *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
  1043. return 0;
  1044. }
  1045. /**
  1046. * Compute profile from profile_idc and constraint_set?_flags.
  1047. *
  1048. * @param sps SPS
  1049. *
  1050. * @return profile as defined by FF_PROFILE_H264_*
  1051. */
  1052. int ff_h264_get_profile(SPS *sps)
  1053. {
  1054. int profile = sps->profile_idc;
  1055. switch (sps->profile_idc) {
  1056. case FF_PROFILE_H264_BASELINE:
  1057. // constraint_set1_flag set to 1
  1058. profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
  1059. break;
  1060. case FF_PROFILE_H264_HIGH_10:
  1061. case FF_PROFILE_H264_HIGH_422:
  1062. case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
  1063. // constraint_set3_flag set to 1
  1064. profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
  1065. break;
  1066. }
  1067. return profile;
  1068. }
  1069. int ff_set_ref_count(H264Context *h, H264SliceContext *sl)
  1070. {
  1071. int ref_count[2], list_count;
  1072. int num_ref_idx_active_override_flag;
  1073. // set defaults, might be overridden a few lines later
  1074. ref_count[0] = h->pps.ref_count[0];
  1075. ref_count[1] = h->pps.ref_count[1];
  1076. if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
  1077. unsigned max[2];
  1078. max[0] = max[1] = h->picture_structure == PICT_FRAME ? 15 : 31;
  1079. if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
  1080. sl->direct_spatial_mv_pred = get_bits1(&sl->gb);
  1081. num_ref_idx_active_override_flag = get_bits1(&sl->gb);
  1082. if (num_ref_idx_active_override_flag) {
  1083. ref_count[0] = get_ue_golomb(&sl->gb) + 1;
  1084. if (sl->slice_type_nos == AV_PICTURE_TYPE_B) {
  1085. ref_count[1] = get_ue_golomb(&sl->gb) + 1;
  1086. } else
  1087. // full range is spec-ok in this case, even for frames
  1088. ref_count[1] = 1;
  1089. }
  1090. if (ref_count[0]-1 > max[0] || ref_count[1]-1 > max[1]){
  1091. 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]);
  1092. sl->ref_count[0] = sl->ref_count[1] = 0;
  1093. sl->list_count = 0;
  1094. return AVERROR_INVALIDDATA;
  1095. }
  1096. if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
  1097. list_count = 2;
  1098. else
  1099. list_count = 1;
  1100. } else {
  1101. list_count = 0;
  1102. ref_count[0] = ref_count[1] = 0;
  1103. }
  1104. if (list_count != sl->list_count ||
  1105. ref_count[0] != sl->ref_count[0] ||
  1106. ref_count[1] != sl->ref_count[1]) {
  1107. sl->ref_count[0] = ref_count[0];
  1108. sl->ref_count[1] = ref_count[1];
  1109. sl->list_count = list_count;
  1110. return 1;
  1111. }
  1112. return 0;
  1113. }
  1114. static const uint8_t start_code[] = { 0x00, 0x00, 0x01 };
  1115. static int get_bit_length(H264Context *h, const uint8_t *buf,
  1116. const uint8_t *ptr, int dst_length,
  1117. int i, int next_avc)
  1118. {
  1119. if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
  1120. buf[i] == 0x00 && buf[i + 1] == 0x00 &&
  1121. buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
  1122. h->workaround_bugs |= FF_BUG_TRUNCATED;
  1123. if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
  1124. while (dst_length > 0 && ptr[dst_length - 1] == 0)
  1125. dst_length--;
  1126. if (!dst_length)
  1127. return 0;
  1128. return 8 * dst_length - decode_rbsp_trailing(h, ptr + dst_length - 1);
  1129. }
  1130. static int get_last_needed_nal(H264Context *h, const uint8_t *buf, int buf_size)
  1131. {
  1132. int next_avc = h->is_avc ? 0 : buf_size;
  1133. int nal_index = 0;
  1134. int buf_index = 0;
  1135. int nals_needed = 0;
  1136. int first_slice = 0;
  1137. while(1) {
  1138. GetBitContext gb;
  1139. int nalsize = 0;
  1140. int dst_length, bit_length, consumed;
  1141. const uint8_t *ptr;
  1142. if (buf_index >= next_avc) {
  1143. nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
  1144. if (nalsize < 0)
  1145. break;
  1146. next_avc = buf_index + nalsize;
  1147. } else {
  1148. buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
  1149. if (buf_index >= buf_size)
  1150. break;
  1151. if (buf_index >= next_avc)
  1152. continue;
  1153. }
  1154. ptr = ff_h264_decode_nal(h, &h->slice_ctx[0], buf + buf_index, &dst_length, &consumed,
  1155. next_avc - buf_index);
  1156. if (!ptr || dst_length < 0)
  1157. return AVERROR_INVALIDDATA;
  1158. buf_index += consumed;
  1159. bit_length = get_bit_length(h, buf, ptr, dst_length,
  1160. buf_index, next_avc);
  1161. nal_index++;
  1162. /* packets can sometimes contain multiple PPS/SPS,
  1163. * e.g. two PAFF field pictures in one packet, or a demuxer
  1164. * which splits NALs strangely if so, when frame threading we
  1165. * can't start the next thread until we've read all of them */
  1166. switch (h->nal_unit_type) {
  1167. case NAL_SPS:
  1168. case NAL_PPS:
  1169. nals_needed = nal_index;
  1170. break;
  1171. case NAL_DPA:
  1172. case NAL_IDR_SLICE:
  1173. case NAL_SLICE:
  1174. init_get_bits(&gb, ptr, bit_length);
  1175. if (!get_ue_golomb_long(&gb) || // first_mb_in_slice
  1176. !first_slice ||
  1177. first_slice != h->nal_unit_type)
  1178. nals_needed = nal_index;
  1179. if (!first_slice)
  1180. first_slice = h->nal_unit_type;
  1181. }
  1182. }
  1183. return nals_needed;
  1184. }
  1185. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
  1186. int parse_extradata)
  1187. {
  1188. AVCodecContext *const avctx = h->avctx;
  1189. H264SliceContext *sl;
  1190. int buf_index;
  1191. unsigned context_count;
  1192. int next_avc;
  1193. int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
  1194. int nal_index;
  1195. int idr_cleared=0;
  1196. int ret = 0;
  1197. h->nal_unit_type= 0;
  1198. if(!h->slice_context_count)
  1199. h->slice_context_count= 1;
  1200. h->max_contexts = h->slice_context_count;
  1201. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)) {
  1202. h->current_slice = 0;
  1203. if (!h->first_field)
  1204. h->cur_pic_ptr = NULL;
  1205. ff_h264_reset_sei(h);
  1206. }
  1207. if (h->nal_length_size == 4) {
  1208. if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
  1209. h->is_avc = 0;
  1210. }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
  1211. h->is_avc = 1;
  1212. }
  1213. if (avctx->active_thread_type & FF_THREAD_FRAME)
  1214. nals_needed = get_last_needed_nal(h, buf, buf_size);
  1215. {
  1216. buf_index = 0;
  1217. context_count = 0;
  1218. next_avc = h->is_avc ? 0 : buf_size;
  1219. nal_index = 0;
  1220. for (;;) {
  1221. int consumed;
  1222. int dst_length;
  1223. int bit_length;
  1224. const uint8_t *ptr;
  1225. int nalsize = 0;
  1226. int err;
  1227. if (buf_index >= next_avc) {
  1228. nalsize = get_avc_nalsize(h, buf, buf_size, &buf_index);
  1229. if (nalsize < 0)
  1230. break;
  1231. next_avc = buf_index + nalsize;
  1232. } else {
  1233. buf_index = find_start_code(buf, buf_size, buf_index, next_avc);
  1234. if (buf_index >= buf_size)
  1235. break;
  1236. if (buf_index >= next_avc)
  1237. continue;
  1238. }
  1239. sl = &h->slice_ctx[context_count];
  1240. ptr = ff_h264_decode_nal(h, sl, buf + buf_index, &dst_length,
  1241. &consumed, next_avc - buf_index);
  1242. if (!ptr || dst_length < 0) {
  1243. ret = -1;
  1244. goto end;
  1245. }
  1246. bit_length = get_bit_length(h, buf, ptr, dst_length,
  1247. buf_index + consumed, next_avc);
  1248. if (h->avctx->debug & FF_DEBUG_STARTCODE)
  1249. av_log(h->avctx, AV_LOG_DEBUG,
  1250. "NAL %d/%d at %d/%d length %d\n",
  1251. h->nal_unit_type, h->nal_ref_idc, buf_index, buf_size, dst_length);
  1252. if (h->is_avc && (nalsize != consumed) && nalsize)
  1253. av_log(h->avctx, AV_LOG_DEBUG,
  1254. "AVC: Consumed only %d bytes instead of %d\n",
  1255. consumed, nalsize);
  1256. buf_index += consumed;
  1257. nal_index++;
  1258. if (avctx->skip_frame >= AVDISCARD_NONREF &&
  1259. h->nal_ref_idc == 0 &&
  1260. h->nal_unit_type != NAL_SEI)
  1261. continue;
  1262. again:
  1263. /* Ignore per frame NAL unit type during extradata
  1264. * parsing. Decoding slices is not possible in codec init
  1265. * with frame-mt */
  1266. if (parse_extradata) {
  1267. switch (h->nal_unit_type) {
  1268. case NAL_IDR_SLICE:
  1269. case NAL_SLICE:
  1270. case NAL_DPA:
  1271. case NAL_DPB:
  1272. case NAL_DPC:
  1273. av_log(h->avctx, AV_LOG_WARNING,
  1274. "Ignoring NAL %d in global header/extradata\n",
  1275. h->nal_unit_type);
  1276. // fall through to next case
  1277. case NAL_AUXILIARY_SLICE:
  1278. h->nal_unit_type = NAL_FF_IGNORE;
  1279. }
  1280. }
  1281. err = 0;
  1282. switch (h->nal_unit_type) {
  1283. case NAL_IDR_SLICE:
  1284. if ((ptr[0] & 0xFC) == 0x98) {
  1285. av_log(h->avctx, AV_LOG_ERROR, "Invalid inter IDR frame\n");
  1286. h->next_outputed_poc = INT_MIN;
  1287. ret = -1;
  1288. goto end;
  1289. }
  1290. if (h->nal_unit_type != NAL_IDR_SLICE) {
  1291. av_log(h->avctx, AV_LOG_ERROR,
  1292. "Invalid mix of idr and non-idr slices\n");
  1293. ret = -1;
  1294. goto end;
  1295. }
  1296. if(!idr_cleared) {
  1297. if (h->current_slice && (avctx->active_thread_type & FF_THREAD_SLICE)) {
  1298. av_log(h, AV_LOG_ERROR, "invalid mixed IDR / non IDR frames cannot be decoded in slice multithreading mode\n");
  1299. ret = AVERROR_INVALIDDATA;
  1300. goto end;
  1301. }
  1302. idr(h); // FIXME ensure we don't lose some frames if there is reordering
  1303. }
  1304. idr_cleared = 1;
  1305. h->has_recovery_point = 1;
  1306. case NAL_SLICE:
  1307. init_get_bits(&sl->gb, ptr, bit_length);
  1308. if ( nals_needed >= nal_index
  1309. || (!(avctx->active_thread_type & FF_THREAD_FRAME) && !context_count))
  1310. h->au_pps_id = -1;
  1311. if ((err = ff_h264_decode_slice_header(h, sl)))
  1312. break;
  1313. if (h->sei_recovery_frame_cnt >= 0) {
  1314. if (h->frame_num != h->sei_recovery_frame_cnt || sl->slice_type_nos != AV_PICTURE_TYPE_I)
  1315. h->valid_recovery_point = 1;
  1316. if ( h->recovery_frame < 0
  1317. || av_mod_uintp2(h->recovery_frame - h->frame_num, h->sps.log2_max_frame_num) > h->sei_recovery_frame_cnt) {
  1318. h->recovery_frame = av_mod_uintp2(h->frame_num + h->sei_recovery_frame_cnt, h->sps.log2_max_frame_num);
  1319. if (!h->valid_recovery_point)
  1320. h->recovery_frame = h->frame_num;
  1321. }
  1322. }
  1323. h->cur_pic_ptr->f->key_frame |=
  1324. (h->nal_unit_type == NAL_IDR_SLICE);
  1325. if (h->nal_unit_type == NAL_IDR_SLICE ||
  1326. h->recovery_frame == h->frame_num) {
  1327. h->recovery_frame = -1;
  1328. h->cur_pic_ptr->recovered = 1;
  1329. }
  1330. // If we have an IDR, all frames after it in decoded order are
  1331. // "recovered".
  1332. if (h->nal_unit_type == NAL_IDR_SLICE)
  1333. h->frame_recovered |= FRAME_RECOVERED_IDR;
  1334. #if 1
  1335. h->cur_pic_ptr->recovered |= h->frame_recovered;
  1336. #else
  1337. h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
  1338. #endif
  1339. if (h->current_slice == 1) {
  1340. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS))
  1341. decode_postinit(h, nal_index >= nals_needed);
  1342. if (h->avctx->hwaccel &&
  1343. (ret = h->avctx->hwaccel->start_frame(h->avctx, buf, buf_size)) < 0)
  1344. goto end;
  1345. #if FF_API_CAP_VDPAU
  1346. if (CONFIG_H264_VDPAU_DECODER &&
  1347. h->avctx->codec->capabilities & AV_CODEC_CAP_HWACCEL_VDPAU)
  1348. ff_vdpau_h264_picture_start(h);
  1349. #endif
  1350. }
  1351. if (sl->redundant_pic_count == 0) {
  1352. if (avctx->hwaccel) {
  1353. ret = avctx->hwaccel->decode_slice(avctx,
  1354. &buf[buf_index - consumed],
  1355. consumed);
  1356. if (ret < 0)
  1357. goto end;
  1358. #if FF_API_CAP_VDPAU
  1359. } else if (CONFIG_H264_VDPAU_DECODER &&
  1360. h->avctx->codec->capabilities & AV_CODEC_CAP_HWACCEL_VDPAU) {
  1361. ff_vdpau_add_data_chunk(h->cur_pic_ptr->f->data[0],
  1362. start_code,
  1363. sizeof(start_code));
  1364. ff_vdpau_add_data_chunk(h->cur_pic_ptr->f->data[0],
  1365. &buf[buf_index - consumed],
  1366. consumed);
  1367. #endif
  1368. } else
  1369. context_count++;
  1370. }
  1371. break;
  1372. case NAL_DPA:
  1373. case NAL_DPB:
  1374. case NAL_DPC:
  1375. avpriv_request_sample(avctx, "data partitioning");
  1376. break;
  1377. case NAL_SEI:
  1378. init_get_bits(&h->gb, ptr, bit_length);
  1379. ret = ff_h264_decode_sei(h);
  1380. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1381. goto end;
  1382. break;
  1383. case NAL_SPS:
  1384. init_get_bits(&h->gb, ptr, bit_length);
  1385. if (ff_h264_decode_seq_parameter_set(h, 0) >= 0)
  1386. break;
  1387. if (h->is_avc ? nalsize : 1) {
  1388. av_log(h->avctx, AV_LOG_DEBUG,
  1389. "SPS decoding failure, trying again with the complete NAL\n");
  1390. if (h->is_avc)
  1391. av_assert0(next_avc - buf_index + consumed == nalsize);
  1392. if ((next_avc - buf_index + consumed - 1) >= INT_MAX/8)
  1393. break;
  1394. init_get_bits(&h->gb, &buf[buf_index + 1 - consumed],
  1395. 8*(next_avc - buf_index + consumed - 1));
  1396. if (ff_h264_decode_seq_parameter_set(h, 0) >= 0)
  1397. break;
  1398. }
  1399. init_get_bits(&h->gb, ptr, bit_length);
  1400. ff_h264_decode_seq_parameter_set(h, 1);
  1401. break;
  1402. case NAL_PPS:
  1403. init_get_bits(&h->gb, ptr, bit_length);
  1404. ret = ff_h264_decode_picture_parameter_set(h, bit_length);
  1405. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1406. goto end;
  1407. break;
  1408. case NAL_AUD:
  1409. case NAL_END_SEQUENCE:
  1410. case NAL_END_STREAM:
  1411. case NAL_FILLER_DATA:
  1412. case NAL_SPS_EXT:
  1413. case NAL_AUXILIARY_SLICE:
  1414. break;
  1415. case NAL_FF_IGNORE:
  1416. break;
  1417. default:
  1418. av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
  1419. h->nal_unit_type, bit_length);
  1420. }
  1421. if (context_count == h->max_contexts) {
  1422. ret = ff_h264_execute_decode_slices(h, context_count);
  1423. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1424. goto end;
  1425. context_count = 0;
  1426. }
  1427. if (err < 0 || err == SLICE_SKIPED) {
  1428. if (err < 0)
  1429. av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
  1430. sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
  1431. } else if (err == SLICE_SINGLETHREAD) {
  1432. if (context_count > 1) {
  1433. ret = ff_h264_execute_decode_slices(h, context_count - 1);
  1434. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1435. goto end;
  1436. context_count = 0;
  1437. }
  1438. /* Slice could not be decoded in parallel mode, restart. Note
  1439. * that rbsp_buffer is not transferred, but since we no longer
  1440. * run in parallel mode this should not be an issue. */
  1441. sl = &h->slice_ctx[0];
  1442. goto again;
  1443. }
  1444. }
  1445. }
  1446. if (context_count) {
  1447. ret = ff_h264_execute_decode_slices(h, context_count);
  1448. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1449. goto end;
  1450. }
  1451. ret = 0;
  1452. end:
  1453. /* clean up */
  1454. if (h->cur_pic_ptr && !h->droppable) {
  1455. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
  1456. h->picture_structure == PICT_BOTTOM_FIELD);
  1457. }
  1458. return (ret < 0) ? ret : buf_index;
  1459. }
  1460. /**
  1461. * Return the number of bytes consumed for building the current frame.
  1462. */
  1463. static int get_consumed_bytes(int pos, int buf_size)
  1464. {
  1465. if (pos == 0)
  1466. pos = 1; // avoid infinite loops (I doubt that is needed but...)
  1467. if (pos + 10 > buf_size)
  1468. pos = buf_size; // oops ;)
  1469. return pos;
  1470. }
  1471. static int output_frame(H264Context *h, AVFrame *dst, H264Picture *srcp)
  1472. {
  1473. AVFrame *src = srcp->f;
  1474. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(src->format);
  1475. int i;
  1476. int ret = av_frame_ref(dst, src);
  1477. if (ret < 0)
  1478. return ret;
  1479. av_dict_set(&dst->metadata, "stereo_mode", ff_h264_sei_stereo_mode(h), 0);
  1480. h->backup_width = h->avctx->width;
  1481. h->backup_height = h->avctx->height;
  1482. h->backup_pix_fmt = h->avctx->pix_fmt;
  1483. h->avctx->width = dst->width;
  1484. h->avctx->height = dst->height;
  1485. h->avctx->pix_fmt = dst->format;
  1486. if (srcp->sei_recovery_frame_cnt == 0)
  1487. dst->key_frame = 1;
  1488. if (!srcp->crop)
  1489. return 0;
  1490. for (i = 0; i < desc->nb_components; i++) {
  1491. int hshift = (i > 0) ? desc->log2_chroma_w : 0;
  1492. int vshift = (i > 0) ? desc->log2_chroma_h : 0;
  1493. int off = ((srcp->crop_left >> hshift) << h->pixel_shift) +
  1494. (srcp->crop_top >> vshift) * dst->linesize[i];
  1495. dst->data[i] += off;
  1496. }
  1497. return 0;
  1498. }
  1499. static int is_extra(const uint8_t *buf, int buf_size)
  1500. {
  1501. int cnt= buf[5]&0x1f;
  1502. const uint8_t *p= buf+6;
  1503. while(cnt--){
  1504. int nalsize= AV_RB16(p) + 2;
  1505. if(nalsize > buf_size - (p-buf) || p[2]!=0x67)
  1506. return 0;
  1507. p += nalsize;
  1508. }
  1509. cnt = *(p++);
  1510. if(!cnt)
  1511. return 0;
  1512. while(cnt--){
  1513. int nalsize= AV_RB16(p) + 2;
  1514. if(nalsize > buf_size - (p-buf) || p[2]!=0x68)
  1515. return 0;
  1516. p += nalsize;
  1517. }
  1518. return 1;
  1519. }
  1520. static int h264_decode_frame(AVCodecContext *avctx, void *data,
  1521. int *got_frame, AVPacket *avpkt)
  1522. {
  1523. const uint8_t *buf = avpkt->data;
  1524. int buf_size = avpkt->size;
  1525. H264Context *h = avctx->priv_data;
  1526. AVFrame *pict = data;
  1527. int buf_index = 0;
  1528. H264Picture *out;
  1529. int i, out_idx;
  1530. int ret;
  1531. h->flags = avctx->flags;
  1532. h->setup_finished = 0;
  1533. if (h->backup_width != -1) {
  1534. avctx->width = h->backup_width;
  1535. h->backup_width = -1;
  1536. }
  1537. if (h->backup_height != -1) {
  1538. avctx->height = h->backup_height;
  1539. h->backup_height = -1;
  1540. }
  1541. if (h->backup_pix_fmt != AV_PIX_FMT_NONE) {
  1542. avctx->pix_fmt = h->backup_pix_fmt;
  1543. h->backup_pix_fmt = AV_PIX_FMT_NONE;
  1544. }
  1545. ff_h264_unref_picture(h, &h->last_pic_for_ec);
  1546. /* end of stream, output what is still in the buffers */
  1547. if (buf_size == 0) {
  1548. out:
  1549. h->cur_pic_ptr = NULL;
  1550. h->first_field = 0;
  1551. // FIXME factorize this with the output code below
  1552. out = h->delayed_pic[0];
  1553. out_idx = 0;
  1554. for (i = 1;
  1555. h->delayed_pic[i] &&
  1556. !h->delayed_pic[i]->f->key_frame &&
  1557. !h->delayed_pic[i]->mmco_reset;
  1558. i++)
  1559. if (h->delayed_pic[i]->poc < out->poc) {
  1560. out = h->delayed_pic[i];
  1561. out_idx = i;
  1562. }
  1563. for (i = out_idx; h->delayed_pic[i]; i++)
  1564. h->delayed_pic[i] = h->delayed_pic[i + 1];
  1565. if (out) {
  1566. out->reference &= ~DELAYED_PIC_REF;
  1567. ret = output_frame(h, pict, out);
  1568. if (ret < 0)
  1569. return ret;
  1570. *got_frame = 1;
  1571. }
  1572. return buf_index;
  1573. }
  1574. if (h->is_avc && av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, NULL)) {
  1575. int side_size;
  1576. uint8_t *side = av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
  1577. if (is_extra(side, side_size))
  1578. ff_h264_decode_extradata(h, side, side_size);
  1579. }
  1580. if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
  1581. if (is_extra(buf, buf_size))
  1582. return ff_h264_decode_extradata(h, buf, buf_size);
  1583. }
  1584. buf_index = decode_nal_units(h, buf, buf_size, 0);
  1585. if (buf_index < 0)
  1586. return AVERROR_INVALIDDATA;
  1587. if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
  1588. av_assert0(buf_index <= buf_size);
  1589. goto out;
  1590. }
  1591. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
  1592. if (avctx->skip_frame >= AVDISCARD_NONREF ||
  1593. buf_size >= 4 && !memcmp("Q264", buf, 4))
  1594. return buf_size;
  1595. av_log(avctx, AV_LOG_ERROR, "no frame!\n");
  1596. return AVERROR_INVALIDDATA;
  1597. }
  1598. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) ||
  1599. (h->mb_y >= h->mb_height && h->mb_height)) {
  1600. if (avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)
  1601. decode_postinit(h, 1);
  1602. if ((ret = ff_h264_field_end(h, &h->slice_ctx[0], 0)) < 0)
  1603. return ret;
  1604. /* Wait for second field. */
  1605. *got_frame = 0;
  1606. if (h->next_output_pic && ((avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT) ||
  1607. (avctx->flags2 & AV_CODEC_FLAG2_SHOW_ALL) ||
  1608. h->next_output_pic->recovered)) {
  1609. if (!h->next_output_pic->recovered)
  1610. h->next_output_pic->f->flags |= AV_FRAME_FLAG_CORRUPT;
  1611. if (!h->avctx->hwaccel &&
  1612. (h->next_output_pic->field_poc[0] == INT_MAX ||
  1613. h->next_output_pic->field_poc[1] == INT_MAX)
  1614. ) {
  1615. int p;
  1616. AVFrame *f = h->next_output_pic->f;
  1617. int field = h->next_output_pic->field_poc[0] == INT_MAX;
  1618. uint8_t *dst_data[4];
  1619. int linesizes[4];
  1620. const uint8_t *src_data[4];
  1621. av_log(h->avctx, AV_LOG_DEBUG, "Duplicating field %d to fill missing\n", field);
  1622. for (p = 0; p<4; p++) {
  1623. dst_data[p] = f->data[p] + (field^1)*f->linesize[p];
  1624. src_data[p] = f->data[p] + field *f->linesize[p];
  1625. linesizes[p] = 2*f->linesize[p];
  1626. }
  1627. av_image_copy(dst_data, linesizes, src_data, linesizes,
  1628. f->format, f->width, f->height>>1);
  1629. }
  1630. ret = output_frame(h, pict, h->next_output_pic);
  1631. if (ret < 0)
  1632. return ret;
  1633. *got_frame = 1;
  1634. if (CONFIG_MPEGVIDEO) {
  1635. ff_print_debug_info2(h->avctx, pict, NULL,
  1636. h->next_output_pic->mb_type,
  1637. h->next_output_pic->qscale_table,
  1638. h->next_output_pic->motion_val,
  1639. &h->low_delay,
  1640. h->mb_width, h->mb_height, h->mb_stride, 1);
  1641. }
  1642. }
  1643. }
  1644. av_assert0(pict->buf[0] || !*got_frame);
  1645. ff_h264_unref_picture(h, &h->last_pic_for_ec);
  1646. return get_consumed_bytes(buf_index, buf_size);
  1647. }
  1648. av_cold void ff_h264_free_context(H264Context *h)
  1649. {
  1650. int i;
  1651. ff_h264_free_tables(h);
  1652. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
  1653. ff_h264_unref_picture(h, &h->DPB[i]);
  1654. av_frame_free(&h->DPB[i].f);
  1655. }
  1656. memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
  1657. h->cur_pic_ptr = NULL;
  1658. for (i = 0; i < h->nb_slice_ctx; i++)
  1659. av_freep(&h->slice_ctx[i].rbsp_buffer);
  1660. av_freep(&h->slice_ctx);
  1661. h->nb_slice_ctx = 0;
  1662. for (i = 0; i < MAX_SPS_COUNT; i++)
  1663. av_freep(h->sps_buffers + i);
  1664. for (i = 0; i < MAX_PPS_COUNT; i++)
  1665. av_freep(h->pps_buffers + i);
  1666. }
  1667. static av_cold int h264_decode_end(AVCodecContext *avctx)
  1668. {
  1669. H264Context *h = avctx->priv_data;
  1670. ff_h264_remove_all_refs(h);
  1671. ff_h264_free_context(h);
  1672. ff_h264_unref_picture(h, &h->cur_pic);
  1673. av_frame_free(&h->cur_pic.f);
  1674. ff_h264_unref_picture(h, &h->last_pic_for_ec);
  1675. av_frame_free(&h->last_pic_for_ec.f);
  1676. return 0;
  1677. }
  1678. #define OFFSET(x) offsetof(H264Context, x)
  1679. #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  1680. static const AVOption h264_options[] = {
  1681. {"is_avc", "is avc", offsetof(H264Context, is_avc), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, 0},
  1682. {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
  1683. { "enable_er", "Enable error resilience on damaged frames (unsafe)", OFFSET(enable_er), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, VD },
  1684. { NULL },
  1685. };
  1686. static const AVClass h264_class = {
  1687. .class_name = "H264 Decoder",
  1688. .item_name = av_default_item_name,
  1689. .option = h264_options,
  1690. .version = LIBAVUTIL_VERSION_INT,
  1691. };
  1692. static const AVProfile profiles[] = {
  1693. { FF_PROFILE_H264_BASELINE, "Baseline" },
  1694. { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
  1695. { FF_PROFILE_H264_MAIN, "Main" },
  1696. { FF_PROFILE_H264_EXTENDED, "Extended" },
  1697. { FF_PROFILE_H264_HIGH, "High" },
  1698. { FF_PROFILE_H264_HIGH_10, "High 10" },
  1699. { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
  1700. { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
  1701. { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
  1702. { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
  1703. { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
  1704. { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
  1705. { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
  1706. { FF_PROFILE_UNKNOWN },
  1707. };
  1708. AVCodec ff_h264_decoder = {
  1709. .name = "h264",
  1710. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
  1711. .type = AVMEDIA_TYPE_VIDEO,
  1712. .id = AV_CODEC_ID_H264,
  1713. .priv_data_size = sizeof(H264Context),
  1714. .init = ff_h264_decode_init,
  1715. .close = h264_decode_end,
  1716. .decode = h264_decode_frame,
  1717. .capabilities = /*AV_CODEC_CAP_DRAW_HORIZ_BAND |*/ AV_CODEC_CAP_DR1 |
  1718. AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS |
  1719. AV_CODEC_CAP_FRAME_THREADS,
  1720. .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
  1721. .flush = flush_dpb,
  1722. .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
  1723. .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
  1724. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  1725. .priv_class = &h264_class,
  1726. };
  1727. #if CONFIG_H264_VDPAU_DECODER && FF_API_VDPAU
  1728. static const AVClass h264_vdpau_class = {
  1729. .class_name = "H264 VDPAU Decoder",
  1730. .item_name = av_default_item_name,
  1731. .option = h264_options,
  1732. .version = LIBAVUTIL_VERSION_INT,
  1733. };
  1734. AVCodec ff_h264_vdpau_decoder = {
  1735. .name = "h264_vdpau",
  1736. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
  1737. .type = AVMEDIA_TYPE_VIDEO,
  1738. .id = AV_CODEC_ID_H264,
  1739. .priv_data_size = sizeof(H264Context),
  1740. .init = ff_h264_decode_init,
  1741. .close = h264_decode_end,
  1742. .decode = h264_decode_frame,
  1743. .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY | AV_CODEC_CAP_HWACCEL_VDPAU,
  1744. .flush = flush_dpb,
  1745. .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
  1746. AV_PIX_FMT_NONE},
  1747. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  1748. .priv_class = &h264_vdpau_class,
  1749. };
  1750. #endif