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.

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