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.

2042 lines
69KB

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