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
68KB

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