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.

810 lines
25KB

  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 Libav.
  6. *
  7. * Libav 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. * Libav 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 Libav; 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. #include "libavutil/display.h"
  27. #include "libavutil/imgutils.h"
  28. #include "libavutil/opt.h"
  29. #include "libavutil/stereo3d.h"
  30. #include "libavutil/timer.h"
  31. #include "internal.h"
  32. #include "bytestream.h"
  33. #include "cabac.h"
  34. #include "cabac_functions.h"
  35. #include "error_resilience.h"
  36. #include "avcodec.h"
  37. #include "h264.h"
  38. #include "h264dec.h"
  39. #include "h2645_parse.h"
  40. #include "h264data.h"
  41. #include "h264chroma.h"
  42. #include "h264_mvpred.h"
  43. #include "h264_ps.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 <assert.h>
  52. const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
  53. static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
  54. int (*mv)[2][4][2],
  55. int mb_x, int mb_y, int mb_intra, int mb_skipped)
  56. {
  57. H264Context *h = opaque;
  58. H264SliceContext *sl = &h->slice_ctx[0];
  59. sl->mb_x = mb_x;
  60. sl->mb_y = mb_y;
  61. sl->mb_xy = mb_x + mb_y * h->mb_stride;
  62. memset(sl->non_zero_count_cache, 0, sizeof(sl->non_zero_count_cache));
  63. assert(ref >= 0);
  64. /* FIXME: It is possible albeit uncommon that slice references
  65. * differ between slices. We take the easy approach and ignore
  66. * it for now. If this turns out to have any relevance in
  67. * practice then correct remapping should be added. */
  68. if (ref >= sl->ref_count[0])
  69. ref = 0;
  70. fill_rectangle(&h->cur_pic.ref_index[0][4 * sl->mb_xy],
  71. 2, 2, 2, ref, 1);
  72. fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
  73. fill_rectangle(sl->mv_cache[0][scan8[0]], 4, 4, 8,
  74. pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
  75. assert(!FRAME_MBAFF(h));
  76. ff_h264_hl_decode_mb(h, &h->slice_ctx[0]);
  77. }
  78. void ff_h264_draw_horiz_band(const H264Context *h, H264SliceContext *sl,
  79. int y, int height)
  80. {
  81. AVCodecContext *avctx = h->avctx;
  82. const AVFrame *src = h->cur_pic.f;
  83. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
  84. int vshift = desc->log2_chroma_h;
  85. const int field_pic = h->picture_structure != PICT_FRAME;
  86. if (field_pic) {
  87. height <<= 1;
  88. y <<= 1;
  89. }
  90. height = FFMIN(height, avctx->height - y);
  91. if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
  92. return;
  93. if (avctx->draw_horiz_band) {
  94. int offset[AV_NUM_DATA_POINTERS];
  95. int i;
  96. offset[0] = y * src->linesize[0];
  97. offset[1] =
  98. offset[2] = (y >> vshift) * src->linesize[1];
  99. for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
  100. offset[i] = 0;
  101. emms_c();
  102. avctx->draw_horiz_band(avctx, src, offset,
  103. y, h->picture_structure, height);
  104. }
  105. }
  106. void ff_h264_free_tables(H264Context *h)
  107. {
  108. int i;
  109. av_freep(&h->intra4x4_pred_mode);
  110. av_freep(&h->chroma_pred_mode_table);
  111. av_freep(&h->cbp_table);
  112. av_freep(&h->mvd_table[0]);
  113. av_freep(&h->mvd_table[1]);
  114. av_freep(&h->direct_table);
  115. av_freep(&h->non_zero_count);
  116. av_freep(&h->slice_table_base);
  117. h->slice_table = NULL;
  118. av_freep(&h->list_counts);
  119. av_freep(&h->mb2b_xy);
  120. av_freep(&h->mb2br_xy);
  121. av_buffer_pool_uninit(&h->qscale_table_pool);
  122. av_buffer_pool_uninit(&h->mb_type_pool);
  123. av_buffer_pool_uninit(&h->motion_val_pool);
  124. av_buffer_pool_uninit(&h->ref_index_pool);
  125. for (i = 0; i < h->nb_slice_ctx; i++) {
  126. H264SliceContext *sl = &h->slice_ctx[i];
  127. av_freep(&sl->dc_val_base);
  128. av_freep(&sl->er.mb_index2xy);
  129. av_freep(&sl->er.error_status_table);
  130. av_freep(&sl->er.er_temp_buffer);
  131. av_freep(&sl->bipred_scratchpad);
  132. av_freep(&sl->edge_emu_buffer);
  133. av_freep(&sl->top_borders[0]);
  134. av_freep(&sl->top_borders[1]);
  135. sl->bipred_scratchpad_allocated = 0;
  136. sl->edge_emu_buffer_allocated = 0;
  137. sl->top_borders_allocated[0] = 0;
  138. sl->top_borders_allocated[1] = 0;
  139. }
  140. }
  141. int ff_h264_alloc_tables(H264Context *h)
  142. {
  143. const int big_mb_num = h->mb_stride * (h->mb_height + 1);
  144. const int row_mb_num = h->mb_stride * 2 * h->nb_slice_ctx;
  145. int x, y;
  146. FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
  147. row_mb_num * 8 * sizeof(uint8_t), fail)
  148. h->slice_ctx[0].intra4x4_pred_mode = h->intra4x4_pred_mode;
  149. FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
  150. big_mb_num * 48 * sizeof(uint8_t), fail)
  151. FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
  152. (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
  153. FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
  154. big_mb_num * sizeof(uint16_t), fail)
  155. FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
  156. big_mb_num * sizeof(uint8_t), fail)
  157. FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
  158. 16 * row_mb_num * sizeof(uint8_t), fail);
  159. FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
  160. 16 * row_mb_num * sizeof(uint8_t), fail);
  161. h->slice_ctx[0].mvd_table[0] = h->mvd_table[0];
  162. h->slice_ctx[0].mvd_table[1] = h->mvd_table[1];
  163. FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
  164. 4 * big_mb_num * sizeof(uint8_t), fail);
  165. FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
  166. big_mb_num * sizeof(uint8_t), fail)
  167. memset(h->slice_table_base, -1,
  168. (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
  169. h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
  170. FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
  171. big_mb_num * sizeof(uint32_t), fail);
  172. FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
  173. big_mb_num * sizeof(uint32_t), fail);
  174. for (y = 0; y < h->mb_height; y++)
  175. for (x = 0; x < h->mb_width; x++) {
  176. const int mb_xy = x + y * h->mb_stride;
  177. const int b_xy = 4 * x + 4 * y * h->b_stride;
  178. h->mb2b_xy[mb_xy] = b_xy;
  179. h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
  180. }
  181. return 0;
  182. fail:
  183. ff_h264_free_tables(h);
  184. return AVERROR(ENOMEM);
  185. }
  186. /**
  187. * Init context
  188. * Allocate buffers which are not shared amongst multiple threads.
  189. */
  190. int ff_h264_slice_context_init(H264Context *h, H264SliceContext *sl)
  191. {
  192. ERContext *er = &sl->er;
  193. int mb_array_size = h->mb_height * h->mb_stride;
  194. int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
  195. int c_size = h->mb_stride * (h->mb_height + 1);
  196. int yc_size = y_size + 2 * c_size;
  197. int x, y, i;
  198. sl->ref_cache[0][scan8[5] + 1] =
  199. sl->ref_cache[0][scan8[7] + 1] =
  200. sl->ref_cache[0][scan8[13] + 1] =
  201. sl->ref_cache[1][scan8[5] + 1] =
  202. sl->ref_cache[1][scan8[7] + 1] =
  203. sl->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
  204. if (CONFIG_ERROR_RESILIENCE) {
  205. /* init ER */
  206. er->avctx = h->avctx;
  207. er->decode_mb = h264_er_decode_mb;
  208. er->opaque = h;
  209. er->quarter_sample = 1;
  210. er->mb_num = h->mb_num;
  211. er->mb_width = h->mb_width;
  212. er->mb_height = h->mb_height;
  213. er->mb_stride = h->mb_stride;
  214. er->b8_stride = h->mb_width * 2 + 1;
  215. // error resilience code looks cleaner with this
  216. FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy,
  217. (h->mb_num + 1) * sizeof(int), fail);
  218. for (y = 0; y < h->mb_height; y++)
  219. for (x = 0; x < h->mb_width; x++)
  220. er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
  221. er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
  222. h->mb_stride + h->mb_width;
  223. FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
  224. mb_array_size * sizeof(uint8_t), fail);
  225. FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer,
  226. h->mb_height * h->mb_stride, fail);
  227. FF_ALLOCZ_OR_GOTO(h->avctx, sl->dc_val_base,
  228. yc_size * sizeof(int16_t), fail);
  229. er->dc_val[0] = sl->dc_val_base + h->mb_width * 2 + 2;
  230. er->dc_val[1] = sl->dc_val_base + y_size + h->mb_stride + 1;
  231. er->dc_val[2] = er->dc_val[1] + c_size;
  232. for (i = 0; i < yc_size; i++)
  233. sl->dc_val_base[i] = 1024;
  234. }
  235. return 0;
  236. fail:
  237. return AVERROR(ENOMEM); // ff_h264_free_tables will clean up for us
  238. }
  239. static int h264_init_context(AVCodecContext *avctx, H264Context *h)
  240. {
  241. int i;
  242. h->avctx = avctx;
  243. h->picture_structure = PICT_FRAME;
  244. h->workaround_bugs = avctx->workaround_bugs;
  245. h->flags = avctx->flags;
  246. h->poc.prev_poc_msb = 1 << 16;
  247. h->recovery_frame = -1;
  248. h->frame_recovered = 0;
  249. h->next_outputed_poc = INT_MIN;
  250. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  251. h->last_pocs[i] = INT_MIN;
  252. ff_h264_sei_uninit(&h->sei);
  253. avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
  254. h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? avctx->thread_count : 1;
  255. h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));
  256. if (!h->slice_ctx) {
  257. h->nb_slice_ctx = 0;
  258. return AVERROR(ENOMEM);
  259. }
  260. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
  261. h->DPB[i].f = av_frame_alloc();
  262. if (!h->DPB[i].f)
  263. return AVERROR(ENOMEM);
  264. }
  265. h->cur_pic.f = av_frame_alloc();
  266. if (!h->cur_pic.f)
  267. return AVERROR(ENOMEM);
  268. h->output_frame = av_frame_alloc();
  269. if (!h->output_frame)
  270. return AVERROR(ENOMEM);
  271. for (i = 0; i < h->nb_slice_ctx; i++)
  272. h->slice_ctx[i].h264 = h;
  273. return 0;
  274. }
  275. static av_cold int h264_decode_end(AVCodecContext *avctx)
  276. {
  277. H264Context *h = avctx->priv_data;
  278. int i;
  279. ff_h264_free_tables(h);
  280. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
  281. ff_h264_unref_picture(h, &h->DPB[i]);
  282. av_frame_free(&h->DPB[i].f);
  283. }
  284. h->cur_pic_ptr = NULL;
  285. av_freep(&h->slice_ctx);
  286. h->nb_slice_ctx = 0;
  287. for (i = 0; i < MAX_SPS_COUNT; i++)
  288. av_buffer_unref(&h->ps.sps_list[i]);
  289. for (i = 0; i < MAX_PPS_COUNT; i++)
  290. av_buffer_unref(&h->ps.pps_list[i]);
  291. ff_h2645_packet_uninit(&h->pkt);
  292. ff_h264_unref_picture(h, &h->cur_pic);
  293. av_frame_free(&h->cur_pic.f);
  294. av_frame_free(&h->output_frame);
  295. return 0;
  296. }
  297. static AVOnce h264_vlc_init = AV_ONCE_INIT;
  298. av_cold int ff_h264_decode_init(AVCodecContext *avctx)
  299. {
  300. H264Context *h = avctx->priv_data;
  301. int ret;
  302. ret = h264_init_context(avctx, h);
  303. if (ret < 0)
  304. return ret;
  305. ret = ff_thread_once(&h264_vlc_init, ff_h264_decode_init_vlc);
  306. if (ret != 0) {
  307. av_log(avctx, AV_LOG_ERROR, "pthread_once has failed.");
  308. return AVERROR_UNKNOWN;
  309. }
  310. if (avctx->ticks_per_frame == 1)
  311. h->avctx->framerate.num *= 2;
  312. avctx->ticks_per_frame = 2;
  313. if (avctx->extradata_size > 0 && avctx->extradata) {
  314. ret = ff_h264_decode_extradata(avctx->extradata, avctx->extradata_size,
  315. &h->ps, &h->is_avc, &h->nal_length_size,
  316. avctx->err_recognition, avctx);
  317. if (ret < 0) {
  318. h264_decode_end(avctx);
  319. return ret;
  320. }
  321. }
  322. if (h->ps.sps && h->ps.sps->bitstream_restriction_flag &&
  323. h->avctx->has_b_frames < h->ps.sps->num_reorder_frames) {
  324. h->avctx->has_b_frames = h->ps.sps->num_reorder_frames;
  325. }
  326. avctx->internal->allocate_progress = 1;
  327. if (h->enable_er) {
  328. av_log(avctx, AV_LOG_WARNING,
  329. "Error resilience is enabled. It is unsafe and unsupported and may crash. "
  330. "Use it at your own risk\n");
  331. }
  332. return 0;
  333. }
  334. static int decode_init_thread_copy(AVCodecContext *avctx)
  335. {
  336. H264Context *h = avctx->priv_data;
  337. int ret;
  338. if (!avctx->internal->is_copy)
  339. return 0;
  340. memset(h, 0, sizeof(*h));
  341. ret = h264_init_context(avctx, h);
  342. if (ret < 0)
  343. return ret;
  344. h->context_initialized = 0;
  345. return 0;
  346. }
  347. /**
  348. * instantaneous decoder refresh.
  349. */
  350. static void idr(H264Context *h)
  351. {
  352. ff_h264_remove_all_refs(h);
  353. h->poc.prev_frame_num =
  354. h->poc.prev_frame_num_offset =
  355. h->poc.prev_poc_msb =
  356. h->poc.prev_poc_lsb = 0;
  357. }
  358. /* forget old pics after a seek */
  359. void ff_h264_flush_change(H264Context *h)
  360. {
  361. int i;
  362. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  363. h->last_pocs[i] = INT_MIN;
  364. h->next_outputed_poc = INT_MIN;
  365. h->prev_interlaced_frame = 1;
  366. idr(h);
  367. if (h->cur_pic_ptr)
  368. h->cur_pic_ptr->reference = 0;
  369. h->first_field = 0;
  370. ff_h264_sei_uninit(&h->sei);
  371. h->recovery_frame = -1;
  372. h->frame_recovered = 0;
  373. }
  374. /* forget old pics after a seek */
  375. static void flush_dpb(AVCodecContext *avctx)
  376. {
  377. H264Context *h = avctx->priv_data;
  378. int i;
  379. memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
  380. ff_h264_flush_change(h);
  381. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
  382. ff_h264_unref_picture(h, &h->DPB[i]);
  383. h->cur_pic_ptr = NULL;
  384. ff_h264_unref_picture(h, &h->cur_pic);
  385. h->mb_y = 0;
  386. ff_h264_free_tables(h);
  387. h->context_initialized = 0;
  388. }
  389. static int get_last_needed_nal(H264Context *h)
  390. {
  391. int nals_needed = 0;
  392. int i, ret;
  393. for (i = 0; i < h->pkt.nb_nals; i++) {
  394. H2645NAL *nal = &h->pkt.nals[i];
  395. GetBitContext gb;
  396. /* packets can sometimes contain multiple PPS/SPS,
  397. * e.g. two PAFF field pictures in one packet, or a demuxer
  398. * which splits NALs strangely if so, when frame threading we
  399. * can't start the next thread until we've read all of them */
  400. switch (nal->type) {
  401. case H264_NAL_SPS:
  402. case H264_NAL_PPS:
  403. nals_needed = i;
  404. break;
  405. case H264_NAL_DPA:
  406. case H264_NAL_IDR_SLICE:
  407. case H264_NAL_SLICE:
  408. ret = init_get_bits8(&gb, nal->data + 1, nal->size - 1);
  409. if (ret < 0) {
  410. av_log(h->avctx, AV_LOG_ERROR, "Invalid zero-sized VCL NAL unit\n");
  411. if (h->avctx->err_recognition & AV_EF_EXPLODE)
  412. return ret;
  413. break;
  414. }
  415. if (!get_ue_golomb(&gb))
  416. nals_needed = i;
  417. }
  418. }
  419. return nals_needed;
  420. }
  421. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size)
  422. {
  423. AVCodecContext *const avctx = h->avctx;
  424. int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
  425. int i, ret = 0;
  426. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)) {
  427. h->current_slice = 0;
  428. if (!h->first_field)
  429. h->cur_pic_ptr = NULL;
  430. ff_h264_sei_uninit(&h->sei);
  431. }
  432. ret = ff_h2645_packet_split(&h->pkt, buf, buf_size, avctx, h->is_avc,
  433. h->nal_length_size, avctx->codec_id);
  434. if (ret < 0) {
  435. av_log(avctx, AV_LOG_ERROR,
  436. "Error splitting the input into NAL units.\n");
  437. /* There are samples in the wild with mp4-style extradata, but Annex B
  438. * data in the packets. If we fail parsing the packet as mp4, try it again
  439. * as Annex B. */
  440. if (h->is_avc && !(avctx->err_recognition & AV_EF_EXPLODE)) {
  441. int err = ff_h2645_packet_split(&h->pkt, buf, buf_size, avctx, 0, 0,
  442. avctx->codec_id);
  443. if (err >= 0) {
  444. av_log(avctx, AV_LOG_WARNING,
  445. "The stream seems to contain AVCC extradata with Annex B "
  446. "formatted data, which is invalid.");
  447. h->is_avc = 0;
  448. ret = 0;
  449. }
  450. }
  451. if (ret < 0)
  452. return ret;
  453. }
  454. if (avctx->active_thread_type & FF_THREAD_FRAME)
  455. nals_needed = get_last_needed_nal(h);
  456. for (i = 0; i < h->pkt.nb_nals; i++) {
  457. H2645NAL *nal = &h->pkt.nals[i];
  458. int max_slice_ctx, err;
  459. if (avctx->skip_frame >= AVDISCARD_NONREF &&
  460. nal->ref_idc == 0 && nal->type != H264_NAL_SEI)
  461. continue;
  462. // FIXME these should stop being context-global variables
  463. h->nal_ref_idc = nal->ref_idc;
  464. h->nal_unit_type = nal->type;
  465. err = 0;
  466. switch (nal->type) {
  467. case H264_NAL_IDR_SLICE:
  468. idr(h); // FIXME ensure we don't lose some frames if there is reordering
  469. case H264_NAL_SLICE:
  470. if ((err = ff_h264_queue_decode_slice(h, nal)))
  471. break;
  472. if (avctx->active_thread_type & FF_THREAD_FRAME && !h->avctx->hwaccel &&
  473. i >= nals_needed && !h->setup_finished && h->cur_pic_ptr) {
  474. ff_thread_finish_setup(avctx);
  475. h->setup_finished = 1;
  476. }
  477. max_slice_ctx = avctx->hwaccel ? 1 : h->nb_slice_ctx;
  478. if (h->nb_slice_ctx_queued == max_slice_ctx) {
  479. if (avctx->hwaccel) {
  480. ret = avctx->hwaccel->decode_slice(avctx, nal->raw_data, nal->raw_size);
  481. h->nb_slice_ctx_queued = 0;
  482. } else
  483. ret = ff_h264_execute_decode_slices(h);
  484. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  485. goto end;
  486. }
  487. break;
  488. case H264_NAL_DPA:
  489. case H264_NAL_DPB:
  490. case H264_NAL_DPC:
  491. avpriv_request_sample(avctx, "data partitioning");
  492. ret = AVERROR(ENOSYS);
  493. goto end;
  494. break;
  495. case H264_NAL_SEI:
  496. ret = ff_h264_sei_decode(&h->sei, &nal->gb, &h->ps, avctx);
  497. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  498. goto end;
  499. break;
  500. case H264_NAL_SPS:
  501. ret = ff_h264_decode_seq_parameter_set(&nal->gb, avctx, &h->ps);
  502. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  503. goto end;
  504. break;
  505. case H264_NAL_PPS:
  506. ret = ff_h264_decode_picture_parameter_set(&nal->gb, avctx, &h->ps,
  507. nal->size_bits);
  508. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  509. goto end;
  510. break;
  511. case H264_NAL_AUD:
  512. case H264_NAL_END_SEQUENCE:
  513. case H264_NAL_END_STREAM:
  514. case H264_NAL_FILLER_DATA:
  515. case H264_NAL_SPS_EXT:
  516. case H264_NAL_AUXILIARY_SLICE:
  517. break;
  518. default:
  519. av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
  520. nal->type, nal->size_bits);
  521. }
  522. if (err < 0) {
  523. av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
  524. }
  525. }
  526. ret = ff_h264_execute_decode_slices(h);
  527. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  528. goto end;
  529. ret = 0;
  530. end:
  531. /* clean up */
  532. if (h->cur_pic_ptr && !h->droppable) {
  533. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
  534. h->picture_structure == PICT_BOTTOM_FIELD);
  535. }
  536. return (ret < 0) ? ret : buf_size;
  537. }
  538. /**
  539. * Return the number of bytes consumed for building the current frame.
  540. */
  541. static int get_consumed_bytes(int pos, int buf_size)
  542. {
  543. if (pos == 0)
  544. pos = 1; // avoid infinite loops (I doubt that is needed but...)
  545. if (pos + 10 > buf_size)
  546. pos = buf_size; // oops ;)
  547. return pos;
  548. }
  549. static int output_frame(H264Context *h, AVFrame *dst, AVFrame *src)
  550. {
  551. int i;
  552. int ret = av_frame_ref(dst, src);
  553. if (ret < 0)
  554. return ret;
  555. if (!h->ps.sps || !h->ps.sps->crop)
  556. return 0;
  557. for (i = 0; i < 3; i++) {
  558. int hshift = (i > 0) ? h->chroma_x_shift : 0;
  559. int vshift = (i > 0) ? h->chroma_y_shift : 0;
  560. int off = ((h->ps.sps->crop_left >> hshift) << h->pixel_shift) +
  561. (h->ps.sps->crop_top >> vshift) * dst->linesize[i];
  562. dst->data[i] += off;
  563. }
  564. return 0;
  565. }
  566. static int h264_decode_frame(AVCodecContext *avctx, void *data,
  567. int *got_frame, AVPacket *avpkt)
  568. {
  569. const uint8_t *buf = avpkt->data;
  570. int buf_size = avpkt->size;
  571. H264Context *h = avctx->priv_data;
  572. AVFrame *pict = data;
  573. int buf_index = 0;
  574. int ret;
  575. const uint8_t *new_extradata;
  576. int new_extradata_size;
  577. h->flags = avctx->flags;
  578. h->setup_finished = 0;
  579. h->nb_slice_ctx_queued = 0;
  580. /* end of stream, output what is still in the buffers */
  581. out:
  582. if (buf_size == 0) {
  583. H264Picture *out;
  584. int i, out_idx;
  585. h->cur_pic_ptr = NULL;
  586. // FIXME factorize this with the output code below
  587. out = h->delayed_pic[0];
  588. out_idx = 0;
  589. for (i = 1;
  590. h->delayed_pic[i] &&
  591. !h->delayed_pic[i]->f->key_frame &&
  592. !h->delayed_pic[i]->mmco_reset;
  593. i++)
  594. if (h->delayed_pic[i]->poc < out->poc) {
  595. out = h->delayed_pic[i];
  596. out_idx = i;
  597. }
  598. for (i = out_idx; h->delayed_pic[i]; i++)
  599. h->delayed_pic[i] = h->delayed_pic[i + 1];
  600. if (out) {
  601. ret = output_frame(h, pict, out->f);
  602. if (ret < 0)
  603. return ret;
  604. *got_frame = 1;
  605. }
  606. return buf_index;
  607. }
  608. new_extradata_size = 0;
  609. new_extradata = av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA,
  610. &new_extradata_size);
  611. if (new_extradata_size > 0 && new_extradata) {
  612. ret = ff_h264_decode_extradata(new_extradata, new_extradata_size,
  613. &h->ps, &h->is_avc, &h->nal_length_size,
  614. avctx->err_recognition, avctx);
  615. if (ret < 0)
  616. return ret;
  617. }
  618. buf_index = decode_nal_units(h, buf, buf_size);
  619. if (buf_index < 0)
  620. return AVERROR_INVALIDDATA;
  621. if (!h->cur_pic_ptr && h->nal_unit_type == H264_NAL_END_SEQUENCE) {
  622. buf_size = 0;
  623. goto out;
  624. }
  625. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
  626. if (avctx->skip_frame >= AVDISCARD_NONREF)
  627. return 0;
  628. av_log(avctx, AV_LOG_ERROR, "no frame!\n");
  629. return AVERROR_INVALIDDATA;
  630. }
  631. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) ||
  632. (h->mb_y >= h->mb_height && h->mb_height)) {
  633. ff_h264_field_end(h, &h->slice_ctx[0], 0);
  634. *got_frame = 0;
  635. if (h->output_frame->buf[0]) {
  636. ret = output_frame(h, pict, h->output_frame) ;
  637. av_frame_unref(h->output_frame);
  638. if (ret < 0)
  639. return ret;
  640. *got_frame = 1;
  641. }
  642. }
  643. assert(pict->buf[0] || !*got_frame);
  644. return get_consumed_bytes(buf_index, buf_size);
  645. }
  646. #define OFFSET(x) offsetof(H264Context, x)
  647. #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  648. static const AVOption h264_options[] = {
  649. { "enable_er", "Enable error resilience on damaged frames (unsafe)", OFFSET(enable_er), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD },
  650. { NULL },
  651. };
  652. static const AVClass h264_class = {
  653. .class_name = "h264",
  654. .item_name = av_default_item_name,
  655. .option = h264_options,
  656. .version = LIBAVUTIL_VERSION_INT,
  657. };
  658. AVCodec ff_h264_decoder = {
  659. .name = "h264",
  660. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
  661. .type = AVMEDIA_TYPE_VIDEO,
  662. .id = AV_CODEC_ID_H264,
  663. .priv_data_size = sizeof(H264Context),
  664. .init = ff_h264_decode_init,
  665. .close = h264_decode_end,
  666. .decode = h264_decode_frame,
  667. .capabilities = /*AV_CODEC_CAP_DRAW_HORIZ_BAND |*/ AV_CODEC_CAP_DR1 |
  668. AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS |
  669. AV_CODEC_CAP_FRAME_THREADS,
  670. .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
  671. .flush = flush_dpb,
  672. .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
  673. .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
  674. .profiles = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
  675. .priv_class = &h264_class,
  676. };