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.

1442 lines
49KB

  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 / MPEG-4 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 "bytestream.h"
  35. #include "cabac.h"
  36. #include "cabac_functions.h"
  37. #include "error_resilience.h"
  38. #include "avcodec.h"
  39. #include "h264.h"
  40. #include "h2645_parse.h"
  41. #include "h264data.h"
  42. #include "h264chroma.h"
  43. #include "h264_mvpred.h"
  44. #include "golomb.h"
  45. #include "mathops.h"
  46. #include "me_cmp.h"
  47. #include "mpegutils.h"
  48. #include "profiles.h"
  49. #include "rectangle.h"
  50. #include "thread.h"
  51. #include "vdpau_compat.h"
  52. static int h264_decode_end(AVCodecContext *avctx);
  53. const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
  54. int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx)
  55. {
  56. H264Context *h = avctx->priv_data;
  57. return h && h->ps.sps ? h->ps.sps->num_reorder_frames : 0;
  58. }
  59. static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
  60. int (*mv)[2][4][2],
  61. int mb_x, int mb_y, int mb_intra, int mb_skipped)
  62. {
  63. H264Context *h = opaque;
  64. H264SliceContext *sl = &h->slice_ctx[0];
  65. sl->mb_x = mb_x;
  66. sl->mb_y = mb_y;
  67. sl->mb_xy = mb_x + mb_y * h->mb_stride;
  68. memset(sl->non_zero_count_cache, 0, sizeof(sl->non_zero_count_cache));
  69. av_assert1(ref >= 0);
  70. /* FIXME: It is possible albeit uncommon that slice references
  71. * differ between slices. We take the easy approach and ignore
  72. * it for now. If this turns out to have any relevance in
  73. * practice then correct remapping should be added. */
  74. if (ref >= sl->ref_count[0])
  75. ref = 0;
  76. if (!sl->ref_list[0][ref].data[0]) {
  77. av_log(h->avctx, AV_LOG_DEBUG, "Reference not available for error concealing\n");
  78. ref = 0;
  79. }
  80. if ((sl->ref_list[0][ref].reference&3) != 3) {
  81. av_log(h->avctx, AV_LOG_DEBUG, "Reference invalid\n");
  82. return;
  83. }
  84. fill_rectangle(&h->cur_pic.ref_index[0][4 * sl->mb_xy],
  85. 2, 2, 2, ref, 1);
  86. fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
  87. fill_rectangle(sl->mv_cache[0][scan8[0]], 4, 4, 8,
  88. pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
  89. sl->mb_mbaff =
  90. sl->mb_field_decoding_flag = 0;
  91. ff_h264_hl_decode_mb(h, &h->slice_ctx[0]);
  92. }
  93. void ff_h264_draw_horiz_band(const H264Context *h, H264SliceContext *sl,
  94. int y, int height)
  95. {
  96. AVCodecContext *avctx = h->avctx;
  97. const AVFrame *src = h->cur_pic.f;
  98. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
  99. int vshift = desc->log2_chroma_h;
  100. const int field_pic = h->picture_structure != PICT_FRAME;
  101. if (field_pic) {
  102. height <<= 1;
  103. y <<= 1;
  104. }
  105. height = FFMIN(height, avctx->height - y);
  106. if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
  107. return;
  108. if (avctx->draw_horiz_band) {
  109. int offset[AV_NUM_DATA_POINTERS];
  110. int i;
  111. offset[0] = y * src->linesize[0];
  112. offset[1] =
  113. offset[2] = (y >> vshift) * src->linesize[1];
  114. for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
  115. offset[i] = 0;
  116. emms_c();
  117. avctx->draw_horiz_band(avctx, src, offset,
  118. y, h->picture_structure, height);
  119. }
  120. }
  121. void ff_h264_free_tables(H264Context *h)
  122. {
  123. int i;
  124. av_freep(&h->intra4x4_pred_mode);
  125. av_freep(&h->chroma_pred_mode_table);
  126. av_freep(&h->cbp_table);
  127. av_freep(&h->mvd_table[0]);
  128. av_freep(&h->mvd_table[1]);
  129. av_freep(&h->direct_table);
  130. av_freep(&h->non_zero_count);
  131. av_freep(&h->slice_table_base);
  132. h->slice_table = NULL;
  133. av_freep(&h->list_counts);
  134. av_freep(&h->mb2b_xy);
  135. av_freep(&h->mb2br_xy);
  136. av_buffer_pool_uninit(&h->qscale_table_pool);
  137. av_buffer_pool_uninit(&h->mb_type_pool);
  138. av_buffer_pool_uninit(&h->motion_val_pool);
  139. av_buffer_pool_uninit(&h->ref_index_pool);
  140. for (i = 0; i < h->nb_slice_ctx; i++) {
  141. H264SliceContext *sl = &h->slice_ctx[i];
  142. av_freep(&sl->dc_val_base);
  143. av_freep(&sl->er.mb_index2xy);
  144. av_freep(&sl->er.error_status_table);
  145. av_freep(&sl->er.er_temp_buffer);
  146. av_freep(&sl->bipred_scratchpad);
  147. av_freep(&sl->edge_emu_buffer);
  148. av_freep(&sl->top_borders[0]);
  149. av_freep(&sl->top_borders[1]);
  150. sl->bipred_scratchpad_allocated = 0;
  151. sl->edge_emu_buffer_allocated = 0;
  152. sl->top_borders_allocated[0] = 0;
  153. sl->top_borders_allocated[1] = 0;
  154. }
  155. }
  156. int ff_h264_alloc_tables(H264Context *h)
  157. {
  158. const int big_mb_num = h->mb_stride * (h->mb_height + 1);
  159. const int row_mb_num = 2*h->mb_stride*FFMAX(h->nb_slice_ctx, 1);
  160. int x, y;
  161. FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
  162. row_mb_num, 8 * sizeof(uint8_t), fail)
  163. h->slice_ctx[0].intra4x4_pred_mode = h->intra4x4_pred_mode;
  164. FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
  165. big_mb_num * 48 * sizeof(uint8_t), fail)
  166. FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
  167. (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
  168. FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
  169. big_mb_num * sizeof(uint16_t), fail)
  170. FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
  171. big_mb_num * sizeof(uint8_t), fail)
  172. FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->mvd_table[0],
  173. row_mb_num, 16 * sizeof(uint8_t), fail);
  174. FF_ALLOCZ_ARRAY_OR_GOTO(h->avctx, h->mvd_table[1],
  175. row_mb_num, 16 * sizeof(uint8_t), fail);
  176. h->slice_ctx[0].mvd_table[0] = h->mvd_table[0];
  177. h->slice_ctx[0].mvd_table[1] = h->mvd_table[1];
  178. FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
  179. 4 * big_mb_num * sizeof(uint8_t), fail);
  180. FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
  181. big_mb_num * sizeof(uint8_t), fail)
  182. memset(h->slice_table_base, -1,
  183. (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
  184. h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
  185. FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
  186. big_mb_num * sizeof(uint32_t), fail);
  187. FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
  188. big_mb_num * sizeof(uint32_t), fail);
  189. for (y = 0; y < h->mb_height; y++)
  190. for (x = 0; x < h->mb_width; x++) {
  191. const int mb_xy = x + y * h->mb_stride;
  192. const int b_xy = 4 * x + 4 * y * h->b_stride;
  193. h->mb2b_xy[mb_xy] = b_xy;
  194. h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
  195. }
  196. return 0;
  197. fail:
  198. ff_h264_free_tables(h);
  199. return AVERROR(ENOMEM);
  200. }
  201. /**
  202. * Init context
  203. * Allocate buffers which are not shared amongst multiple threads.
  204. */
  205. int ff_h264_slice_context_init(H264Context *h, H264SliceContext *sl)
  206. {
  207. ERContext *er = &sl->er;
  208. int mb_array_size = h->mb_height * h->mb_stride;
  209. int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
  210. int c_size = h->mb_stride * (h->mb_height + 1);
  211. int yc_size = y_size + 2 * c_size;
  212. int x, y, i;
  213. sl->ref_cache[0][scan8[5] + 1] =
  214. sl->ref_cache[0][scan8[7] + 1] =
  215. sl->ref_cache[0][scan8[13] + 1] =
  216. sl->ref_cache[1][scan8[5] + 1] =
  217. sl->ref_cache[1][scan8[7] + 1] =
  218. sl->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
  219. if (sl != h->slice_ctx) {
  220. memset(er, 0, sizeof(*er));
  221. } else
  222. if (CONFIG_ERROR_RESILIENCE) {
  223. /* init ER */
  224. er->avctx = h->avctx;
  225. er->decode_mb = h264_er_decode_mb;
  226. er->opaque = h;
  227. er->quarter_sample = 1;
  228. er->mb_num = h->mb_num;
  229. er->mb_width = h->mb_width;
  230. er->mb_height = h->mb_height;
  231. er->mb_stride = h->mb_stride;
  232. er->b8_stride = h->mb_width * 2 + 1;
  233. // error resilience code looks cleaner with this
  234. FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
  235. (h->mb_num + 1) * sizeof(int), fail);
  236. for (y = 0; y < h->mb_height; y++)
  237. for (x = 0; x < h->mb_width; x++)
  238. er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
  239. er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
  240. h->mb_stride + h->mb_width;
  241. FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
  242. mb_array_size * sizeof(uint8_t), fail);
  243. FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
  244. h->mb_height * h->mb_stride, fail);
  245. FF_ALLOCZ_OR_GOTO(h->avctx, sl->dc_val_base,
  246. yc_size * sizeof(int16_t), fail);
  247. er->dc_val[0] = sl->dc_val_base + h->mb_width * 2 + 2;
  248. er->dc_val[1] = sl->dc_val_base + y_size + h->mb_stride + 1;
  249. er->dc_val[2] = er->dc_val[1] + c_size;
  250. for (i = 0; i < yc_size; i++)
  251. sl->dc_val_base[i] = 1024;
  252. }
  253. return 0;
  254. fail:
  255. return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
  256. }
  257. static int h264_init_context(AVCodecContext *avctx, H264Context *h)
  258. {
  259. int i;
  260. h->avctx = avctx;
  261. h->backup_width = -1;
  262. h->backup_height = -1;
  263. h->backup_pix_fmt = AV_PIX_FMT_NONE;
  264. h->cur_chroma_format_idc = -1;
  265. h->picture_structure = PICT_FRAME;
  266. h->workaround_bugs = avctx->workaround_bugs;
  267. h->flags = avctx->flags;
  268. h->poc.prev_poc_msb = 1 << 16;
  269. h->recovery_frame = -1;
  270. h->frame_recovered = 0;
  271. h->poc.prev_frame_num = -1;
  272. h->sei.frame_packing.frame_packing_arrangement_cancel_flag = -1;
  273. h->sei.unregistered.x264_build = -1;
  274. h->next_outputed_poc = INT_MIN;
  275. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  276. h->last_pocs[i] = INT_MIN;
  277. ff_h264_sei_uninit(&h->sei);
  278. avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
  279. h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? avctx->thread_count : 1;
  280. h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
  281. if (!h->slice_ctx) {
  282. h->nb_slice_ctx = 0;
  283. return AVERROR(ENOMEM);
  284. }
  285. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
  286. h->DPB[i].f = av_frame_alloc();
  287. if (!h->DPB[i].f)
  288. return AVERROR(ENOMEM);
  289. }
  290. h->cur_pic.f = av_frame_alloc();
  291. if (!h->cur_pic.f)
  292. return AVERROR(ENOMEM);
  293. h->last_pic_for_ec.f = av_frame_alloc();
  294. if (!h->last_pic_for_ec.f)
  295. return AVERROR(ENOMEM);
  296. for (i = 0; i < h->nb_slice_ctx; i++)
  297. h->slice_ctx[i].h264 = h;
  298. return 0;
  299. }
  300. static av_cold int h264_decode_end(AVCodecContext *avctx)
  301. {
  302. H264Context *h = avctx->priv_data;
  303. int i;
  304. ff_h264_remove_all_refs(h);
  305. ff_h264_free_tables(h);
  306. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
  307. ff_h264_unref_picture(h, &h->DPB[i]);
  308. av_frame_free(&h->DPB[i].f);
  309. }
  310. memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
  311. h->cur_pic_ptr = NULL;
  312. av_freep(&h->slice_ctx);
  313. h->nb_slice_ctx = 0;
  314. ff_h264_sei_uninit(&h->sei);
  315. ff_h264_ps_uninit(&h->ps);
  316. ff_h2645_packet_uninit(&h->pkt);
  317. ff_h264_unref_picture(h, &h->cur_pic);
  318. av_frame_free(&h->cur_pic.f);
  319. ff_h264_unref_picture(h, &h->last_pic_for_ec);
  320. av_frame_free(&h->last_pic_for_ec.f);
  321. return 0;
  322. }
  323. static AVOnce h264_vlc_init = AV_ONCE_INIT;
  324. av_cold int ff_h264_decode_init(AVCodecContext *avctx)
  325. {
  326. H264Context *h = avctx->priv_data;
  327. int ret;
  328. ret = h264_init_context(avctx, h);
  329. if (ret < 0)
  330. return ret;
  331. ret = ff_thread_once(&h264_vlc_init, ff_h264_decode_init_vlc);
  332. if (ret != 0) {
  333. av_log(avctx, AV_LOG_ERROR, "pthread_once has failed.");
  334. return AVERROR_UNKNOWN;
  335. }
  336. if (avctx->codec_id == AV_CODEC_ID_H264) {
  337. if (avctx->ticks_per_frame == 1) {
  338. if(h->avctx->time_base.den < INT_MAX/2) {
  339. h->avctx->time_base.den *= 2;
  340. } else
  341. h->avctx->time_base.num /= 2;
  342. }
  343. avctx->ticks_per_frame = 2;
  344. }
  345. if (avctx->extradata_size > 0 && avctx->extradata) {
  346. ret = ff_h264_decode_extradata(avctx->extradata, avctx->extradata_size,
  347. &h->ps, &h->is_avc, &h->nal_length_size,
  348. avctx->err_recognition, avctx);
  349. if (ret < 0) {
  350. h264_decode_end(avctx);
  351. return ret;
  352. }
  353. }
  354. if (h->ps.sps && h->ps.sps->bitstream_restriction_flag &&
  355. h->avctx->has_b_frames < h->ps.sps->num_reorder_frames) {
  356. h->avctx->has_b_frames = h->ps.sps->num_reorder_frames;
  357. }
  358. avctx->internal->allocate_progress = 1;
  359. ff_h264_flush_change(h);
  360. if (h->enable_er < 0 && (avctx->active_thread_type & FF_THREAD_SLICE))
  361. h->enable_er = 0;
  362. if (h->enable_er && (avctx->active_thread_type & FF_THREAD_SLICE)) {
  363. av_log(avctx, AV_LOG_WARNING,
  364. "Error resilience with slice threads is enabled. It is unsafe and unsupported and may crash. "
  365. "Use it at your own risk\n");
  366. }
  367. return 0;
  368. }
  369. #if HAVE_THREADS
  370. static int decode_init_thread_copy(AVCodecContext *avctx)
  371. {
  372. H264Context *h = avctx->priv_data;
  373. int ret;
  374. if (!avctx->internal->is_copy)
  375. return 0;
  376. memset(h, 0, sizeof(*h));
  377. ret = h264_init_context(avctx, h);
  378. if (ret < 0)
  379. return ret;
  380. h->context_initialized = 0;
  381. return 0;
  382. }
  383. #endif
  384. /**
  385. * Run setup operations that must be run after slice header decoding.
  386. * This includes finding the next displayed frame.
  387. *
  388. * @param h h264 master context
  389. * @param setup_finished enough NALs have been read that we can call
  390. * ff_thread_finish_setup()
  391. */
  392. static void decode_postinit(H264Context *h, int setup_finished)
  393. {
  394. const SPS *sps = h->ps.sps;
  395. H264Picture *out = h->cur_pic_ptr;
  396. H264Picture *cur = h->cur_pic_ptr;
  397. int i, pics, out_of_order, out_idx;
  398. if (h->next_output_pic)
  399. return;
  400. if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
  401. /* FIXME: if we have two PAFF fields in one packet, we can't start
  402. * the next thread here. If we have one field per packet, we can.
  403. * The check in decode_nal_units() is not good enough to find this
  404. * yet, so we assume the worst for now. */
  405. // if (setup_finished)
  406. // ff_thread_finish_setup(h->avctx);
  407. if (cur->field_poc[0] == INT_MAX && cur->field_poc[1] == INT_MAX)
  408. return;
  409. if (h->avctx->hwaccel || h->missing_fields <=1)
  410. return;
  411. }
  412. cur->f->interlaced_frame = 0;
  413. cur->f->repeat_pict = 0;
  414. /* Signal interlacing information externally. */
  415. /* Prioritize picture timing SEI information over used
  416. * decoding process if it exists. */
  417. if (sps->pic_struct_present_flag) {
  418. H264SEIPictureTiming *pt = &h->sei.picture_timing;
  419. switch (pt->pic_struct) {
  420. case SEI_PIC_STRUCT_FRAME:
  421. break;
  422. case SEI_PIC_STRUCT_TOP_FIELD:
  423. case SEI_PIC_STRUCT_BOTTOM_FIELD:
  424. cur->f->interlaced_frame = 1;
  425. break;
  426. case SEI_PIC_STRUCT_TOP_BOTTOM:
  427. case SEI_PIC_STRUCT_BOTTOM_TOP:
  428. if (FIELD_OR_MBAFF_PICTURE(h))
  429. cur->f->interlaced_frame = 1;
  430. else
  431. // try to flag soft telecine progressive
  432. cur->f->interlaced_frame = h->prev_interlaced_frame;
  433. break;
  434. case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
  435. case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
  436. /* Signal the possibility of telecined film externally
  437. * (pic_struct 5,6). From these hints, let the applications
  438. * decide if they apply deinterlacing. */
  439. cur->f->repeat_pict = 1;
  440. break;
  441. case SEI_PIC_STRUCT_FRAME_DOUBLING:
  442. cur->f->repeat_pict = 2;
  443. break;
  444. case SEI_PIC_STRUCT_FRAME_TRIPLING:
  445. cur->f->repeat_pict = 4;
  446. break;
  447. }
  448. if ((pt->ct_type & 3) &&
  449. pt->pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
  450. cur->f->interlaced_frame = (pt->ct_type & (1 << 1)) != 0;
  451. } else {
  452. /* Derive interlacing flag from used decoding process. */
  453. cur->f->interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
  454. }
  455. h->prev_interlaced_frame = cur->f->interlaced_frame;
  456. if (cur->field_poc[0] != cur->field_poc[1]) {
  457. /* Derive top_field_first from field pocs. */
  458. cur->f->top_field_first = cur->field_poc[0] < cur->field_poc[1];
  459. } else {
  460. if (sps->pic_struct_present_flag) {
  461. /* Use picture timing SEI information. Even if it is a
  462. * information of a past frame, better than nothing. */
  463. if (h->sei.picture_timing.pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
  464. h->sei.picture_timing.pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
  465. cur->f->top_field_first = 1;
  466. else
  467. cur->f->top_field_first = 0;
  468. } else if (cur->f->interlaced_frame) {
  469. /* Default to top field first when pic_struct_present_flag
  470. * is not set but interlaced frame detected */
  471. cur->f->top_field_first = 1;
  472. } else {
  473. /* Most likely progressive */
  474. cur->f->top_field_first = 0;
  475. }
  476. }
  477. if (h->sei.frame_packing.present &&
  478. h->sei.frame_packing.frame_packing_arrangement_type <= 6 &&
  479. h->sei.frame_packing.content_interpretation_type > 0 &&
  480. h->sei.frame_packing.content_interpretation_type < 3) {
  481. H264SEIFramePacking *fp = &h->sei.frame_packing;
  482. AVStereo3D *stereo = av_stereo3d_create_side_data(cur->f);
  483. if (stereo) {
  484. switch (fp->frame_packing_arrangement_type) {
  485. case 0:
  486. stereo->type = AV_STEREO3D_CHECKERBOARD;
  487. break;
  488. case 1:
  489. stereo->type = AV_STEREO3D_COLUMNS;
  490. break;
  491. case 2:
  492. stereo->type = AV_STEREO3D_LINES;
  493. break;
  494. case 3:
  495. if (fp->quincunx_sampling_flag)
  496. stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
  497. else
  498. stereo->type = AV_STEREO3D_SIDEBYSIDE;
  499. break;
  500. case 4:
  501. stereo->type = AV_STEREO3D_TOPBOTTOM;
  502. break;
  503. case 5:
  504. stereo->type = AV_STEREO3D_FRAMESEQUENCE;
  505. break;
  506. case 6:
  507. stereo->type = AV_STEREO3D_2D;
  508. break;
  509. }
  510. if (fp->content_interpretation_type == 2)
  511. stereo->flags = AV_STEREO3D_FLAG_INVERT;
  512. }
  513. }
  514. if (h->sei.display_orientation.present &&
  515. (h->sei.display_orientation.anticlockwise_rotation ||
  516. h->sei.display_orientation.hflip ||
  517. h->sei.display_orientation.vflip)) {
  518. H264SEIDisplayOrientation *o = &h->sei.display_orientation;
  519. double angle = o->anticlockwise_rotation * 360 / (double) (1 << 16);
  520. AVFrameSideData *rotation = av_frame_new_side_data(cur->f,
  521. AV_FRAME_DATA_DISPLAYMATRIX,
  522. sizeof(int32_t) * 9);
  523. if (rotation) {
  524. av_display_rotation_set((int32_t *)rotation->data, angle);
  525. av_display_matrix_flip((int32_t *)rotation->data,
  526. o->hflip, o->vflip);
  527. }
  528. }
  529. if (h->sei.afd.present) {
  530. AVFrameSideData *sd = av_frame_new_side_data(cur->f, AV_FRAME_DATA_AFD,
  531. sizeof(uint8_t));
  532. if (sd) {
  533. *sd->data = h->sei.afd.active_format_description;
  534. h->sei.afd.present = 0;
  535. }
  536. }
  537. if (h->sei.a53_caption.a53_caption) {
  538. H264SEIA53Caption *a53 = &h->sei.a53_caption;
  539. AVFrameSideData *sd = av_frame_new_side_data(cur->f,
  540. AV_FRAME_DATA_A53_CC,
  541. a53->a53_caption_size);
  542. if (sd)
  543. memcpy(sd->data, a53->a53_caption, a53->a53_caption_size);
  544. av_freep(&a53->a53_caption);
  545. a53->a53_caption_size = 0;
  546. h->avctx->properties |= FF_CODEC_PROPERTY_CLOSED_CAPTIONS;
  547. }
  548. cur->mmco_reset = h->mmco_reset;
  549. h->mmco_reset = 0;
  550. // FIXME do something with unavailable reference frames
  551. /* Sort B-frames into display order */
  552. if (sps->bitstream_restriction_flag ||
  553. h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
  554. h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, sps->num_reorder_frames);
  555. }
  556. for (i = 0; 1; i++) {
  557. if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
  558. if(i)
  559. h->last_pocs[i-1] = cur->poc;
  560. break;
  561. } else if(i) {
  562. h->last_pocs[i-1]= h->last_pocs[i];
  563. }
  564. }
  565. out_of_order = MAX_DELAYED_PIC_COUNT - i;
  566. if( cur->f->pict_type == AV_PICTURE_TYPE_B
  567. || (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))
  568. out_of_order = FFMAX(out_of_order, 1);
  569. if (out_of_order == MAX_DELAYED_PIC_COUNT) {
  570. av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
  571. for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
  572. h->last_pocs[i] = INT_MIN;
  573. h->last_pocs[0] = cur->poc;
  574. cur->mmco_reset = 1;
  575. } else if(h->avctx->has_b_frames < out_of_order && !sps->bitstream_restriction_flag){
  576. av_log(h->avctx, AV_LOG_INFO, "Increasing reorder buffer to %d\n", out_of_order);
  577. h->avctx->has_b_frames = out_of_order;
  578. }
  579. pics = 0;
  580. while (h->delayed_pic[pics])
  581. pics++;
  582. av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
  583. h->delayed_pic[pics++] = cur;
  584. if (cur->reference == 0)
  585. cur->reference = DELAYED_PIC_REF;
  586. out = h->delayed_pic[0];
  587. out_idx = 0;
  588. for (i = 1; h->delayed_pic[i] &&
  589. !h->delayed_pic[i]->f->key_frame &&
  590. !h->delayed_pic[i]->mmco_reset;
  591. i++)
  592. if (h->delayed_pic[i]->poc < out->poc) {
  593. out = h->delayed_pic[i];
  594. out_idx = i;
  595. }
  596. if (h->avctx->has_b_frames == 0 &&
  597. (h->delayed_pic[0]->f->key_frame || h->delayed_pic[0]->mmco_reset))
  598. h->next_outputed_poc = INT_MIN;
  599. out_of_order = out->poc < h->next_outputed_poc;
  600. if (out_of_order || pics > h->avctx->has_b_frames) {
  601. out->reference &= ~DELAYED_PIC_REF;
  602. for (i = out_idx; h->delayed_pic[i]; i++)
  603. h->delayed_pic[i] = h->delayed_pic[i + 1];
  604. }
  605. if (!out_of_order && pics > h->avctx->has_b_frames) {
  606. h->next_output_pic = out;
  607. if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f->key_frame || h->delayed_pic[0]->mmco_reset)) {
  608. h->next_outputed_poc = INT_MIN;
  609. } else
  610. h->next_outputed_poc = out->poc;
  611. } else {
  612. av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
  613. }
  614. if (h->next_output_pic) {
  615. if (h->next_output_pic->recovered) {
  616. // We have reached an recovery point and all frames after it in
  617. // display order are "recovered".
  618. h->frame_recovered |= FRAME_RECOVERED_SEI;
  619. }
  620. h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
  621. }
  622. if (setup_finished && !h->avctx->hwaccel) {
  623. ff_thread_finish_setup(h->avctx);
  624. if (h->avctx->active_thread_type & FF_THREAD_FRAME)
  625. h->setup_finished = 1;
  626. }
  627. }
  628. /**
  629. * instantaneous decoder refresh.
  630. */
  631. static void idr(H264Context *h)
  632. {
  633. int i;
  634. ff_h264_remove_all_refs(h);
  635. h->poc.prev_frame_num =
  636. h->poc.prev_frame_num_offset = 0;
  637. h->poc.prev_poc_msb = 1<<16;
  638. h->poc.prev_poc_lsb = 0;
  639. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  640. h->last_pocs[i] = INT_MIN;
  641. }
  642. /* forget old pics after a seek */
  643. void ff_h264_flush_change(H264Context *h)
  644. {
  645. int i, j;
  646. h->next_outputed_poc = INT_MIN;
  647. h->prev_interlaced_frame = 1;
  648. idr(h);
  649. h->poc.prev_frame_num = -1;
  650. if (h->cur_pic_ptr) {
  651. h->cur_pic_ptr->reference = 0;
  652. for (j=i=0; h->delayed_pic[i]; i++)
  653. if (h->delayed_pic[i] != h->cur_pic_ptr)
  654. h->delayed_pic[j++] = h->delayed_pic[i];
  655. h->delayed_pic[j] = NULL;
  656. }
  657. ff_h264_unref_picture(h, &h->last_pic_for_ec);
  658. h->first_field = 0;
  659. ff_h264_sei_uninit(&h->sei);
  660. h->recovery_frame = -1;
  661. h->frame_recovered = 0;
  662. h->current_slice = 0;
  663. h->mmco_reset = 1;
  664. }
  665. /* forget old pics after a seek */
  666. static void flush_dpb(AVCodecContext *avctx)
  667. {
  668. H264Context *h = avctx->priv_data;
  669. int i;
  670. memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
  671. ff_h264_flush_change(h);
  672. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
  673. ff_h264_unref_picture(h, &h->DPB[i]);
  674. h->cur_pic_ptr = NULL;
  675. ff_h264_unref_picture(h, &h->cur_pic);
  676. h->mb_y = 0;
  677. ff_h264_free_tables(h);
  678. h->context_initialized = 0;
  679. }
  680. #if FF_API_CAP_VDPAU
  681. static const uint8_t start_code[] = { 0x00, 0x00, 0x01 };
  682. #endif
  683. static int get_last_needed_nal(H264Context *h)
  684. {
  685. int nals_needed = 0;
  686. int first_slice = 0;
  687. int i;
  688. int ret;
  689. for (i = 0; i < h->pkt.nb_nals; i++) {
  690. H2645NAL *nal = &h->pkt.nals[i];
  691. GetBitContext gb;
  692. /* packets can sometimes contain multiple PPS/SPS,
  693. * e.g. two PAFF field pictures in one packet, or a demuxer
  694. * which splits NALs strangely if so, when frame threading we
  695. * can't start the next thread until we've read all of them */
  696. switch (nal->type) {
  697. case NAL_SPS:
  698. case NAL_PPS:
  699. nals_needed = i;
  700. break;
  701. case NAL_DPA:
  702. case NAL_IDR_SLICE:
  703. case NAL_SLICE:
  704. ret = init_get_bits8(&gb, nal->data + 1, (nal->size - 1));
  705. if (ret < 0)
  706. return ret;
  707. if (!get_ue_golomb_long(&gb) || // first_mb_in_slice
  708. !first_slice ||
  709. first_slice != nal->type)
  710. nals_needed = i;
  711. if (!first_slice)
  712. first_slice = nal->type;
  713. }
  714. }
  715. return nals_needed;
  716. }
  717. static void debug_green_metadata(const H264SEIGreenMetaData *gm, void *logctx)
  718. {
  719. av_log(logctx, AV_LOG_DEBUG, "Green Metadata Info SEI message\n");
  720. av_log(logctx, AV_LOG_DEBUG, " green_metadata_type: %d\n", gm->green_metadata_type);
  721. if (gm->green_metadata_type == 0) {
  722. av_log(logctx, AV_LOG_DEBUG, " green_metadata_period_type: %d\n", gm->period_type);
  723. if (gm->period_type == 2)
  724. av_log(logctx, AV_LOG_DEBUG, " green_metadata_num_seconds: %d\n", gm->num_seconds);
  725. else if (gm->period_type == 3)
  726. av_log(logctx, AV_LOG_DEBUG, " green_metadata_num_pictures: %d\n", gm->num_pictures);
  727. av_log(logctx, AV_LOG_DEBUG, " SEI GREEN Complexity Metrics: %f %f %f %f\n",
  728. (float)gm->percent_non_zero_macroblocks/255,
  729. (float)gm->percent_intra_coded_macroblocks/255,
  730. (float)gm->percent_six_tap_filtering/255,
  731. (float)gm->percent_alpha_point_deblocking_instance/255);
  732. } else if (gm->green_metadata_type == 1) {
  733. av_log(logctx, AV_LOG_DEBUG, " xsd_metric_type: %d\n", gm->xsd_metric_type);
  734. if (gm->xsd_metric_type == 0)
  735. av_log(logctx, AV_LOG_DEBUG, " xsd_metric_value: %f\n",
  736. (float)gm->xsd_metric_value/100);
  737. }
  738. }
  739. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size)
  740. {
  741. AVCodecContext *const avctx = h->avctx;
  742. unsigned context_count = 0;
  743. int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
  744. int idr_cleared=0;
  745. int i, ret = 0;
  746. h->nal_unit_type= 0;
  747. h->max_contexts = h->nb_slice_ctx;
  748. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)) {
  749. h->current_slice = 0;
  750. if (!h->first_field)
  751. h->cur_pic_ptr = NULL;
  752. ff_h264_sei_uninit(&h->sei);
  753. }
  754. if (h->nal_length_size == 4) {
  755. if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
  756. h->is_avc = 0;
  757. }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
  758. h->is_avc = 1;
  759. }
  760. ret = ff_h2645_packet_split(&h->pkt, buf, buf_size, avctx, h->is_avc,
  761. h->nal_length_size, avctx->codec_id);
  762. if (ret < 0) {
  763. av_log(avctx, AV_LOG_ERROR,
  764. "Error splitting the input into NAL units.\n");
  765. return ret;
  766. }
  767. if (avctx->active_thread_type & FF_THREAD_FRAME)
  768. nals_needed = get_last_needed_nal(h);
  769. if (nals_needed < 0)
  770. return nals_needed;
  771. for (i = 0; i < h->pkt.nb_nals; i++) {
  772. H2645NAL *nal = &h->pkt.nals[i];
  773. H264SliceContext *sl = &h->slice_ctx[context_count];
  774. int err;
  775. if (avctx->skip_frame >= AVDISCARD_NONREF &&
  776. nal->ref_idc == 0 && nal->type != NAL_SEI)
  777. continue;
  778. again:
  779. // FIXME these should stop being context-global variables
  780. h->nal_ref_idc = nal->ref_idc;
  781. h->nal_unit_type = nal->type;
  782. err = 0;
  783. switch (nal->type) {
  784. case NAL_IDR_SLICE:
  785. if ((nal->data[1] & 0xFC) == 0x98) {
  786. av_log(h->avctx, AV_LOG_ERROR, "Invalid inter IDR frame\n");
  787. h->next_outputed_poc = INT_MIN;
  788. ret = -1;
  789. goto end;
  790. }
  791. if (nal->type != NAL_IDR_SLICE) {
  792. av_log(h->avctx, AV_LOG_ERROR,
  793. "Invalid mix of idr and non-idr slices\n");
  794. ret = -1;
  795. goto end;
  796. }
  797. if(!idr_cleared) {
  798. if (h->current_slice && (avctx->active_thread_type & FF_THREAD_SLICE)) {
  799. av_log(h, AV_LOG_ERROR, "invalid mixed IDR / non IDR frames cannot be decoded in slice multithreading mode\n");
  800. ret = AVERROR_INVALIDDATA;
  801. goto end;
  802. }
  803. idr(h); // FIXME ensure we don't lose some frames if there is reordering
  804. }
  805. idr_cleared = 1;
  806. h->has_recovery_point = 1;
  807. case NAL_SLICE:
  808. sl->gb = nal->gb;
  809. if ((err = ff_h264_decode_slice_header(h, sl, nal)))
  810. break;
  811. if (h->sei.recovery_point.recovery_frame_cnt >= 0) {
  812. const int sei_recovery_frame_cnt = h->sei.recovery_point.recovery_frame_cnt;
  813. if (h->poc.frame_num != sei_recovery_frame_cnt || sl->slice_type_nos != AV_PICTURE_TYPE_I)
  814. h->valid_recovery_point = 1;
  815. if ( h->recovery_frame < 0
  816. || av_mod_uintp2(h->recovery_frame - h->poc.frame_num, h->ps.sps->log2_max_frame_num) > sei_recovery_frame_cnt) {
  817. h->recovery_frame = av_mod_uintp2(h->poc.frame_num + sei_recovery_frame_cnt, h->ps.sps->log2_max_frame_num);
  818. if (!h->valid_recovery_point)
  819. h->recovery_frame = h->poc.frame_num;
  820. }
  821. }
  822. h->cur_pic_ptr->f->key_frame |= (nal->type == NAL_IDR_SLICE);
  823. if (nal->type == NAL_IDR_SLICE ||
  824. (h->recovery_frame == h->poc.frame_num && nal->ref_idc)) {
  825. h->recovery_frame = -1;
  826. h->cur_pic_ptr->recovered = 1;
  827. }
  828. // If we have an IDR, all frames after it in decoded order are
  829. // "recovered".
  830. if (nal->type == NAL_IDR_SLICE)
  831. h->frame_recovered |= FRAME_RECOVERED_IDR;
  832. #if 1
  833. h->cur_pic_ptr->recovered |= h->frame_recovered;
  834. #else
  835. h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
  836. #endif
  837. if (h->current_slice == 1) {
  838. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS))
  839. decode_postinit(h, i >= nals_needed);
  840. if (h->avctx->hwaccel &&
  841. (ret = h->avctx->hwaccel->start_frame(h->avctx, buf, buf_size)) < 0)
  842. goto end;
  843. #if FF_API_CAP_VDPAU
  844. if (CONFIG_H264_VDPAU_DECODER &&
  845. h->avctx->codec->capabilities & AV_CODEC_CAP_HWACCEL_VDPAU)
  846. ff_vdpau_h264_picture_start(h);
  847. #endif
  848. }
  849. if (sl->redundant_pic_count == 0) {
  850. if (avctx->hwaccel) {
  851. ret = avctx->hwaccel->decode_slice(avctx,
  852. nal->raw_data,
  853. nal->raw_size);
  854. if (ret < 0)
  855. goto end;
  856. #if FF_API_CAP_VDPAU
  857. } else if (CONFIG_H264_VDPAU_DECODER &&
  858. h->avctx->codec->capabilities & AV_CODEC_CAP_HWACCEL_VDPAU) {
  859. ff_vdpau_add_data_chunk(h->cur_pic_ptr->f->data[0],
  860. start_code,
  861. sizeof(start_code));
  862. ff_vdpau_add_data_chunk(h->cur_pic_ptr->f->data[0],
  863. nal->raw_data,
  864. nal->raw_size);
  865. #endif
  866. } else
  867. context_count++;
  868. }
  869. break;
  870. case NAL_DPA:
  871. case NAL_DPB:
  872. case NAL_DPC:
  873. avpriv_request_sample(avctx, "data partitioning");
  874. break;
  875. case NAL_SEI:
  876. ret = ff_h264_sei_decode(&h->sei, &nal->gb, &h->ps, avctx);
  877. h->has_recovery_point = h->has_recovery_point || h->sei.recovery_point.recovery_frame_cnt != -1;
  878. if (avctx->debug & FF_DEBUG_GREEN_MD)
  879. debug_green_metadata(&h->sei.green_metadata, h->avctx);
  880. #if FF_API_AFD
  881. FF_DISABLE_DEPRECATION_WARNINGS
  882. h->avctx->dtg_active_format = h->sei.afd.active_format_description;
  883. FF_ENABLE_DEPRECATION_WARNINGS
  884. #endif /* FF_API_AFD */
  885. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  886. goto end;
  887. break;
  888. case NAL_SPS: {
  889. GetBitContext tmp_gb = nal->gb;
  890. if (ff_h264_decode_seq_parameter_set(&tmp_gb, avctx, &h->ps, 0) >= 0)
  891. break;
  892. av_log(h->avctx, AV_LOG_DEBUG,
  893. "SPS decoding failure, trying again with the complete NAL\n");
  894. init_get_bits8(&tmp_gb, nal->raw_data + 1, nal->raw_size - 1);
  895. if (ff_h264_decode_seq_parameter_set(&tmp_gb, avctx, &h->ps, 0) >= 0)
  896. break;
  897. ff_h264_decode_seq_parameter_set(&nal->gb, avctx, &h->ps, 1);
  898. break;
  899. }
  900. case NAL_PPS:
  901. ret = ff_h264_decode_picture_parameter_set(&nal->gb, avctx, &h->ps,
  902. nal->size_bits);
  903. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  904. goto end;
  905. break;
  906. case NAL_AUD:
  907. case NAL_END_SEQUENCE:
  908. case NAL_END_STREAM:
  909. case NAL_FILLER_DATA:
  910. case NAL_SPS_EXT:
  911. case NAL_AUXILIARY_SLICE:
  912. break;
  913. case NAL_FF_IGNORE:
  914. break;
  915. default:
  916. av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
  917. nal->type, nal->size_bits);
  918. }
  919. if (context_count == h->max_contexts) {
  920. ret = ff_h264_execute_decode_slices(h, context_count);
  921. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  922. goto end;
  923. context_count = 0;
  924. }
  925. if (err < 0 || err == SLICE_SKIPED) {
  926. if (err < 0)
  927. av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
  928. sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
  929. } else if (err == SLICE_SINGLETHREAD) {
  930. if (context_count > 0) {
  931. ret = ff_h264_execute_decode_slices(h, context_count);
  932. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  933. goto end;
  934. context_count = 0;
  935. }
  936. /* Slice could not be decoded in parallel mode, restart. */
  937. sl = &h->slice_ctx[0];
  938. goto again;
  939. }
  940. }
  941. if (context_count) {
  942. ret = ff_h264_execute_decode_slices(h, context_count);
  943. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  944. goto end;
  945. }
  946. ret = 0;
  947. end:
  948. #if CONFIG_ERROR_RESILIENCE
  949. /*
  950. * FIXME: Error handling code does not seem to support interlaced
  951. * when slices span multiple rows
  952. * The ff_er_add_slice calls don't work right for bottom
  953. * fields; they cause massive erroneous error concealing
  954. * Error marking covers both fields (top and bottom).
  955. * This causes a mismatched s->error_count
  956. * and a bad error table. Further, the error count goes to
  957. * INT_MAX when called for bottom field, because mb_y is
  958. * past end by one (callers fault) and resync_mb_y != 0
  959. * causes problems for the first MB line, too.
  960. */
  961. if (!FIELD_PICTURE(h) && h->current_slice &&
  962. h->ps.sps == (const SPS*)h->ps.sps_list[h->ps.pps->sps_id]->data &&
  963. h->enable_er) {
  964. H264SliceContext *sl = h->slice_ctx;
  965. int use_last_pic = h->last_pic_for_ec.f->buf[0] && !sl->ref_count[0];
  966. ff_h264_set_erpic(&sl->er.cur_pic, h->cur_pic_ptr);
  967. if (use_last_pic) {
  968. ff_h264_set_erpic(&sl->er.last_pic, &h->last_pic_for_ec);
  969. sl->ref_list[0][0].parent = &h->last_pic_for_ec;
  970. memcpy(sl->ref_list[0][0].data, h->last_pic_for_ec.f->data, sizeof(sl->ref_list[0][0].data));
  971. memcpy(sl->ref_list[0][0].linesize, h->last_pic_for_ec.f->linesize, sizeof(sl->ref_list[0][0].linesize));
  972. sl->ref_list[0][0].reference = h->last_pic_for_ec.reference;
  973. } else if (sl->ref_count[0]) {
  974. ff_h264_set_erpic(&sl->er.last_pic, sl->ref_list[0][0].parent);
  975. } else
  976. ff_h264_set_erpic(&sl->er.last_pic, NULL);
  977. if (sl->ref_count[1])
  978. ff_h264_set_erpic(&sl->er.next_pic, sl->ref_list[1][0].parent);
  979. sl->er.ref_count = sl->ref_count[0];
  980. ff_er_frame_end(&sl->er);
  981. if (use_last_pic)
  982. memset(&sl->ref_list[0][0], 0, sizeof(sl->ref_list[0][0]));
  983. }
  984. #endif /* CONFIG_ERROR_RESILIENCE */
  985. /* clean up */
  986. if (h->cur_pic_ptr && !h->droppable) {
  987. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
  988. h->picture_structure == PICT_BOTTOM_FIELD);
  989. }
  990. return (ret < 0) ? ret : buf_size;
  991. }
  992. /**
  993. * Return the number of bytes consumed for building the current frame.
  994. */
  995. static int get_consumed_bytes(int pos, int buf_size)
  996. {
  997. if (pos == 0)
  998. pos = 1; // avoid infinite loops (I doubt that is needed but...)
  999. if (pos + 10 > buf_size)
  1000. pos = buf_size; // oops ;)
  1001. return pos;
  1002. }
  1003. static int output_frame(H264Context *h, AVFrame *dst, H264Picture *srcp)
  1004. {
  1005. AVFrame *src = srcp->f;
  1006. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(src->format);
  1007. int i;
  1008. int ret = av_frame_ref(dst, src);
  1009. if (ret < 0)
  1010. return ret;
  1011. av_dict_set(&dst->metadata, "stereo_mode", ff_h264_sei_stereo_mode(&h->sei.frame_packing), 0);
  1012. h->backup_width = h->avctx->width;
  1013. h->backup_height = h->avctx->height;
  1014. h->backup_pix_fmt = h->avctx->pix_fmt;
  1015. h->avctx->width = dst->width;
  1016. h->avctx->height = dst->height;
  1017. h->avctx->pix_fmt = dst->format;
  1018. if (srcp->sei_recovery_frame_cnt == 0)
  1019. dst->key_frame = 1;
  1020. if (!srcp->crop)
  1021. return 0;
  1022. for (i = 0; i < desc->nb_components; i++) {
  1023. int hshift = (i > 0) ? desc->log2_chroma_w : 0;
  1024. int vshift = (i > 0) ? desc->log2_chroma_h : 0;
  1025. int off = ((srcp->crop_left >> hshift) << h->pixel_shift) +
  1026. (srcp->crop_top >> vshift) * dst->linesize[i];
  1027. dst->data[i] += off;
  1028. }
  1029. return 0;
  1030. }
  1031. static int is_extra(const uint8_t *buf, int buf_size)
  1032. {
  1033. int cnt= buf[5]&0x1f;
  1034. const uint8_t *p= buf+6;
  1035. while(cnt--){
  1036. int nalsize= AV_RB16(p) + 2;
  1037. if(nalsize > buf_size - (p-buf) || (p[2] & 0x9F) != 7)
  1038. return 0;
  1039. p += nalsize;
  1040. }
  1041. cnt = *(p++);
  1042. if(!cnt)
  1043. return 0;
  1044. while(cnt--){
  1045. int nalsize= AV_RB16(p) + 2;
  1046. if(nalsize > buf_size - (p-buf) || (p[2] & 0x9F) != 8)
  1047. return 0;
  1048. p += nalsize;
  1049. }
  1050. return 1;
  1051. }
  1052. static int h264_decode_frame(AVCodecContext *avctx, void *data,
  1053. int *got_frame, AVPacket *avpkt)
  1054. {
  1055. const uint8_t *buf = avpkt->data;
  1056. int buf_size = avpkt->size;
  1057. H264Context *h = avctx->priv_data;
  1058. AVFrame *pict = data;
  1059. int buf_index = 0;
  1060. H264Picture *out;
  1061. int i, out_idx;
  1062. int ret;
  1063. h->flags = avctx->flags;
  1064. h->setup_finished = 0;
  1065. if (h->backup_width != -1) {
  1066. avctx->width = h->backup_width;
  1067. h->backup_width = -1;
  1068. }
  1069. if (h->backup_height != -1) {
  1070. avctx->height = h->backup_height;
  1071. h->backup_height = -1;
  1072. }
  1073. if (h->backup_pix_fmt != AV_PIX_FMT_NONE) {
  1074. avctx->pix_fmt = h->backup_pix_fmt;
  1075. h->backup_pix_fmt = AV_PIX_FMT_NONE;
  1076. }
  1077. ff_h264_unref_picture(h, &h->last_pic_for_ec);
  1078. /* end of stream, output what is still in the buffers */
  1079. if (buf_size == 0) {
  1080. out:
  1081. h->cur_pic_ptr = NULL;
  1082. h->first_field = 0;
  1083. // FIXME factorize this with the output code below
  1084. out = h->delayed_pic[0];
  1085. out_idx = 0;
  1086. for (i = 1;
  1087. h->delayed_pic[i] &&
  1088. !h->delayed_pic[i]->f->key_frame &&
  1089. !h->delayed_pic[i]->mmco_reset;
  1090. i++)
  1091. if (h->delayed_pic[i]->poc < out->poc) {
  1092. out = h->delayed_pic[i];
  1093. out_idx = i;
  1094. }
  1095. for (i = out_idx; h->delayed_pic[i]; i++)
  1096. h->delayed_pic[i] = h->delayed_pic[i + 1];
  1097. if (out) {
  1098. out->reference &= ~DELAYED_PIC_REF;
  1099. ret = output_frame(h, pict, out);
  1100. if (ret < 0)
  1101. return ret;
  1102. *got_frame = 1;
  1103. }
  1104. return buf_index;
  1105. }
  1106. if (h->is_avc && av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, NULL)) {
  1107. int side_size;
  1108. uint8_t *side = av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
  1109. if (is_extra(side, side_size))
  1110. ff_h264_decode_extradata(side, side_size,
  1111. &h->ps, &h->is_avc, &h->nal_length_size,
  1112. avctx->err_recognition, avctx);
  1113. }
  1114. if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
  1115. if (is_extra(buf, buf_size))
  1116. return ff_h264_decode_extradata(buf, buf_size,
  1117. &h->ps, &h->is_avc, &h->nal_length_size,
  1118. avctx->err_recognition, avctx);
  1119. }
  1120. buf_index = decode_nal_units(h, buf, buf_size);
  1121. if (buf_index < 0)
  1122. return AVERROR_INVALIDDATA;
  1123. if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
  1124. av_assert0(buf_index <= buf_size);
  1125. goto out;
  1126. }
  1127. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
  1128. if (avctx->skip_frame >= AVDISCARD_NONREF ||
  1129. buf_size >= 4 && !memcmp("Q264", buf, 4))
  1130. return buf_size;
  1131. av_log(avctx, AV_LOG_ERROR, "no frame!\n");
  1132. return AVERROR_INVALIDDATA;
  1133. }
  1134. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) ||
  1135. (h->mb_y >= h->mb_height && h->mb_height)) {
  1136. if (avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)
  1137. decode_postinit(h, 1);
  1138. if ((ret = ff_h264_field_end(h, &h->slice_ctx[0], 0)) < 0)
  1139. return ret;
  1140. /* Wait for second field. */
  1141. *got_frame = 0;
  1142. if (h->next_output_pic && ((avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT) ||
  1143. (avctx->flags2 & AV_CODEC_FLAG2_SHOW_ALL) ||
  1144. h->next_output_pic->recovered)) {
  1145. if (!h->next_output_pic->recovered)
  1146. h->next_output_pic->f->flags |= AV_FRAME_FLAG_CORRUPT;
  1147. if (!h->avctx->hwaccel &&
  1148. (h->next_output_pic->field_poc[0] == INT_MAX ||
  1149. h->next_output_pic->field_poc[1] == INT_MAX)
  1150. ) {
  1151. int p;
  1152. AVFrame *f = h->next_output_pic->f;
  1153. int field = h->next_output_pic->field_poc[0] == INT_MAX;
  1154. uint8_t *dst_data[4];
  1155. int linesizes[4];
  1156. const uint8_t *src_data[4];
  1157. av_log(h->avctx, AV_LOG_DEBUG, "Duplicating field %d to fill missing\n", field);
  1158. for (p = 0; p<4; p++) {
  1159. dst_data[p] = f->data[p] + (field^1)*f->linesize[p];
  1160. src_data[p] = f->data[p] + field *f->linesize[p];
  1161. linesizes[p] = 2*f->linesize[p];
  1162. }
  1163. av_image_copy(dst_data, linesizes, src_data, linesizes,
  1164. f->format, f->width, f->height>>1);
  1165. }
  1166. ret = output_frame(h, pict, h->next_output_pic);
  1167. if (ret < 0)
  1168. return ret;
  1169. *got_frame = 1;
  1170. if (CONFIG_MPEGVIDEO) {
  1171. ff_print_debug_info2(h->avctx, pict, NULL,
  1172. h->next_output_pic->mb_type,
  1173. h->next_output_pic->qscale_table,
  1174. h->next_output_pic->motion_val,
  1175. NULL,
  1176. h->mb_width, h->mb_height, h->mb_stride, 1);
  1177. }
  1178. }
  1179. }
  1180. av_assert0(pict->buf[0] || !*got_frame);
  1181. ff_h264_unref_picture(h, &h->last_pic_for_ec);
  1182. return get_consumed_bytes(buf_index, buf_size);
  1183. }
  1184. #define OFFSET(x) offsetof(H264Context, x)
  1185. #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  1186. static const AVOption h264_options[] = {
  1187. {"is_avc", "is avc", offsetof(H264Context, is_avc), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, 0},
  1188. {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
  1189. { "enable_er", "Enable error resilience on damaged frames (unsafe)", OFFSET(enable_er), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, VD },
  1190. { NULL },
  1191. };
  1192. static const AVClass h264_class = {
  1193. .class_name = "H264 Decoder",
  1194. .item_name = av_default_item_name,
  1195. .option = h264_options,
  1196. .version = LIBAVUTIL_VERSION_INT,
  1197. };
  1198. AVCodec ff_h264_decoder = {
  1199. .name = "h264",
  1200. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
  1201. .type = AVMEDIA_TYPE_VIDEO,
  1202. .id = AV_CODEC_ID_H264,
  1203. .priv_data_size = sizeof(H264Context),
  1204. .init = ff_h264_decode_init,
  1205. .close = h264_decode_end,
  1206. .decode = h264_decode_frame,
  1207. .capabilities = /*AV_CODEC_CAP_DRAW_HORIZ_BAND |*/ AV_CODEC_CAP_DR1 |
  1208. AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS |
  1209. AV_CODEC_CAP_FRAME_THREADS,
  1210. .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
  1211. .flush = flush_dpb,
  1212. .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
  1213. .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
  1214. .profiles = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
  1215. .priv_class = &h264_class,
  1216. };
  1217. #if CONFIG_H264_VDPAU_DECODER && FF_API_VDPAU
  1218. static const AVClass h264_vdpau_class = {
  1219. .class_name = "H264 VDPAU Decoder",
  1220. .item_name = av_default_item_name,
  1221. .option = h264_options,
  1222. .version = LIBAVUTIL_VERSION_INT,
  1223. };
  1224. AVCodec ff_h264_vdpau_decoder = {
  1225. .name = "h264_vdpau",
  1226. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
  1227. .type = AVMEDIA_TYPE_VIDEO,
  1228. .id = AV_CODEC_ID_H264,
  1229. .priv_data_size = sizeof(H264Context),
  1230. .init = ff_h264_decode_init,
  1231. .close = h264_decode_end,
  1232. .decode = h264_decode_frame,
  1233. .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY | AV_CODEC_CAP_HWACCEL_VDPAU,
  1234. .flush = flush_dpb,
  1235. .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
  1236. AV_PIX_FMT_NONE},
  1237. .profiles = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
  1238. .priv_class = &h264_vdpau_class,
  1239. };
  1240. #endif