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.

1985 lines
66KB

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