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.

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