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.

2875 lines
108KB

  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. #include "libavutil/avassert.h"
  27. #include "libavutil/display.h"
  28. #include "libavutil/imgutils.h"
  29. #include "libavutil/stereo3d.h"
  30. #include "internal.h"
  31. #include "cabac.h"
  32. #include "cabac_functions.h"
  33. #include "error_resilience.h"
  34. #include "avcodec.h"
  35. #include "h264.h"
  36. #include "h264dec.h"
  37. #include "h264data.h"
  38. #include "h264chroma.h"
  39. #include "h264_mvpred.h"
  40. #include "h264_ps.h"
  41. #include "golomb.h"
  42. #include "mathops.h"
  43. #include "mpegutils.h"
  44. #include "mpegvideo.h"
  45. #include "rectangle.h"
  46. #include "thread.h"
  47. static const uint8_t field_scan[16+1] = {
  48. 0 + 0 * 4, 0 + 1 * 4, 1 + 0 * 4, 0 + 2 * 4,
  49. 0 + 3 * 4, 1 + 1 * 4, 1 + 2 * 4, 1 + 3 * 4,
  50. 2 + 0 * 4, 2 + 1 * 4, 2 + 2 * 4, 2 + 3 * 4,
  51. 3 + 0 * 4, 3 + 1 * 4, 3 + 2 * 4, 3 + 3 * 4,
  52. };
  53. static const uint8_t field_scan8x8[64+1] = {
  54. 0 + 0 * 8, 0 + 1 * 8, 0 + 2 * 8, 1 + 0 * 8,
  55. 1 + 1 * 8, 0 + 3 * 8, 0 + 4 * 8, 1 + 2 * 8,
  56. 2 + 0 * 8, 1 + 3 * 8, 0 + 5 * 8, 0 + 6 * 8,
  57. 0 + 7 * 8, 1 + 4 * 8, 2 + 1 * 8, 3 + 0 * 8,
  58. 2 + 2 * 8, 1 + 5 * 8, 1 + 6 * 8, 1 + 7 * 8,
  59. 2 + 3 * 8, 3 + 1 * 8, 4 + 0 * 8, 3 + 2 * 8,
  60. 2 + 4 * 8, 2 + 5 * 8, 2 + 6 * 8, 2 + 7 * 8,
  61. 3 + 3 * 8, 4 + 1 * 8, 5 + 0 * 8, 4 + 2 * 8,
  62. 3 + 4 * 8, 3 + 5 * 8, 3 + 6 * 8, 3 + 7 * 8,
  63. 4 + 3 * 8, 5 + 1 * 8, 6 + 0 * 8, 5 + 2 * 8,
  64. 4 + 4 * 8, 4 + 5 * 8, 4 + 6 * 8, 4 + 7 * 8,
  65. 5 + 3 * 8, 6 + 1 * 8, 6 + 2 * 8, 5 + 4 * 8,
  66. 5 + 5 * 8, 5 + 6 * 8, 5 + 7 * 8, 6 + 3 * 8,
  67. 7 + 0 * 8, 7 + 1 * 8, 6 + 4 * 8, 6 + 5 * 8,
  68. 6 + 6 * 8, 6 + 7 * 8, 7 + 2 * 8, 7 + 3 * 8,
  69. 7 + 4 * 8, 7 + 5 * 8, 7 + 6 * 8, 7 + 7 * 8,
  70. };
  71. static const uint8_t field_scan8x8_cavlc[64+1] = {
  72. 0 + 0 * 8, 1 + 1 * 8, 2 + 0 * 8, 0 + 7 * 8,
  73. 2 + 2 * 8, 2 + 3 * 8, 2 + 4 * 8, 3 + 3 * 8,
  74. 3 + 4 * 8, 4 + 3 * 8, 4 + 4 * 8, 5 + 3 * 8,
  75. 5 + 5 * 8, 7 + 0 * 8, 6 + 6 * 8, 7 + 4 * 8,
  76. 0 + 1 * 8, 0 + 3 * 8, 1 + 3 * 8, 1 + 4 * 8,
  77. 1 + 5 * 8, 3 + 1 * 8, 2 + 5 * 8, 4 + 1 * 8,
  78. 3 + 5 * 8, 5 + 1 * 8, 4 + 5 * 8, 6 + 1 * 8,
  79. 5 + 6 * 8, 7 + 1 * 8, 6 + 7 * 8, 7 + 5 * 8,
  80. 0 + 2 * 8, 0 + 4 * 8, 0 + 5 * 8, 2 + 1 * 8,
  81. 1 + 6 * 8, 4 + 0 * 8, 2 + 6 * 8, 5 + 0 * 8,
  82. 3 + 6 * 8, 6 + 0 * 8, 4 + 6 * 8, 6 + 2 * 8,
  83. 5 + 7 * 8, 6 + 4 * 8, 7 + 2 * 8, 7 + 6 * 8,
  84. 1 + 0 * 8, 1 + 2 * 8, 0 + 6 * 8, 3 + 0 * 8,
  85. 1 + 7 * 8, 3 + 2 * 8, 2 + 7 * 8, 4 + 2 * 8,
  86. 3 + 7 * 8, 5 + 2 * 8, 4 + 7 * 8, 5 + 4 * 8,
  87. 6 + 3 * 8, 6 + 5 * 8, 7 + 3 * 8, 7 + 7 * 8,
  88. };
  89. // zigzag_scan8x8_cavlc[i] = zigzag_scan8x8[(i/4) + 16*(i%4)]
  90. static const uint8_t zigzag_scan8x8_cavlc[64+1] = {
  91. 0 + 0 * 8, 1 + 1 * 8, 1 + 2 * 8, 2 + 2 * 8,
  92. 4 + 1 * 8, 0 + 5 * 8, 3 + 3 * 8, 7 + 0 * 8,
  93. 3 + 4 * 8, 1 + 7 * 8, 5 + 3 * 8, 6 + 3 * 8,
  94. 2 + 7 * 8, 6 + 4 * 8, 5 + 6 * 8, 7 + 5 * 8,
  95. 1 + 0 * 8, 2 + 0 * 8, 0 + 3 * 8, 3 + 1 * 8,
  96. 3 + 2 * 8, 0 + 6 * 8, 4 + 2 * 8, 6 + 1 * 8,
  97. 2 + 5 * 8, 2 + 6 * 8, 6 + 2 * 8, 5 + 4 * 8,
  98. 3 + 7 * 8, 7 + 3 * 8, 4 + 7 * 8, 7 + 6 * 8,
  99. 0 + 1 * 8, 3 + 0 * 8, 0 + 4 * 8, 4 + 0 * 8,
  100. 2 + 3 * 8, 1 + 5 * 8, 5 + 1 * 8, 5 + 2 * 8,
  101. 1 + 6 * 8, 3 + 5 * 8, 7 + 1 * 8, 4 + 5 * 8,
  102. 4 + 6 * 8, 7 + 4 * 8, 5 + 7 * 8, 6 + 7 * 8,
  103. 0 + 2 * 8, 2 + 1 * 8, 1 + 3 * 8, 5 + 0 * 8,
  104. 1 + 4 * 8, 2 + 4 * 8, 6 + 0 * 8, 4 + 3 * 8,
  105. 0 + 7 * 8, 4 + 4 * 8, 7 + 2 * 8, 3 + 6 * 8,
  106. 5 + 5 * 8, 6 + 5 * 8, 6 + 6 * 8, 7 + 7 * 8,
  107. };
  108. static void release_unused_pictures(H264Context *h, int remove_current)
  109. {
  110. int i;
  111. /* release non reference frames */
  112. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
  113. if (h->DPB[i].f->buf[0] && !h->DPB[i].reference &&
  114. (remove_current || &h->DPB[i] != h->cur_pic_ptr)) {
  115. ff_h264_unref_picture(h, &h->DPB[i]);
  116. }
  117. }
  118. }
  119. static int alloc_scratch_buffers(H264SliceContext *sl, int linesize)
  120. {
  121. const H264Context *h = sl->h264;
  122. int alloc_size = FFALIGN(FFABS(linesize) + 32, 32);
  123. av_fast_malloc(&sl->bipred_scratchpad, &sl->bipred_scratchpad_allocated, 16 * 6 * alloc_size);
  124. // edge emu needs blocksize + filter length - 1
  125. // (= 21x21 for H.264)
  126. av_fast_malloc(&sl->edge_emu_buffer, &sl->edge_emu_buffer_allocated, alloc_size * 2 * 21);
  127. av_fast_mallocz(&sl->top_borders[0], &sl->top_borders_allocated[0],
  128. h->mb_width * 16 * 3 * sizeof(uint8_t) * 2);
  129. av_fast_mallocz(&sl->top_borders[1], &sl->top_borders_allocated[1],
  130. h->mb_width * 16 * 3 * sizeof(uint8_t) * 2);
  131. if (!sl->bipred_scratchpad || !sl->edge_emu_buffer ||
  132. !sl->top_borders[0] || !sl->top_borders[1]) {
  133. av_freep(&sl->bipred_scratchpad);
  134. av_freep(&sl->edge_emu_buffer);
  135. av_freep(&sl->top_borders[0]);
  136. av_freep(&sl->top_borders[1]);
  137. sl->bipred_scratchpad_allocated = 0;
  138. sl->edge_emu_buffer_allocated = 0;
  139. sl->top_borders_allocated[0] = 0;
  140. sl->top_borders_allocated[1] = 0;
  141. return AVERROR(ENOMEM);
  142. }
  143. return 0;
  144. }
  145. static int init_table_pools(H264Context *h)
  146. {
  147. const int big_mb_num = h->mb_stride * (h->mb_height + 1) + 1;
  148. const int mb_array_size = h->mb_stride * h->mb_height;
  149. const int b4_stride = h->mb_width * 4 + 1;
  150. const int b4_array_size = b4_stride * h->mb_height * 4;
  151. h->qscale_table_pool = av_buffer_pool_init(big_mb_num + h->mb_stride,
  152. av_buffer_allocz);
  153. h->mb_type_pool = av_buffer_pool_init((big_mb_num + h->mb_stride) *
  154. sizeof(uint32_t), av_buffer_allocz);
  155. h->motion_val_pool = av_buffer_pool_init(2 * (b4_array_size + 4) *
  156. sizeof(int16_t), av_buffer_allocz);
  157. h->ref_index_pool = av_buffer_pool_init(4 * mb_array_size, av_buffer_allocz);
  158. if (!h->qscale_table_pool || !h->mb_type_pool || !h->motion_val_pool ||
  159. !h->ref_index_pool) {
  160. av_buffer_pool_uninit(&h->qscale_table_pool);
  161. av_buffer_pool_uninit(&h->mb_type_pool);
  162. av_buffer_pool_uninit(&h->motion_val_pool);
  163. av_buffer_pool_uninit(&h->ref_index_pool);
  164. return AVERROR(ENOMEM);
  165. }
  166. return 0;
  167. }
  168. static int alloc_picture(H264Context *h, H264Picture *pic)
  169. {
  170. int i, ret = 0;
  171. av_assert0(!pic->f->data[0]);
  172. pic->tf.f = pic->f;
  173. ret = ff_thread_get_buffer(h->avctx, &pic->tf, pic->reference ?
  174. AV_GET_BUFFER_FLAG_REF : 0);
  175. if (ret < 0)
  176. goto fail;
  177. if (h->avctx->hwaccel) {
  178. const AVHWAccel *hwaccel = h->avctx->hwaccel;
  179. av_assert0(!pic->hwaccel_picture_private);
  180. if (hwaccel->frame_priv_data_size) {
  181. pic->hwaccel_priv_buf = av_buffer_allocz(hwaccel->frame_priv_data_size);
  182. if (!pic->hwaccel_priv_buf)
  183. return AVERROR(ENOMEM);
  184. pic->hwaccel_picture_private = pic->hwaccel_priv_buf->data;
  185. }
  186. }
  187. if (CONFIG_GRAY && !h->avctx->hwaccel && h->flags & AV_CODEC_FLAG_GRAY && pic->f->data[2]) {
  188. int h_chroma_shift, v_chroma_shift;
  189. av_pix_fmt_get_chroma_sub_sample(pic->f->format,
  190. &h_chroma_shift, &v_chroma_shift);
  191. for(i=0; i<AV_CEIL_RSHIFT(pic->f->height, v_chroma_shift); i++) {
  192. memset(pic->f->data[1] + pic->f->linesize[1]*i,
  193. 0x80, AV_CEIL_RSHIFT(pic->f->width, h_chroma_shift));
  194. memset(pic->f->data[2] + pic->f->linesize[2]*i,
  195. 0x80, AV_CEIL_RSHIFT(pic->f->width, h_chroma_shift));
  196. }
  197. }
  198. if (!h->qscale_table_pool) {
  199. ret = init_table_pools(h);
  200. if (ret < 0)
  201. goto fail;
  202. }
  203. pic->qscale_table_buf = av_buffer_pool_get(h->qscale_table_pool);
  204. pic->mb_type_buf = av_buffer_pool_get(h->mb_type_pool);
  205. if (!pic->qscale_table_buf || !pic->mb_type_buf)
  206. goto fail;
  207. pic->mb_type = (uint32_t*)pic->mb_type_buf->data + 2 * h->mb_stride + 1;
  208. pic->qscale_table = pic->qscale_table_buf->data + 2 * h->mb_stride + 1;
  209. for (i = 0; i < 2; i++) {
  210. pic->motion_val_buf[i] = av_buffer_pool_get(h->motion_val_pool);
  211. pic->ref_index_buf[i] = av_buffer_pool_get(h->ref_index_pool);
  212. if (!pic->motion_val_buf[i] || !pic->ref_index_buf[i])
  213. goto fail;
  214. pic->motion_val[i] = (int16_t (*)[2])pic->motion_val_buf[i]->data + 4;
  215. pic->ref_index[i] = pic->ref_index_buf[i]->data;
  216. }
  217. pic->pps_buf = av_buffer_ref(h->ps.pps_ref);
  218. if (!pic->pps_buf)
  219. goto fail;
  220. pic->pps = (const PPS*)pic->pps_buf->data;
  221. pic->mb_width = h->mb_width;
  222. pic->mb_height = h->mb_height;
  223. pic->mb_stride = h->mb_stride;
  224. return 0;
  225. fail:
  226. ff_h264_unref_picture(h, pic);
  227. return (ret < 0) ? ret : AVERROR(ENOMEM);
  228. }
  229. static int find_unused_picture(H264Context *h)
  230. {
  231. int i;
  232. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
  233. if (!h->DPB[i].f->buf[0])
  234. return i;
  235. }
  236. return AVERROR_INVALIDDATA;
  237. }
  238. #define IN_RANGE(a, b, size) (((void*)(a) >= (void*)(b)) && ((void*)(a) < (void*)((b) + (size))))
  239. #define REBASE_PICTURE(pic, new_ctx, old_ctx) \
  240. (((pic) && (pic) >= (old_ctx)->DPB && \
  241. (pic) < (old_ctx)->DPB + H264_MAX_PICTURE_COUNT) ? \
  242. &(new_ctx)->DPB[(pic) - (old_ctx)->DPB] : NULL)
  243. static void copy_picture_range(H264Picture **to, H264Picture **from, int count,
  244. H264Context *new_base,
  245. H264Context *old_base)
  246. {
  247. int i;
  248. for (i = 0; i < count; i++) {
  249. av_assert1(!from[i] ||
  250. IN_RANGE(from[i], old_base, 1) ||
  251. IN_RANGE(from[i], old_base->DPB, H264_MAX_PICTURE_COUNT));
  252. to[i] = REBASE_PICTURE(from[i], new_base, old_base);
  253. }
  254. }
  255. static int h264_slice_header_init(H264Context *h);
  256. int ff_h264_update_thread_context(AVCodecContext *dst,
  257. const AVCodecContext *src)
  258. {
  259. H264Context *h = dst->priv_data, *h1 = src->priv_data;
  260. int inited = h->context_initialized, err = 0;
  261. int need_reinit = 0;
  262. int i, ret;
  263. if (dst == src)
  264. return 0;
  265. // We can't fail if SPS isn't set at it breaks current skip_frame code
  266. //if (!h1->ps.sps)
  267. // return AVERROR_INVALIDDATA;
  268. if (inited &&
  269. (h->width != h1->width ||
  270. h->height != h1->height ||
  271. h->mb_width != h1->mb_width ||
  272. h->mb_height != h1->mb_height ||
  273. !h->ps.sps ||
  274. h->ps.sps->bit_depth_luma != h1->ps.sps->bit_depth_luma ||
  275. h->ps.sps->chroma_format_idc != h1->ps.sps->chroma_format_idc ||
  276. h->ps.sps->colorspace != h1->ps.sps->colorspace)) {
  277. need_reinit = 1;
  278. }
  279. /* copy block_offset since frame_start may not be called */
  280. memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));
  281. // SPS/PPS
  282. for (i = 0; i < FF_ARRAY_ELEMS(h->ps.sps_list); i++) {
  283. ret = av_buffer_replace(&h->ps.sps_list[i], h1->ps.sps_list[i]);
  284. if (ret < 0)
  285. return ret;
  286. }
  287. for (i = 0; i < FF_ARRAY_ELEMS(h->ps.pps_list); i++) {
  288. ret = av_buffer_replace(&h->ps.pps_list[i], h1->ps.pps_list[i]);
  289. if (ret < 0)
  290. return ret;
  291. }
  292. ret = av_buffer_replace(&h->ps.pps_ref, h1->ps.pps_ref);
  293. if (ret < 0)
  294. return ret;
  295. h->ps.pps = NULL;
  296. h->ps.sps = NULL;
  297. if (h1->ps.pps_ref) {
  298. h->ps.pps = (const PPS*)h->ps.pps_ref->data;
  299. h->ps.sps = h->ps.pps->sps;
  300. }
  301. if (need_reinit || !inited) {
  302. h->width = h1->width;
  303. h->height = h1->height;
  304. h->mb_height = h1->mb_height;
  305. h->mb_width = h1->mb_width;
  306. h->mb_num = h1->mb_num;
  307. h->mb_stride = h1->mb_stride;
  308. h->b_stride = h1->b_stride;
  309. h->x264_build = h1->x264_build;
  310. if (h->context_initialized || h1->context_initialized) {
  311. if ((err = h264_slice_header_init(h)) < 0) {
  312. av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed");
  313. return err;
  314. }
  315. }
  316. /* copy block_offset since frame_start may not be called */
  317. memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));
  318. }
  319. h->avctx->coded_height = h1->avctx->coded_height;
  320. h->avctx->coded_width = h1->avctx->coded_width;
  321. h->avctx->width = h1->avctx->width;
  322. h->avctx->height = h1->avctx->height;
  323. h->width_from_caller = h1->width_from_caller;
  324. h->height_from_caller = h1->height_from_caller;
  325. h->coded_picture_number = h1->coded_picture_number;
  326. h->first_field = h1->first_field;
  327. h->picture_structure = h1->picture_structure;
  328. h->mb_aff_frame = h1->mb_aff_frame;
  329. h->droppable = h1->droppable;
  330. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
  331. ff_h264_unref_picture(h, &h->DPB[i]);
  332. if (h1->DPB[i].f->buf[0] &&
  333. (ret = ff_h264_ref_picture(h, &h->DPB[i], &h1->DPB[i])) < 0)
  334. return ret;
  335. }
  336. h->cur_pic_ptr = REBASE_PICTURE(h1->cur_pic_ptr, h, h1);
  337. ff_h264_unref_picture(h, &h->cur_pic);
  338. if (h1->cur_pic.f->buf[0]) {
  339. ret = ff_h264_ref_picture(h, &h->cur_pic, &h1->cur_pic);
  340. if (ret < 0)
  341. return ret;
  342. }
  343. h->enable_er = h1->enable_er;
  344. h->workaround_bugs = h1->workaround_bugs;
  345. h->droppable = h1->droppable;
  346. // extradata/NAL handling
  347. h->is_avc = h1->is_avc;
  348. h->nal_length_size = h1->nal_length_size;
  349. memcpy(&h->poc, &h1->poc, sizeof(h->poc));
  350. memcpy(h->short_ref, h1->short_ref, sizeof(h->short_ref));
  351. memcpy(h->long_ref, h1->long_ref, sizeof(h->long_ref));
  352. memcpy(h->delayed_pic, h1->delayed_pic, sizeof(h->delayed_pic));
  353. memcpy(h->last_pocs, h1->last_pocs, sizeof(h->last_pocs));
  354. h->next_output_pic = h1->next_output_pic;
  355. h->next_outputed_poc = h1->next_outputed_poc;
  356. memcpy(h->mmco, h1->mmco, sizeof(h->mmco));
  357. h->nb_mmco = h1->nb_mmco;
  358. h->mmco_reset = h1->mmco_reset;
  359. h->explicit_ref_marking = h1->explicit_ref_marking;
  360. h->long_ref_count = h1->long_ref_count;
  361. h->short_ref_count = h1->short_ref_count;
  362. copy_picture_range(h->short_ref, h1->short_ref, 32, h, h1);
  363. copy_picture_range(h->long_ref, h1->long_ref, 32, h, h1);
  364. copy_picture_range(h->delayed_pic, h1->delayed_pic,
  365. MAX_DELAYED_PIC_COUNT + 2, h, h1);
  366. h->frame_recovered = h1->frame_recovered;
  367. ret = av_buffer_replace(&h->sei.a53_caption.buf_ref, h1->sei.a53_caption.buf_ref);
  368. if (ret < 0)
  369. return ret;
  370. for (i = 0; i < h->sei.unregistered.nb_buf_ref; i++)
  371. av_buffer_unref(&h->sei.unregistered.buf_ref[i]);
  372. h->sei.unregistered.nb_buf_ref = 0;
  373. if (h1->sei.unregistered.nb_buf_ref) {
  374. ret = av_reallocp_array(&h->sei.unregistered.buf_ref,
  375. h1->sei.unregistered.nb_buf_ref,
  376. sizeof(*h->sei.unregistered.buf_ref));
  377. if (ret < 0)
  378. return ret;
  379. for (i = 0; i < h1->sei.unregistered.nb_buf_ref; i++) {
  380. h->sei.unregistered.buf_ref[i] = av_buffer_ref(h1->sei.unregistered.buf_ref[i]);
  381. if (!h->sei.unregistered.buf_ref[i])
  382. return AVERROR(ENOMEM);
  383. h->sei.unregistered.nb_buf_ref++;
  384. }
  385. }
  386. h->sei.unregistered.x264_build = h1->sei.unregistered.x264_build;
  387. if (!h->cur_pic_ptr)
  388. return 0;
  389. if (!h->droppable) {
  390. err = ff_h264_execute_ref_pic_marking(h);
  391. h->poc.prev_poc_msb = h->poc.poc_msb;
  392. h->poc.prev_poc_lsb = h->poc.poc_lsb;
  393. }
  394. h->poc.prev_frame_num_offset = h->poc.frame_num_offset;
  395. h->poc.prev_frame_num = h->poc.frame_num;
  396. h->recovery_frame = h1->recovery_frame;
  397. return err;
  398. }
  399. static int h264_frame_start(H264Context *h)
  400. {
  401. H264Picture *pic;
  402. int i, ret;
  403. const int pixel_shift = h->pixel_shift;
  404. if (!ff_thread_can_start_frame(h->avctx)) {
  405. av_log(h->avctx, AV_LOG_ERROR, "Attempt to start a frame outside SETUP state\n");
  406. return -1;
  407. }
  408. release_unused_pictures(h, 1);
  409. h->cur_pic_ptr = NULL;
  410. i = find_unused_picture(h);
  411. if (i < 0) {
  412. av_log(h->avctx, AV_LOG_ERROR, "no frame buffer available\n");
  413. return i;
  414. }
  415. pic = &h->DPB[i];
  416. pic->reference = h->droppable ? 0 : h->picture_structure;
  417. pic->f->coded_picture_number = h->coded_picture_number++;
  418. pic->field_picture = h->picture_structure != PICT_FRAME;
  419. pic->frame_num = h->poc.frame_num;
  420. /*
  421. * Zero key_frame here; IDR markings per slice in frame or fields are ORed
  422. * in later.
  423. * See decode_nal_units().
  424. */
  425. pic->f->key_frame = 0;
  426. pic->mmco_reset = 0;
  427. pic->recovered = 0;
  428. pic->invalid_gap = 0;
  429. pic->sei_recovery_frame_cnt = h->sei.recovery_point.recovery_frame_cnt;
  430. pic->f->pict_type = h->slice_ctx[0].slice_type;
  431. pic->f->crop_left = h->crop_left;
  432. pic->f->crop_right = h->crop_right;
  433. pic->f->crop_top = h->crop_top;
  434. pic->f->crop_bottom = h->crop_bottom;
  435. if ((ret = alloc_picture(h, pic)) < 0)
  436. return ret;
  437. h->cur_pic_ptr = pic;
  438. ff_h264_unref_picture(h, &h->cur_pic);
  439. if (CONFIG_ERROR_RESILIENCE) {
  440. ff_h264_set_erpic(&h->slice_ctx[0].er.cur_pic, NULL);
  441. }
  442. if ((ret = ff_h264_ref_picture(h, &h->cur_pic, h->cur_pic_ptr)) < 0)
  443. return ret;
  444. for (i = 0; i < h->nb_slice_ctx; i++) {
  445. h->slice_ctx[i].linesize = h->cur_pic_ptr->f->linesize[0];
  446. h->slice_ctx[i].uvlinesize = h->cur_pic_ptr->f->linesize[1];
  447. }
  448. if (CONFIG_ERROR_RESILIENCE && h->enable_er) {
  449. ff_er_frame_start(&h->slice_ctx[0].er);
  450. ff_h264_set_erpic(&h->slice_ctx[0].er.last_pic, NULL);
  451. ff_h264_set_erpic(&h->slice_ctx[0].er.next_pic, NULL);
  452. }
  453. for (i = 0; i < 16; i++) {
  454. h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * pic->f->linesize[0] * ((scan8[i] - scan8[0]) >> 3);
  455. h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * pic->f->linesize[0] * ((scan8[i] - scan8[0]) >> 3);
  456. }
  457. for (i = 0; i < 16; i++) {
  458. h->block_offset[16 + i] =
  459. h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * pic->f->linesize[1] * ((scan8[i] - scan8[0]) >> 3);
  460. h->block_offset[48 + 16 + i] =
  461. h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * pic->f->linesize[1] * ((scan8[i] - scan8[0]) >> 3);
  462. }
  463. /* We mark the current picture as non-reference after allocating it, so
  464. * that if we break out due to an error it can be released automatically
  465. * in the next ff_mpv_frame_start().
  466. */
  467. h->cur_pic_ptr->reference = 0;
  468. h->cur_pic_ptr->field_poc[0] = h->cur_pic_ptr->field_poc[1] = INT_MAX;
  469. h->next_output_pic = NULL;
  470. h->postpone_filter = 0;
  471. h->mb_aff_frame = h->ps.sps->mb_aff && (h->picture_structure == PICT_FRAME);
  472. if (h->sei.unregistered.x264_build >= 0)
  473. h->x264_build = h->sei.unregistered.x264_build;
  474. assert(h->cur_pic_ptr->long_ref == 0);
  475. return 0;
  476. }
  477. static av_always_inline void backup_mb_border(const H264Context *h, H264SliceContext *sl,
  478. uint8_t *src_y,
  479. uint8_t *src_cb, uint8_t *src_cr,
  480. int linesize, int uvlinesize,
  481. int simple)
  482. {
  483. uint8_t *top_border;
  484. int top_idx = 1;
  485. const int pixel_shift = h->pixel_shift;
  486. int chroma444 = CHROMA444(h);
  487. int chroma422 = CHROMA422(h);
  488. src_y -= linesize;
  489. src_cb -= uvlinesize;
  490. src_cr -= uvlinesize;
  491. if (!simple && FRAME_MBAFF(h)) {
  492. if (sl->mb_y & 1) {
  493. if (!MB_MBAFF(sl)) {
  494. top_border = sl->top_borders[0][sl->mb_x];
  495. AV_COPY128(top_border, src_y + 15 * linesize);
  496. if (pixel_shift)
  497. AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
  498. if (simple || !CONFIG_GRAY || !(h->flags & AV_CODEC_FLAG_GRAY)) {
  499. if (chroma444) {
  500. if (pixel_shift) {
  501. AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
  502. AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
  503. AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
  504. AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
  505. } else {
  506. AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
  507. AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
  508. }
  509. } else if (chroma422) {
  510. if (pixel_shift) {
  511. AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
  512. AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
  513. } else {
  514. AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
  515. AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
  516. }
  517. } else {
  518. if (pixel_shift) {
  519. AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
  520. AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
  521. } else {
  522. AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
  523. AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
  524. }
  525. }
  526. }
  527. }
  528. } else if (MB_MBAFF(sl)) {
  529. top_idx = 0;
  530. } else
  531. return;
  532. }
  533. top_border = sl->top_borders[top_idx][sl->mb_x];
  534. /* There are two lines saved, the line above the top macroblock
  535. * of a pair, and the line above the bottom macroblock. */
  536. AV_COPY128(top_border, src_y + 16 * linesize);
  537. if (pixel_shift)
  538. AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
  539. if (simple || !CONFIG_GRAY || !(h->flags & AV_CODEC_FLAG_GRAY)) {
  540. if (chroma444) {
  541. if (pixel_shift) {
  542. AV_COPY128(top_border + 32, src_cb + 16 * linesize);
  543. AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
  544. AV_COPY128(top_border + 64, src_cr + 16 * linesize);
  545. AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
  546. } else {
  547. AV_COPY128(top_border + 16, src_cb + 16 * linesize);
  548. AV_COPY128(top_border + 32, src_cr + 16 * linesize);
  549. }
  550. } else if (chroma422) {
  551. if (pixel_shift) {
  552. AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
  553. AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
  554. } else {
  555. AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
  556. AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
  557. }
  558. } else {
  559. if (pixel_shift) {
  560. AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
  561. AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
  562. } else {
  563. AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
  564. AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
  565. }
  566. }
  567. }
  568. }
  569. /**
  570. * Initialize implicit_weight table.
  571. * @param field 0/1 initialize the weight for interlaced MBAFF
  572. * -1 initializes the rest
  573. */
  574. static void implicit_weight_table(const H264Context *h, H264SliceContext *sl, int field)
  575. {
  576. int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
  577. for (i = 0; i < 2; i++) {
  578. sl->pwt.luma_weight_flag[i] = 0;
  579. sl->pwt.chroma_weight_flag[i] = 0;
  580. }
  581. if (field < 0) {
  582. if (h->picture_structure == PICT_FRAME) {
  583. cur_poc = h->cur_pic_ptr->poc;
  584. } else {
  585. cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];
  586. }
  587. if (sl->ref_count[0] == 1 && sl->ref_count[1] == 1 && !FRAME_MBAFF(h) &&
  588. sl->ref_list[0][0].poc + (int64_t)sl->ref_list[1][0].poc == 2LL * cur_poc) {
  589. sl->pwt.use_weight = 0;
  590. sl->pwt.use_weight_chroma = 0;
  591. return;
  592. }
  593. ref_start = 0;
  594. ref_count0 = sl->ref_count[0];
  595. ref_count1 = sl->ref_count[1];
  596. } else {
  597. cur_poc = h->cur_pic_ptr->field_poc[field];
  598. ref_start = 16;
  599. ref_count0 = 16 + 2 * sl->ref_count[0];
  600. ref_count1 = 16 + 2 * sl->ref_count[1];
  601. }
  602. sl->pwt.use_weight = 2;
  603. sl->pwt.use_weight_chroma = 2;
  604. sl->pwt.luma_log2_weight_denom = 5;
  605. sl->pwt.chroma_log2_weight_denom = 5;
  606. for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
  607. int64_t poc0 = sl->ref_list[0][ref0].poc;
  608. for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
  609. int w = 32;
  610. if (!sl->ref_list[0][ref0].parent->long_ref && !sl->ref_list[1][ref1].parent->long_ref) {
  611. int poc1 = sl->ref_list[1][ref1].poc;
  612. int td = av_clip_int8(poc1 - poc0);
  613. if (td) {
  614. int tb = av_clip_int8(cur_poc - poc0);
  615. int tx = (16384 + (FFABS(td) >> 1)) / td;
  616. int dist_scale_factor = (tb * tx + 32) >> 8;
  617. if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
  618. w = 64 - dist_scale_factor;
  619. }
  620. }
  621. if (field < 0) {
  622. sl->pwt.implicit_weight[ref0][ref1][0] =
  623. sl->pwt.implicit_weight[ref0][ref1][1] = w;
  624. } else {
  625. sl->pwt.implicit_weight[ref0][ref1][field] = w;
  626. }
  627. }
  628. }
  629. }
  630. /**
  631. * initialize scan tables
  632. */
  633. static void init_scan_tables(H264Context *h)
  634. {
  635. int i;
  636. for (i = 0; i < 16; i++) {
  637. #define TRANSPOSE(x) ((x) >> 2) | (((x) << 2) & 0xF)
  638. h->zigzag_scan[i] = TRANSPOSE(ff_zigzag_scan[i]);
  639. h->field_scan[i] = TRANSPOSE(field_scan[i]);
  640. #undef TRANSPOSE
  641. }
  642. for (i = 0; i < 64; i++) {
  643. #define TRANSPOSE(x) ((x) >> 3) | (((x) & 7) << 3)
  644. h->zigzag_scan8x8[i] = TRANSPOSE(ff_zigzag_direct[i]);
  645. h->zigzag_scan8x8_cavlc[i] = TRANSPOSE(zigzag_scan8x8_cavlc[i]);
  646. h->field_scan8x8[i] = TRANSPOSE(field_scan8x8[i]);
  647. h->field_scan8x8_cavlc[i] = TRANSPOSE(field_scan8x8_cavlc[i]);
  648. #undef TRANSPOSE
  649. }
  650. if (h->ps.sps->transform_bypass) { // FIXME same ugly
  651. memcpy(h->zigzag_scan_q0 , ff_zigzag_scan , sizeof(h->zigzag_scan_q0 ));
  652. memcpy(h->zigzag_scan8x8_q0 , ff_zigzag_direct , sizeof(h->zigzag_scan8x8_q0 ));
  653. memcpy(h->zigzag_scan8x8_cavlc_q0 , zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
  654. memcpy(h->field_scan_q0 , field_scan , sizeof(h->field_scan_q0 ));
  655. memcpy(h->field_scan8x8_q0 , field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
  656. memcpy(h->field_scan8x8_cavlc_q0 , field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
  657. } else {
  658. memcpy(h->zigzag_scan_q0 , h->zigzag_scan , sizeof(h->zigzag_scan_q0 ));
  659. memcpy(h->zigzag_scan8x8_q0 , h->zigzag_scan8x8 , sizeof(h->zigzag_scan8x8_q0 ));
  660. memcpy(h->zigzag_scan8x8_cavlc_q0 , h->zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
  661. memcpy(h->field_scan_q0 , h->field_scan , sizeof(h->field_scan_q0 ));
  662. memcpy(h->field_scan8x8_q0 , h->field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
  663. memcpy(h->field_scan8x8_cavlc_q0 , h->field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
  664. }
  665. }
  666. static enum AVPixelFormat get_pixel_format(H264Context *h, int force_callback)
  667. {
  668. #define HWACCEL_MAX (CONFIG_H264_DXVA2_HWACCEL + \
  669. (CONFIG_H264_D3D11VA_HWACCEL * 2) + \
  670. CONFIG_H264_NVDEC_HWACCEL + \
  671. CONFIG_H264_VAAPI_HWACCEL + \
  672. CONFIG_H264_VIDEOTOOLBOX_HWACCEL + \
  673. CONFIG_H264_VDPAU_HWACCEL)
  674. enum AVPixelFormat pix_fmts[HWACCEL_MAX + 2], *fmt = pix_fmts;
  675. const enum AVPixelFormat *choices = pix_fmts;
  676. int i;
  677. switch (h->ps.sps->bit_depth_luma) {
  678. case 9:
  679. if (CHROMA444(h)) {
  680. if (h->avctx->colorspace == AVCOL_SPC_RGB) {
  681. *fmt++ = AV_PIX_FMT_GBRP9;
  682. } else
  683. *fmt++ = AV_PIX_FMT_YUV444P9;
  684. } else if (CHROMA422(h))
  685. *fmt++ = AV_PIX_FMT_YUV422P9;
  686. else
  687. *fmt++ = AV_PIX_FMT_YUV420P9;
  688. break;
  689. case 10:
  690. if (CHROMA444(h)) {
  691. if (h->avctx->colorspace == AVCOL_SPC_RGB) {
  692. *fmt++ = AV_PIX_FMT_GBRP10;
  693. } else
  694. *fmt++ = AV_PIX_FMT_YUV444P10;
  695. } else if (CHROMA422(h))
  696. *fmt++ = AV_PIX_FMT_YUV422P10;
  697. else
  698. *fmt++ = AV_PIX_FMT_YUV420P10;
  699. break;
  700. case 12:
  701. if (CHROMA444(h)) {
  702. if (h->avctx->colorspace == AVCOL_SPC_RGB) {
  703. *fmt++ = AV_PIX_FMT_GBRP12;
  704. } else
  705. *fmt++ = AV_PIX_FMT_YUV444P12;
  706. } else if (CHROMA422(h))
  707. *fmt++ = AV_PIX_FMT_YUV422P12;
  708. else
  709. *fmt++ = AV_PIX_FMT_YUV420P12;
  710. break;
  711. case 14:
  712. if (CHROMA444(h)) {
  713. if (h->avctx->colorspace == AVCOL_SPC_RGB) {
  714. *fmt++ = AV_PIX_FMT_GBRP14;
  715. } else
  716. *fmt++ = AV_PIX_FMT_YUV444P14;
  717. } else if (CHROMA422(h))
  718. *fmt++ = AV_PIX_FMT_YUV422P14;
  719. else
  720. *fmt++ = AV_PIX_FMT_YUV420P14;
  721. break;
  722. case 8:
  723. #if CONFIG_H264_VDPAU_HWACCEL
  724. *fmt++ = AV_PIX_FMT_VDPAU;
  725. #endif
  726. #if CONFIG_H264_NVDEC_HWACCEL
  727. *fmt++ = AV_PIX_FMT_CUDA;
  728. #endif
  729. if (CHROMA444(h)) {
  730. if (h->avctx->colorspace == AVCOL_SPC_RGB)
  731. *fmt++ = AV_PIX_FMT_GBRP;
  732. else if (h->avctx->color_range == AVCOL_RANGE_JPEG)
  733. *fmt++ = AV_PIX_FMT_YUVJ444P;
  734. else
  735. *fmt++ = AV_PIX_FMT_YUV444P;
  736. } else if (CHROMA422(h)) {
  737. if (h->avctx->color_range == AVCOL_RANGE_JPEG)
  738. *fmt++ = AV_PIX_FMT_YUVJ422P;
  739. else
  740. *fmt++ = AV_PIX_FMT_YUV422P;
  741. } else {
  742. #if CONFIG_H264_DXVA2_HWACCEL
  743. *fmt++ = AV_PIX_FMT_DXVA2_VLD;
  744. #endif
  745. #if CONFIG_H264_D3D11VA_HWACCEL
  746. *fmt++ = AV_PIX_FMT_D3D11VA_VLD;
  747. *fmt++ = AV_PIX_FMT_D3D11;
  748. #endif
  749. #if CONFIG_H264_VAAPI_HWACCEL
  750. *fmt++ = AV_PIX_FMT_VAAPI;
  751. #endif
  752. #if CONFIG_H264_VIDEOTOOLBOX_HWACCEL
  753. *fmt++ = AV_PIX_FMT_VIDEOTOOLBOX;
  754. #endif
  755. if (h->avctx->codec->pix_fmts)
  756. choices = h->avctx->codec->pix_fmts;
  757. else if (h->avctx->color_range == AVCOL_RANGE_JPEG)
  758. *fmt++ = AV_PIX_FMT_YUVJ420P;
  759. else
  760. *fmt++ = AV_PIX_FMT_YUV420P;
  761. }
  762. break;
  763. default:
  764. av_log(h->avctx, AV_LOG_ERROR,
  765. "Unsupported bit depth %d\n", h->ps.sps->bit_depth_luma);
  766. return AVERROR_INVALIDDATA;
  767. }
  768. *fmt = AV_PIX_FMT_NONE;
  769. for (i=0; choices[i] != AV_PIX_FMT_NONE; i++)
  770. if (choices[i] == h->avctx->pix_fmt && !force_callback)
  771. return choices[i];
  772. return ff_thread_get_format(h->avctx, choices);
  773. }
  774. /* export coded and cropped frame dimensions to AVCodecContext */
  775. static void init_dimensions(H264Context *h)
  776. {
  777. const SPS *sps = (const SPS*)h->ps.sps;
  778. int cr = sps->crop_right;
  779. int cl = sps->crop_left;
  780. int ct = sps->crop_top;
  781. int cb = sps->crop_bottom;
  782. int width = h->width - (cr + cl);
  783. int height = h->height - (ct + cb);
  784. av_assert0(sps->crop_right + sps->crop_left < (unsigned)h->width);
  785. av_assert0(sps->crop_top + sps->crop_bottom < (unsigned)h->height);
  786. /* handle container cropping */
  787. if (h->width_from_caller > 0 && h->height_from_caller > 0 &&
  788. !sps->crop_top && !sps->crop_left &&
  789. FFALIGN(h->width_from_caller, 16) == FFALIGN(width, 16) &&
  790. FFALIGN(h->height_from_caller, 16) == FFALIGN(height, 16) &&
  791. h->width_from_caller <= width &&
  792. h->height_from_caller <= height) {
  793. width = h->width_from_caller;
  794. height = h->height_from_caller;
  795. cl = 0;
  796. ct = 0;
  797. cr = h->width - width;
  798. cb = h->height - height;
  799. } else {
  800. h->width_from_caller = 0;
  801. h->height_from_caller = 0;
  802. }
  803. h->avctx->coded_width = h->width;
  804. h->avctx->coded_height = h->height;
  805. h->avctx->width = width;
  806. h->avctx->height = height;
  807. h->crop_right = cr;
  808. h->crop_left = cl;
  809. h->crop_top = ct;
  810. h->crop_bottom = cb;
  811. }
  812. static int h264_slice_header_init(H264Context *h)
  813. {
  814. const SPS *sps = h->ps.sps;
  815. int i, ret;
  816. ff_set_sar(h->avctx, sps->sar);
  817. av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt,
  818. &h->chroma_x_shift, &h->chroma_y_shift);
  819. if (sps->timing_info_present_flag) {
  820. int64_t den = sps->time_scale;
  821. if (h->x264_build < 44U)
  822. den *= 2;
  823. av_reduce(&h->avctx->framerate.den, &h->avctx->framerate.num,
  824. sps->num_units_in_tick * h->avctx->ticks_per_frame, den, 1 << 30);
  825. }
  826. ff_h264_free_tables(h);
  827. h->first_field = 0;
  828. h->prev_interlaced_frame = 1;
  829. init_scan_tables(h);
  830. ret = ff_h264_alloc_tables(h);
  831. if (ret < 0) {
  832. av_log(h->avctx, AV_LOG_ERROR, "Could not allocate memory\n");
  833. goto fail;
  834. }
  835. if (sps->bit_depth_luma < 8 || sps->bit_depth_luma > 14 ||
  836. sps->bit_depth_luma == 11 || sps->bit_depth_luma == 13
  837. ) {
  838. av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth %d\n",
  839. sps->bit_depth_luma);
  840. ret = AVERROR_INVALIDDATA;
  841. goto fail;
  842. }
  843. h->cur_bit_depth_luma =
  844. h->avctx->bits_per_raw_sample = sps->bit_depth_luma;
  845. h->cur_chroma_format_idc = sps->chroma_format_idc;
  846. h->pixel_shift = sps->bit_depth_luma > 8;
  847. h->chroma_format_idc = sps->chroma_format_idc;
  848. h->bit_depth_luma = sps->bit_depth_luma;
  849. ff_h264dsp_init(&h->h264dsp, sps->bit_depth_luma,
  850. sps->chroma_format_idc);
  851. ff_h264chroma_init(&h->h264chroma, sps->bit_depth_chroma);
  852. ff_h264qpel_init(&h->h264qpel, sps->bit_depth_luma);
  853. ff_h264_pred_init(&h->hpc, h->avctx->codec_id, sps->bit_depth_luma,
  854. sps->chroma_format_idc);
  855. ff_videodsp_init(&h->vdsp, sps->bit_depth_luma);
  856. if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
  857. ret = ff_h264_slice_context_init(h, &h->slice_ctx[0]);
  858. if (ret < 0) {
  859. av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
  860. goto fail;
  861. }
  862. } else {
  863. for (i = 0; i < h->nb_slice_ctx; i++) {
  864. H264SliceContext *sl = &h->slice_ctx[i];
  865. sl->h264 = h;
  866. sl->intra4x4_pred_mode = h->intra4x4_pred_mode + i * 8 * 2 * h->mb_stride;
  867. sl->mvd_table[0] = h->mvd_table[0] + i * 8 * 2 * h->mb_stride;
  868. sl->mvd_table[1] = h->mvd_table[1] + i * 8 * 2 * h->mb_stride;
  869. if ((ret = ff_h264_slice_context_init(h, sl)) < 0) {
  870. av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
  871. goto fail;
  872. }
  873. }
  874. }
  875. h->context_initialized = 1;
  876. return 0;
  877. fail:
  878. ff_h264_free_tables(h);
  879. h->context_initialized = 0;
  880. return ret;
  881. }
  882. static enum AVPixelFormat non_j_pixfmt(enum AVPixelFormat a)
  883. {
  884. switch (a) {
  885. case AV_PIX_FMT_YUVJ420P: return AV_PIX_FMT_YUV420P;
  886. case AV_PIX_FMT_YUVJ422P: return AV_PIX_FMT_YUV422P;
  887. case AV_PIX_FMT_YUVJ444P: return AV_PIX_FMT_YUV444P;
  888. default:
  889. return a;
  890. }
  891. }
  892. static int h264_init_ps(H264Context *h, const H264SliceContext *sl, int first_slice)
  893. {
  894. const SPS *sps;
  895. int needs_reinit = 0, must_reinit, ret;
  896. if (first_slice) {
  897. av_buffer_unref(&h->ps.pps_ref);
  898. h->ps.pps = NULL;
  899. h->ps.pps_ref = av_buffer_ref(h->ps.pps_list[sl->pps_id]);
  900. if (!h->ps.pps_ref)
  901. return AVERROR(ENOMEM);
  902. h->ps.pps = (const PPS*)h->ps.pps_ref->data;
  903. }
  904. if (h->ps.sps != h->ps.pps->sps) {
  905. h->ps.sps = (const SPS*)h->ps.pps->sps;
  906. if (h->mb_width != h->ps.sps->mb_width ||
  907. h->mb_height != h->ps.sps->mb_height ||
  908. h->cur_bit_depth_luma != h->ps.sps->bit_depth_luma ||
  909. h->cur_chroma_format_idc != h->ps.sps->chroma_format_idc
  910. )
  911. needs_reinit = 1;
  912. if (h->bit_depth_luma != h->ps.sps->bit_depth_luma ||
  913. h->chroma_format_idc != h->ps.sps->chroma_format_idc)
  914. needs_reinit = 1;
  915. }
  916. sps = h->ps.sps;
  917. must_reinit = (h->context_initialized &&
  918. ( 16*sps->mb_width != h->avctx->coded_width
  919. || 16*sps->mb_height != h->avctx->coded_height
  920. || h->cur_bit_depth_luma != sps->bit_depth_luma
  921. || h->cur_chroma_format_idc != sps->chroma_format_idc
  922. || h->mb_width != sps->mb_width
  923. || h->mb_height != sps->mb_height
  924. ));
  925. if (h->avctx->pix_fmt == AV_PIX_FMT_NONE
  926. || (non_j_pixfmt(h->avctx->pix_fmt) != non_j_pixfmt(get_pixel_format(h, 0))))
  927. must_reinit = 1;
  928. if (first_slice && av_cmp_q(sps->sar, h->avctx->sample_aspect_ratio))
  929. must_reinit = 1;
  930. if (!h->setup_finished) {
  931. h->avctx->profile = ff_h264_get_profile(sps);
  932. h->avctx->level = sps->level_idc;
  933. h->avctx->refs = sps->ref_frame_count;
  934. h->mb_width = sps->mb_width;
  935. h->mb_height = sps->mb_height;
  936. h->mb_num = h->mb_width * h->mb_height;
  937. h->mb_stride = h->mb_width + 1;
  938. h->b_stride = h->mb_width * 4;
  939. h->chroma_y_shift = sps->chroma_format_idc <= 1; // 400 uses yuv420p
  940. h->width = 16 * h->mb_width;
  941. h->height = 16 * h->mb_height;
  942. init_dimensions(h);
  943. if (sps->video_signal_type_present_flag) {
  944. h->avctx->color_range = sps->full_range > 0 ? AVCOL_RANGE_JPEG
  945. : AVCOL_RANGE_MPEG;
  946. if (sps->colour_description_present_flag) {
  947. if (h->avctx->colorspace != sps->colorspace)
  948. needs_reinit = 1;
  949. h->avctx->color_primaries = sps->color_primaries;
  950. h->avctx->color_trc = sps->color_trc;
  951. h->avctx->colorspace = sps->colorspace;
  952. }
  953. }
  954. if (h->sei.alternative_transfer.present &&
  955. av_color_transfer_name(h->sei.alternative_transfer.preferred_transfer_characteristics) &&
  956. h->sei.alternative_transfer.preferred_transfer_characteristics != AVCOL_TRC_UNSPECIFIED) {
  957. h->avctx->color_trc = h->sei.alternative_transfer.preferred_transfer_characteristics;
  958. }
  959. }
  960. h->avctx->chroma_sample_location = sps->chroma_location;
  961. if (!h->context_initialized || must_reinit || needs_reinit) {
  962. int flush_changes = h->context_initialized;
  963. h->context_initialized = 0;
  964. if (sl != h->slice_ctx) {
  965. av_log(h->avctx, AV_LOG_ERROR,
  966. "changing width %d -> %d / height %d -> %d on "
  967. "slice %d\n",
  968. h->width, h->avctx->coded_width,
  969. h->height, h->avctx->coded_height,
  970. h->current_slice + 1);
  971. return AVERROR_INVALIDDATA;
  972. }
  973. av_assert1(first_slice);
  974. if (flush_changes)
  975. ff_h264_flush_change(h);
  976. if ((ret = get_pixel_format(h, 1)) < 0)
  977. return ret;
  978. h->avctx->pix_fmt = ret;
  979. av_log(h->avctx, AV_LOG_VERBOSE, "Reinit context to %dx%d, "
  980. "pix_fmt: %s\n", h->width, h->height, av_get_pix_fmt_name(h->avctx->pix_fmt));
  981. if ((ret = h264_slice_header_init(h)) < 0) {
  982. av_log(h->avctx, AV_LOG_ERROR,
  983. "h264_slice_header_init() failed\n");
  984. return ret;
  985. }
  986. }
  987. return 0;
  988. }
  989. static int h264_export_frame_props(H264Context *h)
  990. {
  991. const SPS *sps = h->ps.sps;
  992. H264Picture *cur = h->cur_pic_ptr;
  993. AVFrame *out = cur->f;
  994. out->interlaced_frame = 0;
  995. out->repeat_pict = 0;
  996. /* Signal interlacing information externally. */
  997. /* Prioritize picture timing SEI information over used
  998. * decoding process if it exists. */
  999. if (h->sei.picture_timing.present) {
  1000. int ret = ff_h264_sei_process_picture_timing(&h->sei.picture_timing, sps,
  1001. h->avctx);
  1002. if (ret < 0) {
  1003. av_log(h->avctx, AV_LOG_ERROR, "Error processing a picture timing SEI\n");
  1004. if (h->avctx->err_recognition & AV_EF_EXPLODE)
  1005. return ret;
  1006. h->sei.picture_timing.present = 0;
  1007. }
  1008. }
  1009. if (sps->pic_struct_present_flag && h->sei.picture_timing.present) {
  1010. H264SEIPictureTiming *pt = &h->sei.picture_timing;
  1011. switch (pt->pic_struct) {
  1012. case H264_SEI_PIC_STRUCT_FRAME:
  1013. break;
  1014. case H264_SEI_PIC_STRUCT_TOP_FIELD:
  1015. case H264_SEI_PIC_STRUCT_BOTTOM_FIELD:
  1016. out->interlaced_frame = 1;
  1017. break;
  1018. case H264_SEI_PIC_STRUCT_TOP_BOTTOM:
  1019. case H264_SEI_PIC_STRUCT_BOTTOM_TOP:
  1020. if (FIELD_OR_MBAFF_PICTURE(h))
  1021. out->interlaced_frame = 1;
  1022. else
  1023. // try to flag soft telecine progressive
  1024. out->interlaced_frame = h->prev_interlaced_frame;
  1025. break;
  1026. case H264_SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
  1027. case H264_SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
  1028. /* Signal the possibility of telecined film externally
  1029. * (pic_struct 5,6). From these hints, let the applications
  1030. * decide if they apply deinterlacing. */
  1031. out->repeat_pict = 1;
  1032. break;
  1033. case H264_SEI_PIC_STRUCT_FRAME_DOUBLING:
  1034. out->repeat_pict = 2;
  1035. break;
  1036. case H264_SEI_PIC_STRUCT_FRAME_TRIPLING:
  1037. out->repeat_pict = 4;
  1038. break;
  1039. }
  1040. if ((pt->ct_type & 3) &&
  1041. pt->pic_struct <= H264_SEI_PIC_STRUCT_BOTTOM_TOP)
  1042. out->interlaced_frame = (pt->ct_type & (1 << 1)) != 0;
  1043. } else {
  1044. /* Derive interlacing flag from used decoding process. */
  1045. out->interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
  1046. }
  1047. h->prev_interlaced_frame = out->interlaced_frame;
  1048. if (cur->field_poc[0] != cur->field_poc[1]) {
  1049. /* Derive top_field_first from field pocs. */
  1050. out->top_field_first = cur->field_poc[0] < cur->field_poc[1];
  1051. } else {
  1052. if (sps->pic_struct_present_flag && h->sei.picture_timing.present) {
  1053. /* Use picture timing SEI information. Even if it is a
  1054. * information of a past frame, better than nothing. */
  1055. if (h->sei.picture_timing.pic_struct == H264_SEI_PIC_STRUCT_TOP_BOTTOM ||
  1056. h->sei.picture_timing.pic_struct == H264_SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
  1057. out->top_field_first = 1;
  1058. else
  1059. out->top_field_first = 0;
  1060. } else if (out->interlaced_frame) {
  1061. /* Default to top field first when pic_struct_present_flag
  1062. * is not set but interlaced frame detected */
  1063. out->top_field_first = 1;
  1064. } else {
  1065. /* Most likely progressive */
  1066. out->top_field_first = 0;
  1067. }
  1068. }
  1069. if (h->sei.frame_packing.present &&
  1070. h->sei.frame_packing.arrangement_type <= 6 &&
  1071. h->sei.frame_packing.content_interpretation_type > 0 &&
  1072. h->sei.frame_packing.content_interpretation_type < 3) {
  1073. H264SEIFramePacking *fp = &h->sei.frame_packing;
  1074. AVStereo3D *stereo = av_stereo3d_create_side_data(out);
  1075. if (stereo) {
  1076. switch (fp->arrangement_type) {
  1077. case H264_SEI_FPA_TYPE_CHECKERBOARD:
  1078. stereo->type = AV_STEREO3D_CHECKERBOARD;
  1079. break;
  1080. case H264_SEI_FPA_TYPE_INTERLEAVE_COLUMN:
  1081. stereo->type = AV_STEREO3D_COLUMNS;
  1082. break;
  1083. case H264_SEI_FPA_TYPE_INTERLEAVE_ROW:
  1084. stereo->type = AV_STEREO3D_LINES;
  1085. break;
  1086. case H264_SEI_FPA_TYPE_SIDE_BY_SIDE:
  1087. if (fp->quincunx_sampling_flag)
  1088. stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
  1089. else
  1090. stereo->type = AV_STEREO3D_SIDEBYSIDE;
  1091. break;
  1092. case H264_SEI_FPA_TYPE_TOP_BOTTOM:
  1093. stereo->type = AV_STEREO3D_TOPBOTTOM;
  1094. break;
  1095. case H264_SEI_FPA_TYPE_INTERLEAVE_TEMPORAL:
  1096. stereo->type = AV_STEREO3D_FRAMESEQUENCE;
  1097. break;
  1098. case H264_SEI_FPA_TYPE_2D:
  1099. stereo->type = AV_STEREO3D_2D;
  1100. break;
  1101. }
  1102. if (fp->content_interpretation_type == 2)
  1103. stereo->flags = AV_STEREO3D_FLAG_INVERT;
  1104. if (fp->arrangement_type == H264_SEI_FPA_TYPE_INTERLEAVE_TEMPORAL) {
  1105. if (fp->current_frame_is_frame0_flag)
  1106. stereo->view = AV_STEREO3D_VIEW_LEFT;
  1107. else
  1108. stereo->view = AV_STEREO3D_VIEW_RIGHT;
  1109. }
  1110. }
  1111. }
  1112. if (h->sei.display_orientation.present &&
  1113. (h->sei.display_orientation.anticlockwise_rotation ||
  1114. h->sei.display_orientation.hflip ||
  1115. h->sei.display_orientation.vflip)) {
  1116. H264SEIDisplayOrientation *o = &h->sei.display_orientation;
  1117. double angle = o->anticlockwise_rotation * 360 / (double) (1 << 16);
  1118. AVFrameSideData *rotation = av_frame_new_side_data(out,
  1119. AV_FRAME_DATA_DISPLAYMATRIX,
  1120. sizeof(int32_t) * 9);
  1121. if (rotation) {
  1122. av_display_rotation_set((int32_t *)rotation->data, angle);
  1123. av_display_matrix_flip((int32_t *)rotation->data,
  1124. o->hflip, o->vflip);
  1125. }
  1126. }
  1127. if (h->sei.afd.present) {
  1128. AVFrameSideData *sd = av_frame_new_side_data(out, AV_FRAME_DATA_AFD,
  1129. sizeof(uint8_t));
  1130. if (sd) {
  1131. *sd->data = h->sei.afd.active_format_description;
  1132. h->sei.afd.present = 0;
  1133. }
  1134. }
  1135. if (h->sei.a53_caption.buf_ref) {
  1136. H264SEIA53Caption *a53 = &h->sei.a53_caption;
  1137. AVFrameSideData *sd = av_frame_new_side_data_from_buf(out, AV_FRAME_DATA_A53_CC, a53->buf_ref);
  1138. if (!sd)
  1139. av_buffer_unref(&a53->buf_ref);
  1140. a53->buf_ref = NULL;
  1141. h->avctx->properties |= FF_CODEC_PROPERTY_CLOSED_CAPTIONS;
  1142. }
  1143. for (int i = 0; i < h->sei.unregistered.nb_buf_ref; i++) {
  1144. H264SEIUnregistered *unreg = &h->sei.unregistered;
  1145. if (unreg->buf_ref[i]) {
  1146. AVFrameSideData *sd = av_frame_new_side_data_from_buf(out,
  1147. AV_FRAME_DATA_SEI_UNREGISTERED,
  1148. unreg->buf_ref[i]);
  1149. if (!sd)
  1150. av_buffer_unref(&unreg->buf_ref[i]);
  1151. unreg->buf_ref[i] = NULL;
  1152. }
  1153. }
  1154. h->sei.unregistered.nb_buf_ref = 0;
  1155. if (h->sei.picture_timing.timecode_cnt > 0) {
  1156. uint32_t *tc_sd;
  1157. char tcbuf[AV_TIMECODE_STR_SIZE];
  1158. AVFrameSideData *tcside = av_frame_new_side_data(out,
  1159. AV_FRAME_DATA_S12M_TIMECODE,
  1160. sizeof(uint32_t)*4);
  1161. if (!tcside)
  1162. return AVERROR(ENOMEM);
  1163. tc_sd = (uint32_t*)tcside->data;
  1164. tc_sd[0] = h->sei.picture_timing.timecode_cnt;
  1165. for (int i = 0; i < tc_sd[0]; i++) {
  1166. int drop = h->sei.picture_timing.timecode[i].dropframe;
  1167. int hh = h->sei.picture_timing.timecode[i].hours;
  1168. int mm = h->sei.picture_timing.timecode[i].minutes;
  1169. int ss = h->sei.picture_timing.timecode[i].seconds;
  1170. int ff = h->sei.picture_timing.timecode[i].frame;
  1171. tc_sd[i + 1] = av_timecode_get_smpte(h->avctx->framerate, drop, hh, mm, ss, ff);
  1172. av_timecode_make_smpte_tc_string2(tcbuf, h->avctx->framerate, tc_sd[i + 1], 0, 0);
  1173. av_dict_set(&out->metadata, "timecode", tcbuf, 0);
  1174. }
  1175. h->sei.picture_timing.timecode_cnt = 0;
  1176. }
  1177. return 0;
  1178. }
  1179. static int h264_select_output_frame(H264Context *h)
  1180. {
  1181. const SPS *sps = h->ps.sps;
  1182. H264Picture *out = h->cur_pic_ptr;
  1183. H264Picture *cur = h->cur_pic_ptr;
  1184. int i, pics, out_of_order, out_idx;
  1185. cur->mmco_reset = h->mmco_reset;
  1186. h->mmco_reset = 0;
  1187. if (sps->bitstream_restriction_flag ||
  1188. h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
  1189. h->avctx->has_b_frames = FFMAX(h->avctx->has_b_frames, sps->num_reorder_frames);
  1190. }
  1191. for (i = 0; 1; i++) {
  1192. if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
  1193. if(i)
  1194. h->last_pocs[i-1] = cur->poc;
  1195. break;
  1196. } else if(i) {
  1197. h->last_pocs[i-1]= h->last_pocs[i];
  1198. }
  1199. }
  1200. out_of_order = MAX_DELAYED_PIC_COUNT - i;
  1201. if( cur->f->pict_type == AV_PICTURE_TYPE_B
  1202. || (h->last_pocs[MAX_DELAYED_PIC_COUNT-2] > INT_MIN && h->last_pocs[MAX_DELAYED_PIC_COUNT-1] - (int64_t)h->last_pocs[MAX_DELAYED_PIC_COUNT-2] > 2))
  1203. out_of_order = FFMAX(out_of_order, 1);
  1204. if (out_of_order == MAX_DELAYED_PIC_COUNT) {
  1205. av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
  1206. for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
  1207. h->last_pocs[i] = INT_MIN;
  1208. h->last_pocs[0] = cur->poc;
  1209. cur->mmco_reset = 1;
  1210. } else if(h->avctx->has_b_frames < out_of_order && !sps->bitstream_restriction_flag){
  1211. int loglevel = h->avctx->frame_number > 1 ? AV_LOG_WARNING : AV_LOG_VERBOSE;
  1212. av_log(h->avctx, loglevel, "Increasing reorder buffer to %d\n", out_of_order);
  1213. h->avctx->has_b_frames = out_of_order;
  1214. }
  1215. pics = 0;
  1216. while (h->delayed_pic[pics])
  1217. pics++;
  1218. av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
  1219. h->delayed_pic[pics++] = cur;
  1220. if (cur->reference == 0)
  1221. cur->reference = DELAYED_PIC_REF;
  1222. out = h->delayed_pic[0];
  1223. out_idx = 0;
  1224. for (i = 1; h->delayed_pic[i] &&
  1225. !h->delayed_pic[i]->f->key_frame &&
  1226. !h->delayed_pic[i]->mmco_reset;
  1227. i++)
  1228. if (h->delayed_pic[i]->poc < out->poc) {
  1229. out = h->delayed_pic[i];
  1230. out_idx = i;
  1231. }
  1232. if (h->avctx->has_b_frames == 0 &&
  1233. (h->delayed_pic[0]->f->key_frame || h->delayed_pic[0]->mmco_reset))
  1234. h->next_outputed_poc = INT_MIN;
  1235. out_of_order = out->poc < h->next_outputed_poc;
  1236. if (out_of_order || pics > h->avctx->has_b_frames) {
  1237. out->reference &= ~DELAYED_PIC_REF;
  1238. for (i = out_idx; h->delayed_pic[i]; i++)
  1239. h->delayed_pic[i] = h->delayed_pic[i + 1];
  1240. }
  1241. if (!out_of_order && pics > h->avctx->has_b_frames) {
  1242. h->next_output_pic = out;
  1243. if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f->key_frame || h->delayed_pic[0]->mmco_reset)) {
  1244. h->next_outputed_poc = INT_MIN;
  1245. } else
  1246. h->next_outputed_poc = out->poc;
  1247. if (out->recovered) {
  1248. // We have reached an recovery point and all frames after it in
  1249. // display order are "recovered".
  1250. h->frame_recovered |= FRAME_RECOVERED_SEI;
  1251. }
  1252. out->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
  1253. if (!out->recovered) {
  1254. if (!(h->avctx->flags & AV_CODEC_FLAG_OUTPUT_CORRUPT) &&
  1255. !(h->avctx->flags2 & AV_CODEC_FLAG2_SHOW_ALL)) {
  1256. h->next_output_pic = NULL;
  1257. } else {
  1258. out->f->flags |= AV_FRAME_FLAG_CORRUPT;
  1259. }
  1260. }
  1261. } else {
  1262. av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
  1263. }
  1264. return 0;
  1265. }
  1266. /* This function is called right after decoding the slice header for a first
  1267. * slice in a field (or a frame). It decides whether we are decoding a new frame
  1268. * or a second field in a pair and does the necessary setup.
  1269. */
  1270. static int h264_field_start(H264Context *h, const H264SliceContext *sl,
  1271. const H2645NAL *nal, int first_slice)
  1272. {
  1273. int i;
  1274. const SPS *sps;
  1275. int last_pic_structure, last_pic_droppable, ret;
  1276. ret = h264_init_ps(h, sl, first_slice);
  1277. if (ret < 0)
  1278. return ret;
  1279. sps = h->ps.sps;
  1280. if (sps && sps->bitstream_restriction_flag &&
  1281. h->avctx->has_b_frames < sps->num_reorder_frames) {
  1282. h->avctx->has_b_frames = sps->num_reorder_frames;
  1283. }
  1284. last_pic_droppable = h->droppable;
  1285. last_pic_structure = h->picture_structure;
  1286. h->droppable = (nal->ref_idc == 0);
  1287. h->picture_structure = sl->picture_structure;
  1288. h->poc.frame_num = sl->frame_num;
  1289. h->poc.poc_lsb = sl->poc_lsb;
  1290. h->poc.delta_poc_bottom = sl->delta_poc_bottom;
  1291. h->poc.delta_poc[0] = sl->delta_poc[0];
  1292. h->poc.delta_poc[1] = sl->delta_poc[1];
  1293. /* Shorten frame num gaps so we don't have to allocate reference
  1294. * frames just to throw them away */
  1295. if (h->poc.frame_num != h->poc.prev_frame_num) {
  1296. int unwrap_prev_frame_num = h->poc.prev_frame_num;
  1297. int max_frame_num = 1 << sps->log2_max_frame_num;
  1298. if (unwrap_prev_frame_num > h->poc.frame_num)
  1299. unwrap_prev_frame_num -= max_frame_num;
  1300. if ((h->poc.frame_num - unwrap_prev_frame_num) > sps->ref_frame_count) {
  1301. unwrap_prev_frame_num = (h->poc.frame_num - sps->ref_frame_count) - 1;
  1302. if (unwrap_prev_frame_num < 0)
  1303. unwrap_prev_frame_num += max_frame_num;
  1304. h->poc.prev_frame_num = unwrap_prev_frame_num;
  1305. }
  1306. }
  1307. /* See if we have a decoded first field looking for a pair...
  1308. * Here, we're using that to see if we should mark previously
  1309. * decode frames as "finished".
  1310. * We have to do that before the "dummy" in-between frame allocation,
  1311. * since that can modify h->cur_pic_ptr. */
  1312. if (h->first_field) {
  1313. int last_field = last_pic_structure == PICT_BOTTOM_FIELD;
  1314. av_assert0(h->cur_pic_ptr);
  1315. av_assert0(h->cur_pic_ptr->f->buf[0]);
  1316. assert(h->cur_pic_ptr->reference != DELAYED_PIC_REF);
  1317. /* Mark old field/frame as completed */
  1318. if (h->cur_pic_ptr->tf.owner[last_field] == h->avctx) {
  1319. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, last_field);
  1320. }
  1321. /* figure out if we have a complementary field pair */
  1322. if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
  1323. /* Previous field is unmatched. Don't display it, but let it
  1324. * remain for reference if marked as such. */
  1325. if (last_pic_structure != PICT_FRAME) {
  1326. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
  1327. last_pic_structure == PICT_TOP_FIELD);
  1328. }
  1329. } else {
  1330. if (h->cur_pic_ptr->frame_num != h->poc.frame_num) {
  1331. /* This and previous field were reference, but had
  1332. * different frame_nums. Consider this field first in
  1333. * pair. Throw away previous field except for reference
  1334. * purposes. */
  1335. if (last_pic_structure != PICT_FRAME) {
  1336. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
  1337. last_pic_structure == PICT_TOP_FIELD);
  1338. }
  1339. } else {
  1340. /* Second field in complementary pair */
  1341. if (!((last_pic_structure == PICT_TOP_FIELD &&
  1342. h->picture_structure == PICT_BOTTOM_FIELD) ||
  1343. (last_pic_structure == PICT_BOTTOM_FIELD &&
  1344. h->picture_structure == PICT_TOP_FIELD))) {
  1345. av_log(h->avctx, AV_LOG_ERROR,
  1346. "Invalid field mode combination %d/%d\n",
  1347. last_pic_structure, h->picture_structure);
  1348. h->picture_structure = last_pic_structure;
  1349. h->droppable = last_pic_droppable;
  1350. return AVERROR_INVALIDDATA;
  1351. } else if (last_pic_droppable != h->droppable) {
  1352. avpriv_request_sample(h->avctx,
  1353. "Found reference and non-reference fields in the same frame, which");
  1354. h->picture_structure = last_pic_structure;
  1355. h->droppable = last_pic_droppable;
  1356. return AVERROR_PATCHWELCOME;
  1357. }
  1358. }
  1359. }
  1360. }
  1361. while (h->poc.frame_num != h->poc.prev_frame_num && !h->first_field &&
  1362. h->poc.frame_num != (h->poc.prev_frame_num + 1) % (1 << sps->log2_max_frame_num)) {
  1363. H264Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
  1364. av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
  1365. h->poc.frame_num, h->poc.prev_frame_num);
  1366. if (!sps->gaps_in_frame_num_allowed_flag)
  1367. for(i=0; i<FF_ARRAY_ELEMS(h->last_pocs); i++)
  1368. h->last_pocs[i] = INT_MIN;
  1369. ret = h264_frame_start(h);
  1370. if (ret < 0) {
  1371. h->first_field = 0;
  1372. return ret;
  1373. }
  1374. h->poc.prev_frame_num++;
  1375. h->poc.prev_frame_num %= 1 << sps->log2_max_frame_num;
  1376. h->cur_pic_ptr->frame_num = h->poc.prev_frame_num;
  1377. h->cur_pic_ptr->invalid_gap = !sps->gaps_in_frame_num_allowed_flag;
  1378. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);
  1379. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);
  1380. h->explicit_ref_marking = 0;
  1381. ret = ff_h264_execute_ref_pic_marking(h);
  1382. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1383. return ret;
  1384. /* Error concealment: If a ref is missing, copy the previous ref
  1385. * in its place.
  1386. * FIXME: Avoiding a memcpy would be nice, but ref handling makes
  1387. * many assumptions about there being no actual duplicates.
  1388. * FIXME: This does not copy padding for out-of-frame motion
  1389. * vectors. Given we are concealing a lost frame, this probably
  1390. * is not noticeable by comparison, but it should be fixed. */
  1391. if (h->short_ref_count) {
  1392. int c[4] = {
  1393. 1<<(h->ps.sps->bit_depth_luma-1),
  1394. 1<<(h->ps.sps->bit_depth_chroma-1),
  1395. 1<<(h->ps.sps->bit_depth_chroma-1),
  1396. -1
  1397. };
  1398. if (prev &&
  1399. h->short_ref[0]->f->width == prev->f->width &&
  1400. h->short_ref[0]->f->height == prev->f->height &&
  1401. h->short_ref[0]->f->format == prev->f->format) {
  1402. ff_thread_await_progress(&prev->tf, INT_MAX, 0);
  1403. if (prev->field_picture)
  1404. ff_thread_await_progress(&prev->tf, INT_MAX, 1);
  1405. ff_thread_release_buffer(h->avctx, &h->short_ref[0]->tf);
  1406. h->short_ref[0]->tf.f = h->short_ref[0]->f;
  1407. ret = ff_thread_ref_frame(&h->short_ref[0]->tf, &prev->tf);
  1408. if (ret < 0)
  1409. return ret;
  1410. h->short_ref[0]->poc = prev->poc + 2U;
  1411. ff_thread_report_progress(&h->short_ref[0]->tf, INT_MAX, 0);
  1412. if (h->short_ref[0]->field_picture)
  1413. ff_thread_report_progress(&h->short_ref[0]->tf, INT_MAX, 1);
  1414. } else if (!h->frame_recovered && !h->avctx->hwaccel)
  1415. ff_color_frame(h->short_ref[0]->f, c);
  1416. h->short_ref[0]->frame_num = h->poc.prev_frame_num;
  1417. }
  1418. }
  1419. /* See if we have a decoded first field looking for a pair...
  1420. * We're using that to see whether to continue decoding in that
  1421. * frame, or to allocate a new one. */
  1422. if (h->first_field) {
  1423. av_assert0(h->cur_pic_ptr);
  1424. av_assert0(h->cur_pic_ptr->f->buf[0]);
  1425. assert(h->cur_pic_ptr->reference != DELAYED_PIC_REF);
  1426. /* figure out if we have a complementary field pair */
  1427. if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
  1428. /* Previous field is unmatched. Don't display it, but let it
  1429. * remain for reference if marked as such. */
  1430. h->missing_fields ++;
  1431. h->cur_pic_ptr = NULL;
  1432. h->first_field = FIELD_PICTURE(h);
  1433. } else {
  1434. h->missing_fields = 0;
  1435. if (h->cur_pic_ptr->frame_num != h->poc.frame_num) {
  1436. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
  1437. h->picture_structure==PICT_BOTTOM_FIELD);
  1438. /* This and the previous field had different frame_nums.
  1439. * Consider this field first in pair. Throw away previous
  1440. * one except for reference purposes. */
  1441. h->first_field = 1;
  1442. h->cur_pic_ptr = NULL;
  1443. } else if (h->cur_pic_ptr->reference & DELAYED_PIC_REF) {
  1444. /* This frame was already output, we cannot draw into it
  1445. * anymore.
  1446. */
  1447. h->first_field = 1;
  1448. h->cur_pic_ptr = NULL;
  1449. } else {
  1450. /* Second field in complementary pair */
  1451. h->first_field = 0;
  1452. }
  1453. }
  1454. } else {
  1455. /* Frame or first field in a potentially complementary pair */
  1456. h->first_field = FIELD_PICTURE(h);
  1457. }
  1458. if (!FIELD_PICTURE(h) || h->first_field) {
  1459. if (h264_frame_start(h) < 0) {
  1460. h->first_field = 0;
  1461. return AVERROR_INVALIDDATA;
  1462. }
  1463. } else {
  1464. int field = h->picture_structure == PICT_BOTTOM_FIELD;
  1465. release_unused_pictures(h, 0);
  1466. h->cur_pic_ptr->tf.owner[field] = h->avctx;
  1467. }
  1468. /* Some macroblocks can be accessed before they're available in case
  1469. * of lost slices, MBAFF or threading. */
  1470. if (FIELD_PICTURE(h)) {
  1471. for(i = (h->picture_structure == PICT_BOTTOM_FIELD); i<h->mb_height; i++)
  1472. memset(h->slice_table + i*h->mb_stride, -1, (h->mb_stride - (i+1==h->mb_height)) * sizeof(*h->slice_table));
  1473. } else {
  1474. memset(h->slice_table, -1,
  1475. (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));
  1476. }
  1477. ret = ff_h264_init_poc(h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc,
  1478. h->ps.sps, &h->poc, h->picture_structure, nal->ref_idc);
  1479. if (ret < 0)
  1480. return ret;
  1481. memcpy(h->mmco, sl->mmco, sl->nb_mmco * sizeof(*h->mmco));
  1482. h->nb_mmco = sl->nb_mmco;
  1483. h->explicit_ref_marking = sl->explicit_ref_marking;
  1484. h->picture_idr = nal->type == H264_NAL_IDR_SLICE;
  1485. if (h->sei.recovery_point.recovery_frame_cnt >= 0) {
  1486. const int sei_recovery_frame_cnt = h->sei.recovery_point.recovery_frame_cnt;
  1487. if (h->poc.frame_num != sei_recovery_frame_cnt || sl->slice_type_nos != AV_PICTURE_TYPE_I)
  1488. h->valid_recovery_point = 1;
  1489. if ( h->recovery_frame < 0
  1490. || av_mod_uintp2(h->recovery_frame - h->poc.frame_num, h->ps.sps->log2_max_frame_num) > sei_recovery_frame_cnt) {
  1491. h->recovery_frame = av_mod_uintp2(h->poc.frame_num + sei_recovery_frame_cnt, h->ps.sps->log2_max_frame_num);
  1492. if (!h->valid_recovery_point)
  1493. h->recovery_frame = h->poc.frame_num;
  1494. }
  1495. }
  1496. h->cur_pic_ptr->f->key_frame |= (nal->type == H264_NAL_IDR_SLICE);
  1497. if (nal->type == H264_NAL_IDR_SLICE ||
  1498. (h->recovery_frame == h->poc.frame_num && nal->ref_idc)) {
  1499. h->recovery_frame = -1;
  1500. h->cur_pic_ptr->recovered = 1;
  1501. }
  1502. // If we have an IDR, all frames after it in decoded order are
  1503. // "recovered".
  1504. if (nal->type == H264_NAL_IDR_SLICE)
  1505. h->frame_recovered |= FRAME_RECOVERED_IDR;
  1506. #if 1
  1507. h->cur_pic_ptr->recovered |= h->frame_recovered;
  1508. #else
  1509. h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
  1510. #endif
  1511. /* Set the frame properties/side data. Only done for the second field in
  1512. * field coded frames, since some SEI information is present for each field
  1513. * and is merged by the SEI parsing code. */
  1514. if (!FIELD_PICTURE(h) || !h->first_field || h->missing_fields > 1) {
  1515. ret = h264_export_frame_props(h);
  1516. if (ret < 0)
  1517. return ret;
  1518. ret = h264_select_output_frame(h);
  1519. if (ret < 0)
  1520. return ret;
  1521. }
  1522. return 0;
  1523. }
  1524. static int h264_slice_header_parse(const H264Context *h, H264SliceContext *sl,
  1525. const H2645NAL *nal)
  1526. {
  1527. const SPS *sps;
  1528. const PPS *pps;
  1529. int ret;
  1530. unsigned int slice_type, tmp, i;
  1531. int field_pic_flag, bottom_field_flag;
  1532. int first_slice = sl == h->slice_ctx && !h->current_slice;
  1533. int picture_structure;
  1534. if (first_slice)
  1535. av_assert0(!h->setup_finished);
  1536. sl->first_mb_addr = get_ue_golomb_long(&sl->gb);
  1537. slice_type = get_ue_golomb_31(&sl->gb);
  1538. if (slice_type > 9) {
  1539. av_log(h->avctx, AV_LOG_ERROR,
  1540. "slice type %d too large at %d\n",
  1541. slice_type, sl->first_mb_addr);
  1542. return AVERROR_INVALIDDATA;
  1543. }
  1544. if (slice_type > 4) {
  1545. slice_type -= 5;
  1546. sl->slice_type_fixed = 1;
  1547. } else
  1548. sl->slice_type_fixed = 0;
  1549. slice_type = ff_h264_golomb_to_pict_type[slice_type];
  1550. sl->slice_type = slice_type;
  1551. sl->slice_type_nos = slice_type & 3;
  1552. if (nal->type == H264_NAL_IDR_SLICE &&
  1553. sl->slice_type_nos != AV_PICTURE_TYPE_I) {
  1554. av_log(h->avctx, AV_LOG_ERROR, "A non-intra slice in an IDR NAL unit.\n");
  1555. return AVERROR_INVALIDDATA;
  1556. }
  1557. sl->pps_id = get_ue_golomb(&sl->gb);
  1558. if (sl->pps_id >= MAX_PPS_COUNT) {
  1559. av_log(h->avctx, AV_LOG_ERROR, "pps_id %u out of range\n", sl->pps_id);
  1560. return AVERROR_INVALIDDATA;
  1561. }
  1562. if (!h->ps.pps_list[sl->pps_id]) {
  1563. av_log(h->avctx, AV_LOG_ERROR,
  1564. "non-existing PPS %u referenced\n",
  1565. sl->pps_id);
  1566. return AVERROR_INVALIDDATA;
  1567. }
  1568. pps = (const PPS*)h->ps.pps_list[sl->pps_id]->data;
  1569. sps = pps->sps;
  1570. sl->frame_num = get_bits(&sl->gb, sps->log2_max_frame_num);
  1571. if (!first_slice) {
  1572. if (h->poc.frame_num != sl->frame_num) {
  1573. av_log(h->avctx, AV_LOG_ERROR, "Frame num change from %d to %d\n",
  1574. h->poc.frame_num, sl->frame_num);
  1575. return AVERROR_INVALIDDATA;
  1576. }
  1577. }
  1578. sl->mb_mbaff = 0;
  1579. if (sps->frame_mbs_only_flag) {
  1580. picture_structure = PICT_FRAME;
  1581. } else {
  1582. if (!sps->direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B) {
  1583. av_log(h->avctx, AV_LOG_ERROR, "This stream was generated by a broken encoder, invalid 8x8 inference\n");
  1584. return -1;
  1585. }
  1586. field_pic_flag = get_bits1(&sl->gb);
  1587. if (field_pic_flag) {
  1588. bottom_field_flag = get_bits1(&sl->gb);
  1589. picture_structure = PICT_TOP_FIELD + bottom_field_flag;
  1590. } else {
  1591. picture_structure = PICT_FRAME;
  1592. }
  1593. }
  1594. sl->picture_structure = picture_structure;
  1595. sl->mb_field_decoding_flag = picture_structure != PICT_FRAME;
  1596. if (picture_structure == PICT_FRAME) {
  1597. sl->curr_pic_num = sl->frame_num;
  1598. sl->max_pic_num = 1 << sps->log2_max_frame_num;
  1599. } else {
  1600. sl->curr_pic_num = 2 * sl->frame_num + 1;
  1601. sl->max_pic_num = 1 << (sps->log2_max_frame_num + 1);
  1602. }
  1603. if (nal->type == H264_NAL_IDR_SLICE)
  1604. get_ue_golomb_long(&sl->gb); /* idr_pic_id */
  1605. if (sps->poc_type == 0) {
  1606. sl->poc_lsb = get_bits(&sl->gb, sps->log2_max_poc_lsb);
  1607. if (pps->pic_order_present == 1 && picture_structure == PICT_FRAME)
  1608. sl->delta_poc_bottom = get_se_golomb(&sl->gb);
  1609. }
  1610. if (sps->poc_type == 1 && !sps->delta_pic_order_always_zero_flag) {
  1611. sl->delta_poc[0] = get_se_golomb(&sl->gb);
  1612. if (pps->pic_order_present == 1 && picture_structure == PICT_FRAME)
  1613. sl->delta_poc[1] = get_se_golomb(&sl->gb);
  1614. }
  1615. sl->redundant_pic_count = 0;
  1616. if (pps->redundant_pic_cnt_present)
  1617. sl->redundant_pic_count = get_ue_golomb(&sl->gb);
  1618. if (sl->slice_type_nos == AV_PICTURE_TYPE_B)
  1619. sl->direct_spatial_mv_pred = get_bits1(&sl->gb);
  1620. ret = ff_h264_parse_ref_count(&sl->list_count, sl->ref_count,
  1621. &sl->gb, pps, sl->slice_type_nos,
  1622. picture_structure, h->avctx);
  1623. if (ret < 0)
  1624. return ret;
  1625. if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {
  1626. ret = ff_h264_decode_ref_pic_list_reordering(sl, h->avctx);
  1627. if (ret < 0) {
  1628. sl->ref_count[1] = sl->ref_count[0] = 0;
  1629. return ret;
  1630. }
  1631. }
  1632. sl->pwt.use_weight = 0;
  1633. for (i = 0; i < 2; i++) {
  1634. sl->pwt.luma_weight_flag[i] = 0;
  1635. sl->pwt.chroma_weight_flag[i] = 0;
  1636. }
  1637. if ((pps->weighted_pred && sl->slice_type_nos == AV_PICTURE_TYPE_P) ||
  1638. (pps->weighted_bipred_idc == 1 &&
  1639. sl->slice_type_nos == AV_PICTURE_TYPE_B)) {
  1640. ret = ff_h264_pred_weight_table(&sl->gb, sps, sl->ref_count,
  1641. sl->slice_type_nos, &sl->pwt,
  1642. picture_structure, h->avctx);
  1643. if (ret < 0)
  1644. return ret;
  1645. }
  1646. sl->explicit_ref_marking = 0;
  1647. if (nal->ref_idc) {
  1648. ret = ff_h264_decode_ref_pic_marking(sl, &sl->gb, nal, h->avctx);
  1649. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1650. return AVERROR_INVALIDDATA;
  1651. }
  1652. if (sl->slice_type_nos != AV_PICTURE_TYPE_I && pps->cabac) {
  1653. tmp = get_ue_golomb_31(&sl->gb);
  1654. if (tmp > 2) {
  1655. av_log(h->avctx, AV_LOG_ERROR, "cabac_init_idc %u overflow\n", tmp);
  1656. return AVERROR_INVALIDDATA;
  1657. }
  1658. sl->cabac_init_idc = tmp;
  1659. }
  1660. sl->last_qscale_diff = 0;
  1661. tmp = pps->init_qp + (unsigned)get_se_golomb(&sl->gb);
  1662. if (tmp > 51 + 6 * (sps->bit_depth_luma - 8)) {
  1663. av_log(h->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
  1664. return AVERROR_INVALIDDATA;
  1665. }
  1666. sl->qscale = tmp;
  1667. sl->chroma_qp[0] = get_chroma_qp(pps, 0, sl->qscale);
  1668. sl->chroma_qp[1] = get_chroma_qp(pps, 1, sl->qscale);
  1669. // FIXME qscale / qp ... stuff
  1670. if (sl->slice_type == AV_PICTURE_TYPE_SP)
  1671. get_bits1(&sl->gb); /* sp_for_switch_flag */
  1672. if (sl->slice_type == AV_PICTURE_TYPE_SP ||
  1673. sl->slice_type == AV_PICTURE_TYPE_SI)
  1674. get_se_golomb(&sl->gb); /* slice_qs_delta */
  1675. sl->deblocking_filter = 1;
  1676. sl->slice_alpha_c0_offset = 0;
  1677. sl->slice_beta_offset = 0;
  1678. if (pps->deblocking_filter_parameters_present) {
  1679. tmp = get_ue_golomb_31(&sl->gb);
  1680. if (tmp > 2) {
  1681. av_log(h->avctx, AV_LOG_ERROR,
  1682. "deblocking_filter_idc %u out of range\n", tmp);
  1683. return AVERROR_INVALIDDATA;
  1684. }
  1685. sl->deblocking_filter = tmp;
  1686. if (sl->deblocking_filter < 2)
  1687. sl->deblocking_filter ^= 1; // 1<->0
  1688. if (sl->deblocking_filter) {
  1689. int slice_alpha_c0_offset_div2 = get_se_golomb(&sl->gb);
  1690. int slice_beta_offset_div2 = get_se_golomb(&sl->gb);
  1691. if (slice_alpha_c0_offset_div2 > 6 ||
  1692. slice_alpha_c0_offset_div2 < -6 ||
  1693. slice_beta_offset_div2 > 6 ||
  1694. slice_beta_offset_div2 < -6) {
  1695. av_log(h->avctx, AV_LOG_ERROR,
  1696. "deblocking filter parameters %d %d out of range\n",
  1697. slice_alpha_c0_offset_div2, slice_beta_offset_div2);
  1698. return AVERROR_INVALIDDATA;
  1699. }
  1700. sl->slice_alpha_c0_offset = slice_alpha_c0_offset_div2 * 2;
  1701. sl->slice_beta_offset = slice_beta_offset_div2 * 2;
  1702. }
  1703. }
  1704. return 0;
  1705. }
  1706. /* do all the per-slice initialization needed before we can start decoding the
  1707. * actual MBs */
  1708. static int h264_slice_init(H264Context *h, H264SliceContext *sl,
  1709. const H2645NAL *nal)
  1710. {
  1711. int i, j, ret = 0;
  1712. if (h->picture_idr && nal->type != H264_NAL_IDR_SLICE) {
  1713. av_log(h->avctx, AV_LOG_ERROR, "Invalid mix of IDR and non-IDR slices\n");
  1714. return AVERROR_INVALIDDATA;
  1715. }
  1716. av_assert1(h->mb_num == h->mb_width * h->mb_height);
  1717. if (sl->first_mb_addr << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num ||
  1718. sl->first_mb_addr >= h->mb_num) {
  1719. av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
  1720. return AVERROR_INVALIDDATA;
  1721. }
  1722. sl->resync_mb_x = sl->mb_x = sl->first_mb_addr % h->mb_width;
  1723. sl->resync_mb_y = sl->mb_y = (sl->first_mb_addr / h->mb_width) <<
  1724. FIELD_OR_MBAFF_PICTURE(h);
  1725. if (h->picture_structure == PICT_BOTTOM_FIELD)
  1726. sl->resync_mb_y = sl->mb_y = sl->mb_y + 1;
  1727. av_assert1(sl->mb_y < h->mb_height);
  1728. ret = ff_h264_build_ref_list(h, sl);
  1729. if (ret < 0)
  1730. return ret;
  1731. if (h->ps.pps->weighted_bipred_idc == 2 &&
  1732. sl->slice_type_nos == AV_PICTURE_TYPE_B) {
  1733. implicit_weight_table(h, sl, -1);
  1734. if (FRAME_MBAFF(h)) {
  1735. implicit_weight_table(h, sl, 0);
  1736. implicit_weight_table(h, sl, 1);
  1737. }
  1738. }
  1739. if (sl->slice_type_nos == AV_PICTURE_TYPE_B && !sl->direct_spatial_mv_pred)
  1740. ff_h264_direct_dist_scale_factor(h, sl);
  1741. if (!h->setup_finished)
  1742. ff_h264_direct_ref_list_init(h, sl);
  1743. if (h->avctx->skip_loop_filter >= AVDISCARD_ALL ||
  1744. (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
  1745. h->nal_unit_type != H264_NAL_IDR_SLICE) ||
  1746. (h->avctx->skip_loop_filter >= AVDISCARD_NONINTRA &&
  1747. sl->slice_type_nos != AV_PICTURE_TYPE_I) ||
  1748. (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&
  1749. sl->slice_type_nos == AV_PICTURE_TYPE_B) ||
  1750. (h->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
  1751. nal->ref_idc == 0))
  1752. sl->deblocking_filter = 0;
  1753. if (sl->deblocking_filter == 1 && h->nb_slice_ctx > 1) {
  1754. if (h->avctx->flags2 & AV_CODEC_FLAG2_FAST) {
  1755. /* Cheat slightly for speed:
  1756. * Do not bother to deblock across slices. */
  1757. sl->deblocking_filter = 2;
  1758. } else {
  1759. h->postpone_filter = 1;
  1760. }
  1761. }
  1762. sl->qp_thresh = 15 -
  1763. FFMIN(sl->slice_alpha_c0_offset, sl->slice_beta_offset) -
  1764. FFMAX3(0,
  1765. h->ps.pps->chroma_qp_index_offset[0],
  1766. h->ps.pps->chroma_qp_index_offset[1]) +
  1767. 6 * (h->ps.sps->bit_depth_luma - 8);
  1768. sl->slice_num = ++h->current_slice;
  1769. if (sl->slice_num)
  1770. h->slice_row[(sl->slice_num-1)&(MAX_SLICES-1)]= sl->resync_mb_y;
  1771. if ( h->slice_row[sl->slice_num&(MAX_SLICES-1)] + 3 >= sl->resync_mb_y
  1772. && h->slice_row[sl->slice_num&(MAX_SLICES-1)] <= sl->resync_mb_y
  1773. && sl->slice_num >= MAX_SLICES) {
  1774. //in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case
  1775. av_log(h->avctx, AV_LOG_WARNING, "Possibly too many slices (%d >= %d), increase MAX_SLICES and recompile if there are artifacts\n", sl->slice_num, MAX_SLICES);
  1776. }
  1777. for (j = 0; j < 2; j++) {
  1778. int id_list[16];
  1779. int *ref2frm = h->ref2frm[sl->slice_num & (MAX_SLICES - 1)][j];
  1780. for (i = 0; i < 16; i++) {
  1781. id_list[i] = 60;
  1782. if (j < sl->list_count && i < sl->ref_count[j] &&
  1783. sl->ref_list[j][i].parent->f->buf[0]) {
  1784. int k;
  1785. AVBuffer *buf = sl->ref_list[j][i].parent->f->buf[0]->buffer;
  1786. for (k = 0; k < h->short_ref_count; k++)
  1787. if (h->short_ref[k]->f->buf[0]->buffer == buf) {
  1788. id_list[i] = k;
  1789. break;
  1790. }
  1791. for (k = 0; k < h->long_ref_count; k++)
  1792. if (h->long_ref[k] && h->long_ref[k]->f->buf[0]->buffer == buf) {
  1793. id_list[i] = h->short_ref_count + k;
  1794. break;
  1795. }
  1796. }
  1797. }
  1798. ref2frm[0] =
  1799. ref2frm[1] = -1;
  1800. for (i = 0; i < 16; i++)
  1801. ref2frm[i + 2] = 4 * id_list[i] + (sl->ref_list[j][i].reference & 3);
  1802. ref2frm[18 + 0] =
  1803. ref2frm[18 + 1] = -1;
  1804. for (i = 16; i < 48; i++)
  1805. ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
  1806. (sl->ref_list[j][i].reference & 3);
  1807. }
  1808. if (h->avctx->debug & FF_DEBUG_PICT_INFO) {
  1809. av_log(h->avctx, AV_LOG_DEBUG,
  1810. "slice:%d %s mb:%d %c%s%s frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d:%d:%d weight:%d%s %s\n",
  1811. sl->slice_num,
  1812. (h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
  1813. sl->mb_y * h->mb_width + sl->mb_x,
  1814. av_get_picture_type_char(sl->slice_type),
  1815. sl->slice_type_fixed ? " fix" : "",
  1816. nal->type == H264_NAL_IDR_SLICE ? " IDR" : "",
  1817. h->poc.frame_num,
  1818. h->cur_pic_ptr->field_poc[0],
  1819. h->cur_pic_ptr->field_poc[1],
  1820. sl->ref_count[0], sl->ref_count[1],
  1821. sl->qscale,
  1822. sl->deblocking_filter,
  1823. sl->slice_alpha_c0_offset, sl->slice_beta_offset,
  1824. sl->pwt.use_weight,
  1825. sl->pwt.use_weight == 1 && sl->pwt.use_weight_chroma ? "c" : "",
  1826. sl->slice_type == AV_PICTURE_TYPE_B ? (sl->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
  1827. }
  1828. return 0;
  1829. }
  1830. int ff_h264_queue_decode_slice(H264Context *h, const H2645NAL *nal)
  1831. {
  1832. H264SliceContext *sl = h->slice_ctx + h->nb_slice_ctx_queued;
  1833. int first_slice = sl == h->slice_ctx && !h->current_slice;
  1834. int ret;
  1835. sl->gb = nal->gb;
  1836. ret = h264_slice_header_parse(h, sl, nal);
  1837. if (ret < 0)
  1838. return ret;
  1839. // discard redundant pictures
  1840. if (sl->redundant_pic_count > 0) {
  1841. sl->ref_count[0] = sl->ref_count[1] = 0;
  1842. return 0;
  1843. }
  1844. if (sl->first_mb_addr == 0 || !h->current_slice) {
  1845. if (h->setup_finished) {
  1846. av_log(h->avctx, AV_LOG_ERROR, "Too many fields\n");
  1847. return AVERROR_INVALIDDATA;
  1848. }
  1849. }
  1850. if (sl->first_mb_addr == 0) { // FIXME better field boundary detection
  1851. if (h->current_slice) {
  1852. // this slice starts a new field
  1853. // first decode any pending queued slices
  1854. if (h->nb_slice_ctx_queued) {
  1855. H264SliceContext tmp_ctx;
  1856. ret = ff_h264_execute_decode_slices(h);
  1857. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  1858. return ret;
  1859. memcpy(&tmp_ctx, h->slice_ctx, sizeof(tmp_ctx));
  1860. memcpy(h->slice_ctx, sl, sizeof(tmp_ctx));
  1861. memcpy(sl, &tmp_ctx, sizeof(tmp_ctx));
  1862. sl = h->slice_ctx;
  1863. }
  1864. if (h->cur_pic_ptr && FIELD_PICTURE(h) && h->first_field) {
  1865. ret = ff_h264_field_end(h, h->slice_ctx, 1);
  1866. if (ret < 0)
  1867. return ret;
  1868. } else if (h->cur_pic_ptr && !FIELD_PICTURE(h) && !h->first_field && h->nal_unit_type == H264_NAL_IDR_SLICE) {
  1869. av_log(h, AV_LOG_WARNING, "Broken frame packetizing\n");
  1870. ret = ff_h264_field_end(h, h->slice_ctx, 1);
  1871. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);
  1872. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);
  1873. h->cur_pic_ptr = NULL;
  1874. if (ret < 0)
  1875. return ret;
  1876. } else
  1877. return AVERROR_INVALIDDATA;
  1878. }
  1879. if (!h->first_field) {
  1880. if (h->cur_pic_ptr && !h->droppable) {
  1881. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
  1882. h->picture_structure == PICT_BOTTOM_FIELD);
  1883. }
  1884. h->cur_pic_ptr = NULL;
  1885. }
  1886. }
  1887. if (!h->current_slice)
  1888. av_assert0(sl == h->slice_ctx);
  1889. if (h->current_slice == 0 && !h->first_field) {
  1890. if (
  1891. (h->avctx->skip_frame >= AVDISCARD_NONREF && !h->nal_ref_idc) ||
  1892. (h->avctx->skip_frame >= AVDISCARD_BIDIR && sl->slice_type_nos == AV_PICTURE_TYPE_B) ||
  1893. (h->avctx->skip_frame >= AVDISCARD_NONINTRA && sl->slice_type_nos != AV_PICTURE_TYPE_I) ||
  1894. (h->avctx->skip_frame >= AVDISCARD_NONKEY && h->nal_unit_type != H264_NAL_IDR_SLICE && h->sei.recovery_point.recovery_frame_cnt < 0) ||
  1895. h->avctx->skip_frame >= AVDISCARD_ALL) {
  1896. return 0;
  1897. }
  1898. }
  1899. if (!first_slice) {
  1900. const PPS *pps = (const PPS*)h->ps.pps_list[sl->pps_id]->data;
  1901. if (h->ps.pps->sps_id != pps->sps_id ||
  1902. h->ps.pps->transform_8x8_mode != pps->transform_8x8_mode /*||
  1903. (h->setup_finished && h->ps.pps != pps)*/) {
  1904. av_log(h->avctx, AV_LOG_ERROR, "PPS changed between slices\n");
  1905. return AVERROR_INVALIDDATA;
  1906. }
  1907. if (h->ps.sps != pps->sps) {
  1908. av_log(h->avctx, AV_LOG_ERROR,
  1909. "SPS changed in the middle of the frame\n");
  1910. return AVERROR_INVALIDDATA;
  1911. }
  1912. }
  1913. if (h->current_slice == 0) {
  1914. ret = h264_field_start(h, sl, nal, first_slice);
  1915. if (ret < 0)
  1916. return ret;
  1917. } else {
  1918. if (h->picture_structure != sl->picture_structure ||
  1919. h->droppable != (nal->ref_idc == 0)) {
  1920. av_log(h->avctx, AV_LOG_ERROR,
  1921. "Changing field mode (%d -> %d) between slices is not allowed\n",
  1922. h->picture_structure, sl->picture_structure);
  1923. return AVERROR_INVALIDDATA;
  1924. } else if (!h->cur_pic_ptr) {
  1925. av_log(h->avctx, AV_LOG_ERROR,
  1926. "unset cur_pic_ptr on slice %d\n",
  1927. h->current_slice + 1);
  1928. return AVERROR_INVALIDDATA;
  1929. }
  1930. }
  1931. ret = h264_slice_init(h, sl, nal);
  1932. if (ret < 0)
  1933. return ret;
  1934. h->nb_slice_ctx_queued++;
  1935. return 0;
  1936. }
  1937. int ff_h264_get_slice_type(const H264SliceContext *sl)
  1938. {
  1939. switch (sl->slice_type) {
  1940. case AV_PICTURE_TYPE_P:
  1941. return 0;
  1942. case AV_PICTURE_TYPE_B:
  1943. return 1;
  1944. case AV_PICTURE_TYPE_I:
  1945. return 2;
  1946. case AV_PICTURE_TYPE_SP:
  1947. return 3;
  1948. case AV_PICTURE_TYPE_SI:
  1949. return 4;
  1950. default:
  1951. return AVERROR_INVALIDDATA;
  1952. }
  1953. }
  1954. static av_always_inline void fill_filter_caches_inter(const H264Context *h,
  1955. H264SliceContext *sl,
  1956. int mb_type, int top_xy,
  1957. int left_xy[LEFT_MBS],
  1958. int top_type,
  1959. int left_type[LEFT_MBS],
  1960. int mb_xy, int list)
  1961. {
  1962. int b_stride = h->b_stride;
  1963. int16_t(*mv_dst)[2] = &sl->mv_cache[list][scan8[0]];
  1964. int8_t *ref_cache = &sl->ref_cache[list][scan8[0]];
  1965. if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
  1966. if (USES_LIST(top_type, list)) {
  1967. const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride;
  1968. const int b8_xy = 4 * top_xy + 2;
  1969. const int *ref2frm = &h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][list][(MB_MBAFF(sl) ? 20 : 2)];
  1970. AV_COPY128(mv_dst - 1 * 8, h->cur_pic.motion_val[list][b_xy + 0]);
  1971. ref_cache[0 - 1 * 8] =
  1972. ref_cache[1 - 1 * 8] = ref2frm[h->cur_pic.ref_index[list][b8_xy + 0]];
  1973. ref_cache[2 - 1 * 8] =
  1974. ref_cache[3 - 1 * 8] = ref2frm[h->cur_pic.ref_index[list][b8_xy + 1]];
  1975. } else {
  1976. AV_ZERO128(mv_dst - 1 * 8);
  1977. AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  1978. }
  1979. if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
  1980. if (USES_LIST(left_type[LTOP], list)) {
  1981. const int b_xy = h->mb2b_xy[left_xy[LTOP]] + 3;
  1982. const int b8_xy = 4 * left_xy[LTOP] + 1;
  1983. const int *ref2frm = &h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][list][(MB_MBAFF(sl) ? 20 : 2)];
  1984. AV_COPY32(mv_dst - 1 + 0, h->cur_pic.motion_val[list][b_xy + b_stride * 0]);
  1985. AV_COPY32(mv_dst - 1 + 8, h->cur_pic.motion_val[list][b_xy + b_stride * 1]);
  1986. AV_COPY32(mv_dst - 1 + 16, h->cur_pic.motion_val[list][b_xy + b_stride * 2]);
  1987. AV_COPY32(mv_dst - 1 + 24, h->cur_pic.motion_val[list][b_xy + b_stride * 3]);
  1988. ref_cache[-1 + 0] =
  1989. ref_cache[-1 + 8] = ref2frm[h->cur_pic.ref_index[list][b8_xy + 2 * 0]];
  1990. ref_cache[-1 + 16] =
  1991. ref_cache[-1 + 24] = ref2frm[h->cur_pic.ref_index[list][b8_xy + 2 * 1]];
  1992. } else {
  1993. AV_ZERO32(mv_dst - 1 + 0);
  1994. AV_ZERO32(mv_dst - 1 + 8);
  1995. AV_ZERO32(mv_dst - 1 + 16);
  1996. AV_ZERO32(mv_dst - 1 + 24);
  1997. ref_cache[-1 + 0] =
  1998. ref_cache[-1 + 8] =
  1999. ref_cache[-1 + 16] =
  2000. ref_cache[-1 + 24] = LIST_NOT_USED;
  2001. }
  2002. }
  2003. }
  2004. if (!USES_LIST(mb_type, list)) {
  2005. fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
  2006. AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  2007. AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  2008. AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  2009. AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  2010. return;
  2011. }
  2012. {
  2013. int8_t *ref = &h->cur_pic.ref_index[list][4 * mb_xy];
  2014. const int *ref2frm = &h->ref2frm[sl->slice_num & (MAX_SLICES - 1)][list][(MB_MBAFF(sl) ? 20 : 2)];
  2015. uint32_t ref01 = (pack16to32(ref2frm[ref[0]], ref2frm[ref[1]]) & 0x00FF00FF) * 0x0101;
  2016. uint32_t ref23 = (pack16to32(ref2frm[ref[2]], ref2frm[ref[3]]) & 0x00FF00FF) * 0x0101;
  2017. AV_WN32A(&ref_cache[0 * 8], ref01);
  2018. AV_WN32A(&ref_cache[1 * 8], ref01);
  2019. AV_WN32A(&ref_cache[2 * 8], ref23);
  2020. AV_WN32A(&ref_cache[3 * 8], ref23);
  2021. }
  2022. {
  2023. int16_t(*mv_src)[2] = &h->cur_pic.motion_val[list][4 * sl->mb_x + 4 * sl->mb_y * b_stride];
  2024. AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
  2025. AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
  2026. AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
  2027. AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
  2028. }
  2029. }
  2030. /**
  2031. * @return non zero if the loop filter can be skipped
  2032. */
  2033. static int fill_filter_caches(const H264Context *h, H264SliceContext *sl, int mb_type)
  2034. {
  2035. const int mb_xy = sl->mb_xy;
  2036. int top_xy, left_xy[LEFT_MBS];
  2037. int top_type, left_type[LEFT_MBS];
  2038. uint8_t *nnz;
  2039. uint8_t *nnz_cache;
  2040. top_xy = mb_xy - (h->mb_stride << MB_FIELD(sl));
  2041. left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
  2042. if (FRAME_MBAFF(h)) {
  2043. const int left_mb_field_flag = IS_INTERLACED(h->cur_pic.mb_type[mb_xy - 1]);
  2044. const int curr_mb_field_flag = IS_INTERLACED(mb_type);
  2045. if (sl->mb_y & 1) {
  2046. if (left_mb_field_flag != curr_mb_field_flag)
  2047. left_xy[LTOP] -= h->mb_stride;
  2048. } else {
  2049. if (curr_mb_field_flag)
  2050. top_xy += h->mb_stride &
  2051. (((h->cur_pic.mb_type[top_xy] >> 7) & 1) - 1);
  2052. if (left_mb_field_flag != curr_mb_field_flag)
  2053. left_xy[LBOT] += h->mb_stride;
  2054. }
  2055. }
  2056. sl->top_mb_xy = top_xy;
  2057. sl->left_mb_xy[LTOP] = left_xy[LTOP];
  2058. sl->left_mb_xy[LBOT] = left_xy[LBOT];
  2059. {
  2060. /* For sufficiently low qp, filtering wouldn't do anything.
  2061. * This is a conservative estimate: could also check beta_offset
  2062. * and more accurate chroma_qp. */
  2063. int qp_thresh = sl->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
  2064. int qp = h->cur_pic.qscale_table[mb_xy];
  2065. if (qp <= qp_thresh &&
  2066. (left_xy[LTOP] < 0 ||
  2067. ((qp + h->cur_pic.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
  2068. (top_xy < 0 ||
  2069. ((qp + h->cur_pic.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
  2070. if (!FRAME_MBAFF(h))
  2071. return 1;
  2072. if ((left_xy[LTOP] < 0 ||
  2073. ((qp + h->cur_pic.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
  2074. (top_xy < h->mb_stride ||
  2075. ((qp + h->cur_pic.qscale_table[top_xy - h->mb_stride] + 1) >> 1) <= qp_thresh))
  2076. return 1;
  2077. }
  2078. }
  2079. top_type = h->cur_pic.mb_type[top_xy];
  2080. left_type[LTOP] = h->cur_pic.mb_type[left_xy[LTOP]];
  2081. left_type[LBOT] = h->cur_pic.mb_type[left_xy[LBOT]];
  2082. if (sl->deblocking_filter == 2) {
  2083. if (h->slice_table[top_xy] != sl->slice_num)
  2084. top_type = 0;
  2085. if (h->slice_table[left_xy[LBOT]] != sl->slice_num)
  2086. left_type[LTOP] = left_type[LBOT] = 0;
  2087. } else {
  2088. if (h->slice_table[top_xy] == 0xFFFF)
  2089. top_type = 0;
  2090. if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
  2091. left_type[LTOP] = left_type[LBOT] = 0;
  2092. }
  2093. sl->top_type = top_type;
  2094. sl->left_type[LTOP] = left_type[LTOP];
  2095. sl->left_type[LBOT] = left_type[LBOT];
  2096. if (IS_INTRA(mb_type))
  2097. return 0;
  2098. fill_filter_caches_inter(h, sl, mb_type, top_xy, left_xy,
  2099. top_type, left_type, mb_xy, 0);
  2100. if (sl->list_count == 2)
  2101. fill_filter_caches_inter(h, sl, mb_type, top_xy, left_xy,
  2102. top_type, left_type, mb_xy, 1);
  2103. nnz = h->non_zero_count[mb_xy];
  2104. nnz_cache = sl->non_zero_count_cache;
  2105. AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
  2106. AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
  2107. AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
  2108. AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
  2109. sl->cbp = h->cbp_table[mb_xy];
  2110. if (top_type) {
  2111. nnz = h->non_zero_count[top_xy];
  2112. AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
  2113. }
  2114. if (left_type[LTOP]) {
  2115. nnz = h->non_zero_count[left_xy[LTOP]];
  2116. nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
  2117. nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
  2118. nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
  2119. nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
  2120. }
  2121. /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
  2122. * from what the loop filter needs */
  2123. if (!CABAC(h) && h->ps.pps->transform_8x8_mode) {
  2124. if (IS_8x8DCT(top_type)) {
  2125. nnz_cache[4 + 8 * 0] =
  2126. nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
  2127. nnz_cache[6 + 8 * 0] =
  2128. nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
  2129. }
  2130. if (IS_8x8DCT(left_type[LTOP])) {
  2131. nnz_cache[3 + 8 * 1] =
  2132. nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
  2133. }
  2134. if (IS_8x8DCT(left_type[LBOT])) {
  2135. nnz_cache[3 + 8 * 3] =
  2136. nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
  2137. }
  2138. if (IS_8x8DCT(mb_type)) {
  2139. nnz_cache[scan8[0]] =
  2140. nnz_cache[scan8[1]] =
  2141. nnz_cache[scan8[2]] =
  2142. nnz_cache[scan8[3]] = (sl->cbp & 0x1000) >> 12;
  2143. nnz_cache[scan8[0 + 4]] =
  2144. nnz_cache[scan8[1 + 4]] =
  2145. nnz_cache[scan8[2 + 4]] =
  2146. nnz_cache[scan8[3 + 4]] = (sl->cbp & 0x2000) >> 12;
  2147. nnz_cache[scan8[0 + 8]] =
  2148. nnz_cache[scan8[1 + 8]] =
  2149. nnz_cache[scan8[2 + 8]] =
  2150. nnz_cache[scan8[3 + 8]] = (sl->cbp & 0x4000) >> 12;
  2151. nnz_cache[scan8[0 + 12]] =
  2152. nnz_cache[scan8[1 + 12]] =
  2153. nnz_cache[scan8[2 + 12]] =
  2154. nnz_cache[scan8[3 + 12]] = (sl->cbp & 0x8000) >> 12;
  2155. }
  2156. }
  2157. return 0;
  2158. }
  2159. static void loop_filter(const H264Context *h, H264SliceContext *sl, int start_x, int end_x)
  2160. {
  2161. uint8_t *dest_y, *dest_cb, *dest_cr;
  2162. int linesize, uvlinesize, mb_x, mb_y;
  2163. const int end_mb_y = sl->mb_y + FRAME_MBAFF(h);
  2164. const int old_slice_type = sl->slice_type;
  2165. const int pixel_shift = h->pixel_shift;
  2166. const int block_h = 16 >> h->chroma_y_shift;
  2167. if (h->postpone_filter)
  2168. return;
  2169. if (sl->deblocking_filter) {
  2170. for (mb_x = start_x; mb_x < end_x; mb_x++)
  2171. for (mb_y = end_mb_y - FRAME_MBAFF(h); mb_y <= end_mb_y; mb_y++) {
  2172. int mb_xy, mb_type;
  2173. mb_xy = sl->mb_xy = mb_x + mb_y * h->mb_stride;
  2174. mb_type = h->cur_pic.mb_type[mb_xy];
  2175. if (FRAME_MBAFF(h))
  2176. sl->mb_mbaff =
  2177. sl->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
  2178. sl->mb_x = mb_x;
  2179. sl->mb_y = mb_y;
  2180. dest_y = h->cur_pic.f->data[0] +
  2181. ((mb_x << pixel_shift) + mb_y * sl->linesize) * 16;
  2182. dest_cb = h->cur_pic.f->data[1] +
  2183. (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
  2184. mb_y * sl->uvlinesize * block_h;
  2185. dest_cr = h->cur_pic.f->data[2] +
  2186. (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
  2187. mb_y * sl->uvlinesize * block_h;
  2188. // FIXME simplify above
  2189. if (MB_FIELD(sl)) {
  2190. linesize = sl->mb_linesize = sl->linesize * 2;
  2191. uvlinesize = sl->mb_uvlinesize = sl->uvlinesize * 2;
  2192. if (mb_y & 1) { // FIXME move out of this function?
  2193. dest_y -= sl->linesize * 15;
  2194. dest_cb -= sl->uvlinesize * (block_h - 1);
  2195. dest_cr -= sl->uvlinesize * (block_h - 1);
  2196. }
  2197. } else {
  2198. linesize = sl->mb_linesize = sl->linesize;
  2199. uvlinesize = sl->mb_uvlinesize = sl->uvlinesize;
  2200. }
  2201. backup_mb_border(h, sl, dest_y, dest_cb, dest_cr, linesize,
  2202. uvlinesize, 0);
  2203. if (fill_filter_caches(h, sl, mb_type))
  2204. continue;
  2205. sl->chroma_qp[0] = get_chroma_qp(h->ps.pps, 0, h->cur_pic.qscale_table[mb_xy]);
  2206. sl->chroma_qp[1] = get_chroma_qp(h->ps.pps, 1, h->cur_pic.qscale_table[mb_xy]);
  2207. if (FRAME_MBAFF(h)) {
  2208. ff_h264_filter_mb(h, sl, mb_x, mb_y, dest_y, dest_cb, dest_cr,
  2209. linesize, uvlinesize);
  2210. } else {
  2211. ff_h264_filter_mb_fast(h, sl, mb_x, mb_y, dest_y, dest_cb,
  2212. dest_cr, linesize, uvlinesize);
  2213. }
  2214. }
  2215. }
  2216. sl->slice_type = old_slice_type;
  2217. sl->mb_x = end_x;
  2218. sl->mb_y = end_mb_y - FRAME_MBAFF(h);
  2219. sl->chroma_qp[0] = get_chroma_qp(h->ps.pps, 0, sl->qscale);
  2220. sl->chroma_qp[1] = get_chroma_qp(h->ps.pps, 1, sl->qscale);
  2221. }
  2222. static void predict_field_decoding_flag(const H264Context *h, H264SliceContext *sl)
  2223. {
  2224. const int mb_xy = sl->mb_x + sl->mb_y * h->mb_stride;
  2225. int mb_type = (h->slice_table[mb_xy - 1] == sl->slice_num) ?
  2226. h->cur_pic.mb_type[mb_xy - 1] :
  2227. (h->slice_table[mb_xy - h->mb_stride] == sl->slice_num) ?
  2228. h->cur_pic.mb_type[mb_xy - h->mb_stride] : 0;
  2229. sl->mb_mbaff = sl->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
  2230. }
  2231. /**
  2232. * Draw edges and report progress for the last MB row.
  2233. */
  2234. static void decode_finish_row(const H264Context *h, H264SliceContext *sl)
  2235. {
  2236. int top = 16 * (sl->mb_y >> FIELD_PICTURE(h));
  2237. int pic_height = 16 * h->mb_height >> FIELD_PICTURE(h);
  2238. int height = 16 << FRAME_MBAFF(h);
  2239. int deblock_border = (16 + 4) << FRAME_MBAFF(h);
  2240. if (sl->deblocking_filter) {
  2241. if ((top + height) >= pic_height)
  2242. height += deblock_border;
  2243. top -= deblock_border;
  2244. }
  2245. if (top >= pic_height || (top + height) < 0)
  2246. return;
  2247. height = FFMIN(height, pic_height - top);
  2248. if (top < 0) {
  2249. height = top + height;
  2250. top = 0;
  2251. }
  2252. ff_h264_draw_horiz_band(h, sl, top, height);
  2253. if (h->droppable || sl->h264->slice_ctx[0].er.error_occurred)
  2254. return;
  2255. ff_thread_report_progress(&h->cur_pic_ptr->tf, top + height - 1,
  2256. h->picture_structure == PICT_BOTTOM_FIELD);
  2257. }
  2258. static void er_add_slice(H264SliceContext *sl,
  2259. int startx, int starty,
  2260. int endx, int endy, int status)
  2261. {
  2262. if (!sl->h264->enable_er)
  2263. return;
  2264. if (CONFIG_ERROR_RESILIENCE) {
  2265. ERContext *er = &sl->h264->slice_ctx[0].er;
  2266. ff_er_add_slice(er, startx, starty, endx, endy, status);
  2267. }
  2268. }
  2269. static int decode_slice(struct AVCodecContext *avctx, void *arg)
  2270. {
  2271. H264SliceContext *sl = arg;
  2272. const H264Context *h = sl->h264;
  2273. int lf_x_start = sl->mb_x;
  2274. int orig_deblock = sl->deblocking_filter;
  2275. int ret;
  2276. sl->linesize = h->cur_pic_ptr->f->linesize[0];
  2277. sl->uvlinesize = h->cur_pic_ptr->f->linesize[1];
  2278. ret = alloc_scratch_buffers(sl, sl->linesize);
  2279. if (ret < 0)
  2280. return ret;
  2281. sl->mb_skip_run = -1;
  2282. av_assert0(h->block_offset[15] == (4 * ((scan8[15] - scan8[0]) & 7) << h->pixel_shift) + 4 * sl->linesize * ((scan8[15] - scan8[0]) >> 3));
  2283. if (h->postpone_filter)
  2284. sl->deblocking_filter = 0;
  2285. sl->is_complex = FRAME_MBAFF(h) || h->picture_structure != PICT_FRAME ||
  2286. (CONFIG_GRAY && (h->flags & AV_CODEC_FLAG_GRAY));
  2287. if (!(h->avctx->active_thread_type & FF_THREAD_SLICE) && h->picture_structure == PICT_FRAME && h->slice_ctx[0].er.error_status_table) {
  2288. const int start_i = av_clip(sl->resync_mb_x + sl->resync_mb_y * h->mb_width, 0, h->mb_num - 1);
  2289. if (start_i) {
  2290. int prev_status = h->slice_ctx[0].er.error_status_table[h->slice_ctx[0].er.mb_index2xy[start_i - 1]];
  2291. prev_status &= ~ VP_START;
  2292. if (prev_status != (ER_MV_END | ER_DC_END | ER_AC_END))
  2293. h->slice_ctx[0].er.error_occurred = 1;
  2294. }
  2295. }
  2296. if (h->ps.pps->cabac) {
  2297. /* realign */
  2298. align_get_bits(&sl->gb);
  2299. /* init cabac */
  2300. ret = ff_init_cabac_decoder(&sl->cabac,
  2301. sl->gb.buffer + get_bits_count(&sl->gb) / 8,
  2302. (get_bits_left(&sl->gb) + 7) / 8);
  2303. if (ret < 0)
  2304. return ret;
  2305. ff_h264_init_cabac_states(h, sl);
  2306. for (;;) {
  2307. int ret, eos;
  2308. if (sl->mb_x + sl->mb_y * h->mb_width >= sl->next_slice_idx) {
  2309. av_log(h->avctx, AV_LOG_ERROR, "Slice overlaps with next at %d\n",
  2310. sl->next_slice_idx);
  2311. er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
  2312. sl->mb_y, ER_MB_ERROR);
  2313. return AVERROR_INVALIDDATA;
  2314. }
  2315. ret = ff_h264_decode_mb_cabac(h, sl);
  2316. if (ret >= 0)
  2317. ff_h264_hl_decode_mb(h, sl);
  2318. // FIXME optimal? or let mb_decode decode 16x32 ?
  2319. if (ret >= 0 && FRAME_MBAFF(h)) {
  2320. sl->mb_y++;
  2321. ret = ff_h264_decode_mb_cabac(h, sl);
  2322. if (ret >= 0)
  2323. ff_h264_hl_decode_mb(h, sl);
  2324. sl->mb_y--;
  2325. }
  2326. eos = get_cabac_terminate(&sl->cabac);
  2327. if ((h->workaround_bugs & FF_BUG_TRUNCATED) &&
  2328. sl->cabac.bytestream > sl->cabac.bytestream_end + 2) {
  2329. er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x - 1,
  2330. sl->mb_y, ER_MB_END);
  2331. if (sl->mb_x >= lf_x_start)
  2332. loop_filter(h, sl, lf_x_start, sl->mb_x + 1);
  2333. goto finish;
  2334. }
  2335. if (sl->cabac.bytestream > sl->cabac.bytestream_end + 2 )
  2336. av_log(h->avctx, AV_LOG_DEBUG, "bytestream overread %"PTRDIFF_SPECIFIER"\n", sl->cabac.bytestream_end - sl->cabac.bytestream);
  2337. if (ret < 0 || sl->cabac.bytestream > sl->cabac.bytestream_end + 4) {
  2338. av_log(h->avctx, AV_LOG_ERROR,
  2339. "error while decoding MB %d %d, bytestream %"PTRDIFF_SPECIFIER"\n",
  2340. sl->mb_x, sl->mb_y,
  2341. sl->cabac.bytestream_end - sl->cabac.bytestream);
  2342. er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
  2343. sl->mb_y, ER_MB_ERROR);
  2344. return AVERROR_INVALIDDATA;
  2345. }
  2346. if (++sl->mb_x >= h->mb_width) {
  2347. loop_filter(h, sl, lf_x_start, sl->mb_x);
  2348. sl->mb_x = lf_x_start = 0;
  2349. decode_finish_row(h, sl);
  2350. ++sl->mb_y;
  2351. if (FIELD_OR_MBAFF_PICTURE(h)) {
  2352. ++sl->mb_y;
  2353. if (FRAME_MBAFF(h) && sl->mb_y < h->mb_height)
  2354. predict_field_decoding_flag(h, sl);
  2355. }
  2356. }
  2357. if (eos || sl->mb_y >= h->mb_height) {
  2358. ff_tlog(h->avctx, "slice end %d %d\n",
  2359. get_bits_count(&sl->gb), sl->gb.size_in_bits);
  2360. er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x - 1,
  2361. sl->mb_y, ER_MB_END);
  2362. if (sl->mb_x > lf_x_start)
  2363. loop_filter(h, sl, lf_x_start, sl->mb_x);
  2364. goto finish;
  2365. }
  2366. }
  2367. } else {
  2368. for (;;) {
  2369. int ret;
  2370. if (sl->mb_x + sl->mb_y * h->mb_width >= sl->next_slice_idx) {
  2371. av_log(h->avctx, AV_LOG_ERROR, "Slice overlaps with next at %d\n",
  2372. sl->next_slice_idx);
  2373. er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
  2374. sl->mb_y, ER_MB_ERROR);
  2375. return AVERROR_INVALIDDATA;
  2376. }
  2377. ret = ff_h264_decode_mb_cavlc(h, sl);
  2378. if (ret >= 0)
  2379. ff_h264_hl_decode_mb(h, sl);
  2380. // FIXME optimal? or let mb_decode decode 16x32 ?
  2381. if (ret >= 0 && FRAME_MBAFF(h)) {
  2382. sl->mb_y++;
  2383. ret = ff_h264_decode_mb_cavlc(h, sl);
  2384. if (ret >= 0)
  2385. ff_h264_hl_decode_mb(h, sl);
  2386. sl->mb_y--;
  2387. }
  2388. if (ret < 0) {
  2389. av_log(h->avctx, AV_LOG_ERROR,
  2390. "error while decoding MB %d %d\n", sl->mb_x, sl->mb_y);
  2391. er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
  2392. sl->mb_y, ER_MB_ERROR);
  2393. return ret;
  2394. }
  2395. if (++sl->mb_x >= h->mb_width) {
  2396. loop_filter(h, sl, lf_x_start, sl->mb_x);
  2397. sl->mb_x = lf_x_start = 0;
  2398. decode_finish_row(h, sl);
  2399. ++sl->mb_y;
  2400. if (FIELD_OR_MBAFF_PICTURE(h)) {
  2401. ++sl->mb_y;
  2402. if (FRAME_MBAFF(h) && sl->mb_y < h->mb_height)
  2403. predict_field_decoding_flag(h, sl);
  2404. }
  2405. if (sl->mb_y >= h->mb_height) {
  2406. ff_tlog(h->avctx, "slice end %d %d\n",
  2407. get_bits_count(&sl->gb), sl->gb.size_in_bits);
  2408. if ( get_bits_left(&sl->gb) == 0
  2409. || get_bits_left(&sl->gb) > 0 && !(h->avctx->err_recognition & AV_EF_AGGRESSIVE)) {
  2410. er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y,
  2411. sl->mb_x - 1, sl->mb_y, ER_MB_END);
  2412. goto finish;
  2413. } else {
  2414. er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y,
  2415. sl->mb_x, sl->mb_y, ER_MB_END);
  2416. return AVERROR_INVALIDDATA;
  2417. }
  2418. }
  2419. }
  2420. if (get_bits_left(&sl->gb) <= 0 && sl->mb_skip_run <= 0) {
  2421. ff_tlog(h->avctx, "slice end %d %d\n",
  2422. get_bits_count(&sl->gb), sl->gb.size_in_bits);
  2423. if (get_bits_left(&sl->gb) == 0) {
  2424. er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y,
  2425. sl->mb_x - 1, sl->mb_y, ER_MB_END);
  2426. if (sl->mb_x > lf_x_start)
  2427. loop_filter(h, sl, lf_x_start, sl->mb_x);
  2428. goto finish;
  2429. } else {
  2430. er_add_slice(sl, sl->resync_mb_x, sl->resync_mb_y, sl->mb_x,
  2431. sl->mb_y, ER_MB_ERROR);
  2432. return AVERROR_INVALIDDATA;
  2433. }
  2434. }
  2435. }
  2436. }
  2437. finish:
  2438. sl->deblocking_filter = orig_deblock;
  2439. return 0;
  2440. }
  2441. /**
  2442. * Call decode_slice() for each context.
  2443. *
  2444. * @param h h264 master context
  2445. */
  2446. int ff_h264_execute_decode_slices(H264Context *h)
  2447. {
  2448. AVCodecContext *const avctx = h->avctx;
  2449. H264SliceContext *sl;
  2450. int context_count = h->nb_slice_ctx_queued;
  2451. int ret = 0;
  2452. int i, j;
  2453. h->slice_ctx[0].next_slice_idx = INT_MAX;
  2454. if (h->avctx->hwaccel || context_count < 1)
  2455. return 0;
  2456. av_assert0(context_count && h->slice_ctx[context_count - 1].mb_y < h->mb_height);
  2457. if (context_count == 1) {
  2458. h->slice_ctx[0].next_slice_idx = h->mb_width * h->mb_height;
  2459. h->postpone_filter = 0;
  2460. ret = decode_slice(avctx, &h->slice_ctx[0]);
  2461. h->mb_y = h->slice_ctx[0].mb_y;
  2462. if (ret < 0)
  2463. goto finish;
  2464. } else {
  2465. av_assert0(context_count > 0);
  2466. for (i = 0; i < context_count; i++) {
  2467. int next_slice_idx = h->mb_width * h->mb_height;
  2468. int slice_idx;
  2469. sl = &h->slice_ctx[i];
  2470. if (CONFIG_ERROR_RESILIENCE) {
  2471. sl->er.error_count = 0;
  2472. }
  2473. /* make sure none of those slices overlap */
  2474. slice_idx = sl->mb_y * h->mb_width + sl->mb_x;
  2475. for (j = 0; j < context_count; j++) {
  2476. H264SliceContext *sl2 = &h->slice_ctx[j];
  2477. int slice_idx2 = sl2->mb_y * h->mb_width + sl2->mb_x;
  2478. if (i == j || slice_idx2 < slice_idx)
  2479. continue;
  2480. next_slice_idx = FFMIN(next_slice_idx, slice_idx2);
  2481. }
  2482. sl->next_slice_idx = next_slice_idx;
  2483. }
  2484. avctx->execute(avctx, decode_slice, h->slice_ctx,
  2485. NULL, context_count, sizeof(h->slice_ctx[0]));
  2486. /* pull back stuff from slices to master context */
  2487. sl = &h->slice_ctx[context_count - 1];
  2488. h->mb_y = sl->mb_y;
  2489. if (CONFIG_ERROR_RESILIENCE) {
  2490. for (i = 1; i < context_count; i++)
  2491. h->slice_ctx[0].er.error_count += h->slice_ctx[i].er.error_count;
  2492. }
  2493. if (h->postpone_filter) {
  2494. h->postpone_filter = 0;
  2495. for (i = 0; i < context_count; i++) {
  2496. int y_end, x_end;
  2497. sl = &h->slice_ctx[i];
  2498. y_end = FFMIN(sl->mb_y + 1, h->mb_height);
  2499. x_end = (sl->mb_y >= h->mb_height) ? h->mb_width : sl->mb_x;
  2500. for (j = sl->resync_mb_y; j < y_end; j += 1 + FIELD_OR_MBAFF_PICTURE(h)) {
  2501. sl->mb_y = j;
  2502. loop_filter(h, sl, j > sl->resync_mb_y ? 0 : sl->resync_mb_x,
  2503. j == y_end - 1 ? x_end : h->mb_width);
  2504. }
  2505. }
  2506. }
  2507. }
  2508. finish:
  2509. h->nb_slice_ctx_queued = 0;
  2510. return ret;
  2511. }