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.

2774 lines
104KB

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