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.

2011 lines
67KB

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