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.

957 lines
30KB

  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. for (i = 0; i < h->nb_slice_ctx; i++)
  269. h->slice_ctx[i].h264 = h;
  270. return 0;
  271. }
  272. static av_cold int h264_decode_end(AVCodecContext *avctx)
  273. {
  274. H264Context *h = avctx->priv_data;
  275. int i;
  276. ff_h264_free_tables(h);
  277. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
  278. ff_h264_unref_picture(h, &h->DPB[i]);
  279. av_frame_free(&h->DPB[i].f);
  280. }
  281. h->cur_pic_ptr = NULL;
  282. av_freep(&h->slice_ctx);
  283. h->nb_slice_ctx = 0;
  284. for (i = 0; i < MAX_SPS_COUNT; i++)
  285. av_buffer_unref(&h->ps.sps_list[i]);
  286. for (i = 0; i < MAX_PPS_COUNT; i++)
  287. av_buffer_unref(&h->ps.pps_list[i]);
  288. ff_h2645_packet_uninit(&h->pkt);
  289. ff_h264_unref_picture(h, &h->cur_pic);
  290. av_frame_free(&h->cur_pic.f);
  291. return 0;
  292. }
  293. static AVOnce h264_vlc_init = AV_ONCE_INIT;
  294. av_cold int ff_h264_decode_init(AVCodecContext *avctx)
  295. {
  296. H264Context *h = avctx->priv_data;
  297. int ret;
  298. ret = h264_init_context(avctx, h);
  299. if (ret < 0)
  300. return ret;
  301. ret = ff_thread_once(&h264_vlc_init, ff_h264_decode_init_vlc);
  302. if (ret != 0) {
  303. av_log(avctx, AV_LOG_ERROR, "pthread_once has failed.");
  304. return AVERROR_UNKNOWN;
  305. }
  306. if (avctx->ticks_per_frame == 1)
  307. h->avctx->framerate.num *= 2;
  308. avctx->ticks_per_frame = 2;
  309. if (avctx->extradata_size > 0 && avctx->extradata) {
  310. ret = ff_h264_decode_extradata(avctx->extradata, avctx->extradata_size,
  311. &h->ps, &h->is_avc, &h->nal_length_size,
  312. avctx->err_recognition, avctx);
  313. if (ret < 0) {
  314. h264_decode_end(avctx);
  315. return ret;
  316. }
  317. }
  318. if (h->ps.sps && h->ps.sps->bitstream_restriction_flag &&
  319. h->avctx->has_b_frames < h->ps.sps->num_reorder_frames) {
  320. h->avctx->has_b_frames = h->ps.sps->num_reorder_frames;
  321. }
  322. avctx->internal->allocate_progress = 1;
  323. if (h->enable_er) {
  324. av_log(avctx, AV_LOG_WARNING,
  325. "Error resilience is enabled. It is unsafe and unsupported and may crash. "
  326. "Use it at your own risk\n");
  327. }
  328. return 0;
  329. }
  330. static int decode_init_thread_copy(AVCodecContext *avctx)
  331. {
  332. H264Context *h = avctx->priv_data;
  333. int ret;
  334. if (!avctx->internal->is_copy)
  335. return 0;
  336. memset(h, 0, sizeof(*h));
  337. ret = h264_init_context(avctx, h);
  338. if (ret < 0)
  339. return ret;
  340. h->context_initialized = 0;
  341. return 0;
  342. }
  343. /**
  344. * Run setup operations that must be run after slice header decoding.
  345. * This includes finding the next displayed frame.
  346. *
  347. * @param h h264 master context
  348. * @param setup_finished enough NALs have been read that we can call
  349. * ff_thread_finish_setup()
  350. */
  351. static void decode_postinit(H264Context *h, int setup_finished)
  352. {
  353. const SPS *sps = h->ps.sps;
  354. H264Picture *out = h->cur_pic_ptr;
  355. H264Picture *cur = h->cur_pic_ptr;
  356. int i, pics, out_of_order, out_idx;
  357. int invalid = 0, cnt = 0;
  358. if (h->next_output_pic)
  359. return;
  360. if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
  361. /* FIXME: if we have two PAFF fields in one packet, we can't start
  362. * the next thread here. If we have one field per packet, we can.
  363. * The check in decode_nal_units() is not good enough to find this
  364. * yet, so we assume the worst for now. */
  365. // if (setup_finished)
  366. // ff_thread_finish_setup(h->avctx);
  367. return;
  368. }
  369. // FIXME do something with unavailable reference frames
  370. /* Sort B-frames into display order */
  371. if (sps->bitstream_restriction_flag ||
  372. h->avctx->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
  373. h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, sps->num_reorder_frames);
  374. }
  375. pics = 0;
  376. while (h->delayed_pic[pics])
  377. pics++;
  378. assert(pics <= MAX_DELAYED_PIC_COUNT);
  379. h->delayed_pic[pics++] = cur;
  380. if (cur->reference == 0)
  381. cur->reference = DELAYED_PIC_REF;
  382. /* Frame reordering. This code takes pictures from coding order and sorts
  383. * them by their incremental POC value into display order. It supports POC
  384. * gaps, MMCO reset codes and random resets.
  385. * A "display group" can start either with a IDR frame (f.key_frame = 1),
  386. * and/or can be closed down with a MMCO reset code. In sequences where
  387. * there is no delay, we can't detect that (since the frame was already
  388. * output to the user), so we also set h->mmco_reset to detect the MMCO
  389. * reset code.
  390. * FIXME: if we detect insufficient delays (as per h->avctx->has_b_frames),
  391. * we increase the delay between input and output. All frames affected by
  392. * the lag (e.g. those that should have been output before another frame
  393. * that we already returned to the user) will be dropped. This is a bug
  394. * that we will fix later. */
  395. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++) {
  396. cnt += out->poc < h->last_pocs[i];
  397. invalid += out->poc == INT_MIN;
  398. }
  399. if (!h->mmco_reset && !cur->f->key_frame &&
  400. cnt + invalid == MAX_DELAYED_PIC_COUNT && cnt > 0) {
  401. h->mmco_reset = 2;
  402. if (pics > 1)
  403. h->delayed_pic[pics - 2]->mmco_reset = 2;
  404. }
  405. if (h->mmco_reset || cur->f->key_frame) {
  406. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  407. h->last_pocs[i] = INT_MIN;
  408. cnt = 0;
  409. invalid = MAX_DELAYED_PIC_COUNT;
  410. }
  411. out = h->delayed_pic[0];
  412. out_idx = 0;
  413. for (i = 1; i < MAX_DELAYED_PIC_COUNT &&
  414. h->delayed_pic[i] &&
  415. !h->delayed_pic[i - 1]->mmco_reset &&
  416. !h->delayed_pic[i]->f->key_frame;
  417. i++)
  418. if (h->delayed_pic[i]->poc < out->poc) {
  419. out = h->delayed_pic[i];
  420. out_idx = i;
  421. }
  422. if (h->avctx->has_b_frames == 0 &&
  423. (h->delayed_pic[0]->f->key_frame || h->mmco_reset))
  424. h->next_outputed_poc = INT_MIN;
  425. out_of_order = !out->f->key_frame && !h->mmco_reset &&
  426. (out->poc < h->next_outputed_poc);
  427. if (sps->bitstream_restriction_flag &&
  428. h->avctx->has_b_frames >= sps->num_reorder_frames) {
  429. } else if (out_of_order && pics - 1 == h->avctx->has_b_frames &&
  430. h->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT) {
  431. if (invalid + cnt < MAX_DELAYED_PIC_COUNT) {
  432. h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, cnt);
  433. }
  434. } else if (!h->avctx->has_b_frames &&
  435. ((h->next_outputed_poc != INT_MIN &&
  436. out->poc > h->next_outputed_poc + 2) ||
  437. cur->f->pict_type == AV_PICTURE_TYPE_B)) {
  438. h->avctx->has_b_frames++;
  439. }
  440. if (pics > h->avctx->has_b_frames) {
  441. out->reference &= ~DELAYED_PIC_REF;
  442. for (i = out_idx; h->delayed_pic[i]; i++)
  443. h->delayed_pic[i] = h->delayed_pic[i + 1];
  444. }
  445. memmove(h->last_pocs, &h->last_pocs[1],
  446. sizeof(*h->last_pocs) * (MAX_DELAYED_PIC_COUNT - 1));
  447. h->last_pocs[MAX_DELAYED_PIC_COUNT - 1] = cur->poc;
  448. if (!out_of_order && pics > h->avctx->has_b_frames) {
  449. h->next_output_pic = out;
  450. if (out->mmco_reset) {
  451. if (out_idx > 0) {
  452. h->next_outputed_poc = out->poc;
  453. h->delayed_pic[out_idx - 1]->mmco_reset = out->mmco_reset;
  454. } else {
  455. h->next_outputed_poc = INT_MIN;
  456. }
  457. } else {
  458. if (out_idx == 0 && pics > 1 && h->delayed_pic[0]->f->key_frame) {
  459. h->next_outputed_poc = INT_MIN;
  460. } else {
  461. h->next_outputed_poc = out->poc;
  462. }
  463. }
  464. h->mmco_reset = 0;
  465. } else {
  466. av_log(h->avctx, AV_LOG_DEBUG, "no picture\n");
  467. }
  468. if (h->next_output_pic) {
  469. if (h->next_output_pic->recovered) {
  470. // We have reached an recovery point and all frames after it in
  471. // display order are "recovered".
  472. h->frame_recovered |= FRAME_RECOVERED_SEI;
  473. }
  474. h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
  475. }
  476. if (setup_finished && !h->avctx->hwaccel) {
  477. ff_thread_finish_setup(h->avctx);
  478. if (h->avctx->active_thread_type & FF_THREAD_FRAME)
  479. h->setup_finished = 1;
  480. }
  481. }
  482. /**
  483. * instantaneous decoder refresh.
  484. */
  485. static void idr(H264Context *h)
  486. {
  487. ff_h264_remove_all_refs(h);
  488. h->poc.prev_frame_num =
  489. h->poc.prev_frame_num_offset =
  490. h->poc.prev_poc_msb =
  491. h->poc.prev_poc_lsb = 0;
  492. }
  493. /* forget old pics after a seek */
  494. void ff_h264_flush_change(H264Context *h)
  495. {
  496. int i;
  497. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  498. h->last_pocs[i] = INT_MIN;
  499. h->next_outputed_poc = INT_MIN;
  500. h->prev_interlaced_frame = 1;
  501. idr(h);
  502. if (h->cur_pic_ptr)
  503. h->cur_pic_ptr->reference = 0;
  504. h->first_field = 0;
  505. ff_h264_sei_uninit(&h->sei);
  506. h->recovery_frame = -1;
  507. h->frame_recovered = 0;
  508. }
  509. /* forget old pics after a seek */
  510. static void flush_dpb(AVCodecContext *avctx)
  511. {
  512. H264Context *h = avctx->priv_data;
  513. int i;
  514. memset(h->delayed_pic, 0, sizeof(h->delayed_pic));
  515. ff_h264_flush_change(h);
  516. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
  517. ff_h264_unref_picture(h, &h->DPB[i]);
  518. h->cur_pic_ptr = NULL;
  519. ff_h264_unref_picture(h, &h->cur_pic);
  520. h->mb_y = 0;
  521. ff_h264_free_tables(h);
  522. h->context_initialized = 0;
  523. }
  524. static int get_last_needed_nal(H264Context *h)
  525. {
  526. int nals_needed = 0;
  527. int i;
  528. for (i = 0; i < h->pkt.nb_nals; i++) {
  529. H2645NAL *nal = &h->pkt.nals[i];
  530. GetBitContext gb;
  531. /* packets can sometimes contain multiple PPS/SPS,
  532. * e.g. two PAFF field pictures in one packet, or a demuxer
  533. * which splits NALs strangely if so, when frame threading we
  534. * can't start the next thread until we've read all of them */
  535. switch (nal->type) {
  536. case H264_NAL_SPS:
  537. case H264_NAL_PPS:
  538. nals_needed = i;
  539. break;
  540. case H264_NAL_DPA:
  541. case H264_NAL_IDR_SLICE:
  542. case H264_NAL_SLICE:
  543. init_get_bits(&gb, nal->data + 1, (nal->size - 1) * 8);
  544. if (!get_ue_golomb(&gb))
  545. nals_needed = i;
  546. }
  547. }
  548. return nals_needed;
  549. }
  550. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size)
  551. {
  552. AVCodecContext *const avctx = h->avctx;
  553. unsigned context_count = 0;
  554. int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
  555. int i, ret = 0;
  556. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)) {
  557. h->current_slice = 0;
  558. if (!h->first_field)
  559. h->cur_pic_ptr = NULL;
  560. ff_h264_sei_uninit(&h->sei);
  561. }
  562. ret = ff_h2645_packet_split(&h->pkt, buf, buf_size, avctx, h->is_avc,
  563. h->nal_length_size, avctx->codec_id);
  564. if (ret < 0) {
  565. av_log(avctx, AV_LOG_ERROR,
  566. "Error splitting the input into NAL units.\n");
  567. return ret;
  568. }
  569. if (avctx->active_thread_type & FF_THREAD_FRAME)
  570. nals_needed = get_last_needed_nal(h);
  571. for (i = 0; i < h->pkt.nb_nals; i++) {
  572. H2645NAL *nal = &h->pkt.nals[i];
  573. H264SliceContext *sl = &h->slice_ctx[context_count];
  574. int err;
  575. if (avctx->skip_frame >= AVDISCARD_NONREF &&
  576. nal->ref_idc == 0 && nal->type != H264_NAL_SEI)
  577. continue;
  578. // FIXME these should stop being context-global variables
  579. h->nal_ref_idc = nal->ref_idc;
  580. h->nal_unit_type = nal->type;
  581. err = 0;
  582. switch (nal->type) {
  583. case H264_NAL_IDR_SLICE:
  584. idr(h); // FIXME ensure we don't lose some frames if there is reordering
  585. case H264_NAL_SLICE:
  586. sl->gb = nal->gb;
  587. if ((err = ff_h264_decode_slice_header(h, sl, nal)))
  588. break;
  589. if (sl->redundant_pic_count > 0)
  590. break;
  591. if (h->current_slice == 1) {
  592. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS))
  593. decode_postinit(h, i >= nals_needed);
  594. }
  595. if ((avctx->skip_frame < AVDISCARD_NONREF || nal->ref_idc) &&
  596. (avctx->skip_frame < AVDISCARD_BIDIR ||
  597. sl->slice_type_nos != AV_PICTURE_TYPE_B) &&
  598. (avctx->skip_frame < AVDISCARD_NONKEY ||
  599. h->cur_pic_ptr->f->key_frame) &&
  600. avctx->skip_frame < AVDISCARD_ALL) {
  601. if (avctx->hwaccel) {
  602. ret = avctx->hwaccel->decode_slice(avctx, nal->raw_data, nal->raw_size);
  603. if (ret < 0)
  604. return ret;
  605. } else
  606. context_count++;
  607. }
  608. break;
  609. case H264_NAL_DPA:
  610. case H264_NAL_DPB:
  611. case H264_NAL_DPC:
  612. avpriv_request_sample(avctx, "data partitioning");
  613. ret = AVERROR(ENOSYS);
  614. goto end;
  615. break;
  616. case H264_NAL_SEI:
  617. ret = ff_h264_sei_decode(&h->sei, &nal->gb, &h->ps, avctx);
  618. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  619. goto end;
  620. break;
  621. case H264_NAL_SPS:
  622. ret = ff_h264_decode_seq_parameter_set(&nal->gb, avctx, &h->ps);
  623. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  624. goto end;
  625. break;
  626. case H264_NAL_PPS:
  627. ret = ff_h264_decode_picture_parameter_set(&nal->gb, avctx, &h->ps,
  628. nal->size_bits);
  629. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  630. goto end;
  631. break;
  632. case H264_NAL_AUD:
  633. case H264_NAL_END_SEQUENCE:
  634. case H264_NAL_END_STREAM:
  635. case H264_NAL_FILLER_DATA:
  636. case H264_NAL_SPS_EXT:
  637. case H264_NAL_AUXILIARY_SLICE:
  638. break;
  639. default:
  640. av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
  641. nal->type, nal->size_bits);
  642. }
  643. if (context_count == h->nb_slice_ctx) {
  644. ret = ff_h264_execute_decode_slices(h, context_count);
  645. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  646. goto end;
  647. context_count = 0;
  648. }
  649. if (err < 0) {
  650. av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
  651. sl->ref_count[0] = sl->ref_count[1] = sl->list_count = 0;
  652. }
  653. }
  654. if (context_count) {
  655. ret = ff_h264_execute_decode_slices(h, context_count);
  656. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  657. goto end;
  658. }
  659. ret = 0;
  660. end:
  661. /* clean up */
  662. if (h->cur_pic_ptr && !h->droppable) {
  663. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
  664. h->picture_structure == PICT_BOTTOM_FIELD);
  665. }
  666. return (ret < 0) ? ret : buf_size;
  667. }
  668. /**
  669. * Return the number of bytes consumed for building the current frame.
  670. */
  671. static int get_consumed_bytes(int pos, int buf_size)
  672. {
  673. if (pos == 0)
  674. pos = 1; // avoid infinite loops (I doubt that is needed but...)
  675. if (pos + 10 > buf_size)
  676. pos = buf_size; // oops ;)
  677. return pos;
  678. }
  679. static int output_frame(H264Context *h, AVFrame *dst, AVFrame *src)
  680. {
  681. int i;
  682. int ret = av_frame_ref(dst, src);
  683. if (ret < 0)
  684. return ret;
  685. if (!h->ps.sps || !h->ps.sps->crop)
  686. return 0;
  687. for (i = 0; i < 3; i++) {
  688. int hshift = (i > 0) ? h->chroma_x_shift : 0;
  689. int vshift = (i > 0) ? h->chroma_y_shift : 0;
  690. int off = ((h->ps.sps->crop_left >> hshift) << h->pixel_shift) +
  691. (h->ps.sps->crop_top >> vshift) * dst->linesize[i];
  692. dst->data[i] += off;
  693. }
  694. return 0;
  695. }
  696. static int h264_decode_frame(AVCodecContext *avctx, void *data,
  697. int *got_frame, AVPacket *avpkt)
  698. {
  699. const uint8_t *buf = avpkt->data;
  700. int buf_size = avpkt->size;
  701. H264Context *h = avctx->priv_data;
  702. AVFrame *pict = data;
  703. int buf_index = 0;
  704. int ret;
  705. const uint8_t *new_extradata;
  706. int new_extradata_size;
  707. h->flags = avctx->flags;
  708. h->setup_finished = 0;
  709. /* end of stream, output what is still in the buffers */
  710. out:
  711. if (buf_size == 0) {
  712. H264Picture *out;
  713. int i, out_idx;
  714. h->cur_pic_ptr = NULL;
  715. // FIXME factorize this with the output code below
  716. out = h->delayed_pic[0];
  717. out_idx = 0;
  718. for (i = 1;
  719. h->delayed_pic[i] &&
  720. !h->delayed_pic[i]->f->key_frame &&
  721. !h->delayed_pic[i]->mmco_reset;
  722. i++)
  723. if (h->delayed_pic[i]->poc < out->poc) {
  724. out = h->delayed_pic[i];
  725. out_idx = i;
  726. }
  727. for (i = out_idx; h->delayed_pic[i]; i++)
  728. h->delayed_pic[i] = h->delayed_pic[i + 1];
  729. if (out) {
  730. ret = output_frame(h, pict, out->f);
  731. if (ret < 0)
  732. return ret;
  733. *got_frame = 1;
  734. }
  735. return buf_index;
  736. }
  737. new_extradata_size = 0;
  738. new_extradata = av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA,
  739. &new_extradata_size);
  740. if (new_extradata_size > 0 && new_extradata) {
  741. ret = ff_h264_decode_extradata(new_extradata, new_extradata_size,
  742. &h->ps, &h->is_avc, &h->nal_length_size,
  743. avctx->err_recognition, avctx);
  744. if (ret < 0)
  745. return ret;
  746. }
  747. buf_index = decode_nal_units(h, buf, buf_size);
  748. if (buf_index < 0)
  749. return AVERROR_INVALIDDATA;
  750. if (!h->cur_pic_ptr && h->nal_unit_type == H264_NAL_END_SEQUENCE) {
  751. buf_size = 0;
  752. goto out;
  753. }
  754. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
  755. if (avctx->skip_frame >= AVDISCARD_NONREF)
  756. return 0;
  757. av_log(avctx, AV_LOG_ERROR, "no frame!\n");
  758. return AVERROR_INVALIDDATA;
  759. }
  760. if (!(avctx->flags2 & AV_CODEC_FLAG2_CHUNKS) ||
  761. (h->mb_y >= h->mb_height && h->mb_height)) {
  762. if (avctx->flags2 & AV_CODEC_FLAG2_CHUNKS)
  763. decode_postinit(h, 1);
  764. ff_h264_field_end(h, &h->slice_ctx[0], 0);
  765. *got_frame = 0;
  766. if (h->next_output_pic && ((avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT) ||
  767. h->next_output_pic->recovered)) {
  768. if (!h->next_output_pic->recovered)
  769. h->next_output_pic->f->flags |= AV_FRAME_FLAG_CORRUPT;
  770. ret = output_frame(h, pict, h->next_output_pic->f);
  771. if (ret < 0)
  772. return ret;
  773. *got_frame = 1;
  774. }
  775. }
  776. assert(pict->buf[0] || !*got_frame);
  777. return get_consumed_bytes(buf_index, buf_size);
  778. }
  779. #define OFFSET(x) offsetof(H264Context, x)
  780. #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  781. static const AVOption h264_options[] = {
  782. { "enable_er", "Enable error resilience on damaged frames (unsafe)", OFFSET(enable_er), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD },
  783. { NULL },
  784. };
  785. static const AVClass h264_class = {
  786. .class_name = "h264",
  787. .item_name = av_default_item_name,
  788. .option = h264_options,
  789. .version = LIBAVUTIL_VERSION_INT,
  790. };
  791. AVCodec ff_h264_decoder = {
  792. .name = "h264",
  793. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
  794. .type = AVMEDIA_TYPE_VIDEO,
  795. .id = AV_CODEC_ID_H264,
  796. .priv_data_size = sizeof(H264Context),
  797. .init = ff_h264_decode_init,
  798. .close = h264_decode_end,
  799. .decode = h264_decode_frame,
  800. .capabilities = /*AV_CODEC_CAP_DRAW_HORIZ_BAND |*/ AV_CODEC_CAP_DR1 |
  801. AV_CODEC_CAP_DELAY | AV_CODEC_CAP_SLICE_THREADS |
  802. AV_CODEC_CAP_FRAME_THREADS,
  803. .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
  804. .flush = flush_dpb,
  805. .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
  806. .update_thread_context = ONLY_IF_THREADS_ENABLED(ff_h264_update_thread_context),
  807. .profiles = NULL_IF_CONFIG_SMALL(ff_h264_profiles),
  808. .priv_class = &h264_class,
  809. };