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.

5422 lines
202KB

  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 / MPEG4 part10 codec.
  24. * @author Michael Niedermayer <michaelni@gmx.at>
  25. */
  26. #define UNCHECKED_BITSTREAM_READER 1
  27. #include "libavutil/avassert.h"
  28. #include "libavutil/imgutils.h"
  29. #include "libavutil/opt.h"
  30. #include "libavutil/stereo3d.h"
  31. #include "libavutil/timer.h"
  32. #include "internal.h"
  33. #include "cabac.h"
  34. #include "cabac_functions.h"
  35. #include "dsputil.h"
  36. #include "error_resilience.h"
  37. #include "avcodec.h"
  38. #include "mpegvideo.h"
  39. #include "h264.h"
  40. #include "h264data.h"
  41. #include "h264chroma.h"
  42. #include "h264_mvpred.h"
  43. #include "golomb.h"
  44. #include "mathops.h"
  45. #include "rectangle.h"
  46. #include "svq3.h"
  47. #include "thread.h"
  48. #include "vdpau_internal.h"
  49. #include <assert.h>
  50. static void flush_change(H264Context *h);
  51. const uint16_t ff_h264_mb_sizes[4] = { 256, 384, 512, 768 };
  52. static const uint8_t rem6[QP_MAX_NUM + 1] = {
  53. 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
  54. 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
  55. 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2,
  56. 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
  57. 0, 1, 2, 3,
  58. };
  59. static const uint8_t div6[QP_MAX_NUM + 1] = {
  60. 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3,
  61. 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6,
  62. 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10,
  63. 10,10,10,11,11,11,11,11,11,12,12,12,12,12,12,13,13,13, 13, 13, 13,
  64. 14,14,14,14,
  65. };
  66. static const uint8_t field_scan[16+1] = {
  67. 0 + 0 * 4, 0 + 1 * 4, 1 + 0 * 4, 0 + 2 * 4,
  68. 0 + 3 * 4, 1 + 1 * 4, 1 + 2 * 4, 1 + 3 * 4,
  69. 2 + 0 * 4, 2 + 1 * 4, 2 + 2 * 4, 2 + 3 * 4,
  70. 3 + 0 * 4, 3 + 1 * 4, 3 + 2 * 4, 3 + 3 * 4,
  71. };
  72. static const uint8_t field_scan8x8[64+1] = {
  73. 0 + 0 * 8, 0 + 1 * 8, 0 + 2 * 8, 1 + 0 * 8,
  74. 1 + 1 * 8, 0 + 3 * 8, 0 + 4 * 8, 1 + 2 * 8,
  75. 2 + 0 * 8, 1 + 3 * 8, 0 + 5 * 8, 0 + 6 * 8,
  76. 0 + 7 * 8, 1 + 4 * 8, 2 + 1 * 8, 3 + 0 * 8,
  77. 2 + 2 * 8, 1 + 5 * 8, 1 + 6 * 8, 1 + 7 * 8,
  78. 2 + 3 * 8, 3 + 1 * 8, 4 + 0 * 8, 3 + 2 * 8,
  79. 2 + 4 * 8, 2 + 5 * 8, 2 + 6 * 8, 2 + 7 * 8,
  80. 3 + 3 * 8, 4 + 1 * 8, 5 + 0 * 8, 4 + 2 * 8,
  81. 3 + 4 * 8, 3 + 5 * 8, 3 + 6 * 8, 3 + 7 * 8,
  82. 4 + 3 * 8, 5 + 1 * 8, 6 + 0 * 8, 5 + 2 * 8,
  83. 4 + 4 * 8, 4 + 5 * 8, 4 + 6 * 8, 4 + 7 * 8,
  84. 5 + 3 * 8, 6 + 1 * 8, 6 + 2 * 8, 5 + 4 * 8,
  85. 5 + 5 * 8, 5 + 6 * 8, 5 + 7 * 8, 6 + 3 * 8,
  86. 7 + 0 * 8, 7 + 1 * 8, 6 + 4 * 8, 6 + 5 * 8,
  87. 6 + 6 * 8, 6 + 7 * 8, 7 + 2 * 8, 7 + 3 * 8,
  88. 7 + 4 * 8, 7 + 5 * 8, 7 + 6 * 8, 7 + 7 * 8,
  89. };
  90. static const uint8_t field_scan8x8_cavlc[64+1] = {
  91. 0 + 0 * 8, 1 + 1 * 8, 2 + 0 * 8, 0 + 7 * 8,
  92. 2 + 2 * 8, 2 + 3 * 8, 2 + 4 * 8, 3 + 3 * 8,
  93. 3 + 4 * 8, 4 + 3 * 8, 4 + 4 * 8, 5 + 3 * 8,
  94. 5 + 5 * 8, 7 + 0 * 8, 6 + 6 * 8, 7 + 4 * 8,
  95. 0 + 1 * 8, 0 + 3 * 8, 1 + 3 * 8, 1 + 4 * 8,
  96. 1 + 5 * 8, 3 + 1 * 8, 2 + 5 * 8, 4 + 1 * 8,
  97. 3 + 5 * 8, 5 + 1 * 8, 4 + 5 * 8, 6 + 1 * 8,
  98. 5 + 6 * 8, 7 + 1 * 8, 6 + 7 * 8, 7 + 5 * 8,
  99. 0 + 2 * 8, 0 + 4 * 8, 0 + 5 * 8, 2 + 1 * 8,
  100. 1 + 6 * 8, 4 + 0 * 8, 2 + 6 * 8, 5 + 0 * 8,
  101. 3 + 6 * 8, 6 + 0 * 8, 4 + 6 * 8, 6 + 2 * 8,
  102. 5 + 7 * 8, 6 + 4 * 8, 7 + 2 * 8, 7 + 6 * 8,
  103. 1 + 0 * 8, 1 + 2 * 8, 0 + 6 * 8, 3 + 0 * 8,
  104. 1 + 7 * 8, 3 + 2 * 8, 2 + 7 * 8, 4 + 2 * 8,
  105. 3 + 7 * 8, 5 + 2 * 8, 4 + 7 * 8, 5 + 4 * 8,
  106. 6 + 3 * 8, 6 + 5 * 8, 7 + 3 * 8, 7 + 7 * 8,
  107. };
  108. // zigzag_scan8x8_cavlc[i] = zigzag_scan8x8[(i/4) + 16*(i%4)]
  109. static const uint8_t zigzag_scan8x8_cavlc[64+1] = {
  110. 0 + 0 * 8, 1 + 1 * 8, 1 + 2 * 8, 2 + 2 * 8,
  111. 4 + 1 * 8, 0 + 5 * 8, 3 + 3 * 8, 7 + 0 * 8,
  112. 3 + 4 * 8, 1 + 7 * 8, 5 + 3 * 8, 6 + 3 * 8,
  113. 2 + 7 * 8, 6 + 4 * 8, 5 + 6 * 8, 7 + 5 * 8,
  114. 1 + 0 * 8, 2 + 0 * 8, 0 + 3 * 8, 3 + 1 * 8,
  115. 3 + 2 * 8, 0 + 6 * 8, 4 + 2 * 8, 6 + 1 * 8,
  116. 2 + 5 * 8, 2 + 6 * 8, 6 + 2 * 8, 5 + 4 * 8,
  117. 3 + 7 * 8, 7 + 3 * 8, 4 + 7 * 8, 7 + 6 * 8,
  118. 0 + 1 * 8, 3 + 0 * 8, 0 + 4 * 8, 4 + 0 * 8,
  119. 2 + 3 * 8, 1 + 5 * 8, 5 + 1 * 8, 5 + 2 * 8,
  120. 1 + 6 * 8, 3 + 5 * 8, 7 + 1 * 8, 4 + 5 * 8,
  121. 4 + 6 * 8, 7 + 4 * 8, 5 + 7 * 8, 6 + 7 * 8,
  122. 0 + 2 * 8, 2 + 1 * 8, 1 + 3 * 8, 5 + 0 * 8,
  123. 1 + 4 * 8, 2 + 4 * 8, 6 + 0 * 8, 4 + 3 * 8,
  124. 0 + 7 * 8, 4 + 4 * 8, 7 + 2 * 8, 3 + 6 * 8,
  125. 5 + 5 * 8, 6 + 5 * 8, 6 + 6 * 8, 7 + 7 * 8,
  126. };
  127. static const uint8_t dequant4_coeff_init[6][3] = {
  128. { 10, 13, 16 },
  129. { 11, 14, 18 },
  130. { 13, 16, 20 },
  131. { 14, 18, 23 },
  132. { 16, 20, 25 },
  133. { 18, 23, 29 },
  134. };
  135. static const uint8_t dequant8_coeff_init_scan[16] = {
  136. 0, 3, 4, 3, 3, 1, 5, 1, 4, 5, 2, 5, 3, 1, 5, 1
  137. };
  138. static const uint8_t dequant8_coeff_init[6][6] = {
  139. { 20, 18, 32, 19, 25, 24 },
  140. { 22, 19, 35, 21, 28, 26 },
  141. { 26, 23, 42, 24, 33, 31 },
  142. { 28, 25, 45, 26, 35, 33 },
  143. { 32, 28, 51, 30, 40, 38 },
  144. { 36, 32, 58, 34, 46, 43 },
  145. };
  146. static const enum AVPixelFormat h264_hwaccel_pixfmt_list_420[] = {
  147. #if CONFIG_H264_DXVA2_HWACCEL
  148. AV_PIX_FMT_DXVA2_VLD,
  149. #endif
  150. #if CONFIG_H264_VAAPI_HWACCEL
  151. AV_PIX_FMT_VAAPI_VLD,
  152. #endif
  153. #if CONFIG_H264_VDA_HWACCEL
  154. AV_PIX_FMT_VDA_VLD,
  155. #endif
  156. #if CONFIG_H264_VDPAU_HWACCEL
  157. AV_PIX_FMT_VDPAU,
  158. #endif
  159. AV_PIX_FMT_YUV420P,
  160. AV_PIX_FMT_NONE
  161. };
  162. static const enum AVPixelFormat h264_hwaccel_pixfmt_list_jpeg_420[] = {
  163. #if CONFIG_H264_DXVA2_HWACCEL
  164. AV_PIX_FMT_DXVA2_VLD,
  165. #endif
  166. #if CONFIG_H264_VAAPI_HWACCEL
  167. AV_PIX_FMT_VAAPI_VLD,
  168. #endif
  169. #if CONFIG_H264_VDA_HWACCEL
  170. AV_PIX_FMT_VDA_VLD,
  171. #endif
  172. #if CONFIG_H264_VDPAU_HWACCEL
  173. AV_PIX_FMT_VDPAU,
  174. #endif
  175. AV_PIX_FMT_YUVJ420P,
  176. AV_PIX_FMT_NONE
  177. };
  178. int avpriv_h264_has_num_reorder_frames(AVCodecContext *avctx)
  179. {
  180. H264Context *h = avctx->priv_data;
  181. return h ? h->sps.num_reorder_frames : 0;
  182. }
  183. static void h264_er_decode_mb(void *opaque, int ref, int mv_dir, int mv_type,
  184. int (*mv)[2][4][2],
  185. int mb_x, int mb_y, int mb_intra, int mb_skipped)
  186. {
  187. H264Context *h = opaque;
  188. h->mb_x = mb_x;
  189. h->mb_y = mb_y;
  190. h->mb_xy = mb_x + mb_y * h->mb_stride;
  191. memset(h->non_zero_count_cache, 0, sizeof(h->non_zero_count_cache));
  192. av_assert1(ref >= 0);
  193. /* FIXME: It is possible albeit uncommon that slice references
  194. * differ between slices. We take the easy approach and ignore
  195. * it for now. If this turns out to have any relevance in
  196. * practice then correct remapping should be added. */
  197. if (ref >= h->ref_count[0])
  198. ref = 0;
  199. if (!h->ref_list[0][ref].f.data[0]) {
  200. av_log(h->avctx, AV_LOG_DEBUG, "Reference not available for error concealing\n");
  201. ref = 0;
  202. }
  203. if ((h->ref_list[0][ref].reference&3) != 3) {
  204. av_log(h->avctx, AV_LOG_DEBUG, "Reference invalid\n");
  205. return;
  206. }
  207. fill_rectangle(&h->cur_pic.ref_index[0][4 * h->mb_xy],
  208. 2, 2, 2, ref, 1);
  209. fill_rectangle(&h->ref_cache[0][scan8[0]], 4, 4, 8, ref, 1);
  210. fill_rectangle(h->mv_cache[0][scan8[0]], 4, 4, 8,
  211. pack16to32((*mv)[0][0][0], (*mv)[0][0][1]), 4);
  212. h->mb_mbaff =
  213. h->mb_field_decoding_flag = 0;
  214. ff_h264_hl_decode_mb(h);
  215. }
  216. void ff_h264_draw_horiz_band(H264Context *h, int y, int height)
  217. {
  218. AVCodecContext *avctx = h->avctx;
  219. AVFrame *cur = &h->cur_pic.f;
  220. AVFrame *last = h->ref_list[0][0].f.data[0] ? &h->ref_list[0][0].f : NULL;
  221. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
  222. int vshift = desc->log2_chroma_h;
  223. const int field_pic = h->picture_structure != PICT_FRAME;
  224. if (field_pic) {
  225. height <<= 1;
  226. y <<= 1;
  227. }
  228. height = FFMIN(height, avctx->height - y);
  229. if (field_pic && h->first_field && !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD))
  230. return;
  231. if (avctx->draw_horiz_band) {
  232. AVFrame *src;
  233. int offset[AV_NUM_DATA_POINTERS];
  234. int i;
  235. if (cur->pict_type == AV_PICTURE_TYPE_B || h->low_delay ||
  236. (avctx->slice_flags & SLICE_FLAG_CODED_ORDER))
  237. src = cur;
  238. else if (last)
  239. src = last;
  240. else
  241. return;
  242. offset[0] = y * src->linesize[0];
  243. offset[1] =
  244. offset[2] = (y >> vshift) * src->linesize[1];
  245. for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
  246. offset[i] = 0;
  247. emms_c();
  248. avctx->draw_horiz_band(avctx, src, offset,
  249. y, h->picture_structure, height);
  250. }
  251. }
  252. static void unref_picture(H264Context *h, H264Picture *pic)
  253. {
  254. int off = offsetof(H264Picture, tf) + sizeof(pic->tf);
  255. int i;
  256. if (!pic->f.buf[0])
  257. return;
  258. ff_thread_release_buffer(h->avctx, &pic->tf);
  259. av_buffer_unref(&pic->hwaccel_priv_buf);
  260. av_buffer_unref(&pic->qscale_table_buf);
  261. av_buffer_unref(&pic->mb_type_buf);
  262. for (i = 0; i < 2; i++) {
  263. av_buffer_unref(&pic->motion_val_buf[i]);
  264. av_buffer_unref(&pic->ref_index_buf[i]);
  265. }
  266. memset((uint8_t*)pic + off, 0, sizeof(*pic) - off);
  267. }
  268. static void release_unused_pictures(H264Context *h, int remove_current)
  269. {
  270. int i;
  271. /* release non reference frames */
  272. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
  273. if (h->DPB[i].f.buf[0] && !h->DPB[i].reference &&
  274. (remove_current || &h->DPB[i] != h->cur_pic_ptr)) {
  275. unref_picture(h, &h->DPB[i]);
  276. }
  277. }
  278. }
  279. static int ref_picture(H264Context *h, H264Picture *dst, H264Picture *src)
  280. {
  281. int ret, i;
  282. av_assert0(!dst->f.buf[0]);
  283. av_assert0(src->f.buf[0]);
  284. src->tf.f = &src->f;
  285. dst->tf.f = &dst->f;
  286. ret = ff_thread_ref_frame(&dst->tf, &src->tf);
  287. if (ret < 0)
  288. goto fail;
  289. dst->qscale_table_buf = av_buffer_ref(src->qscale_table_buf);
  290. dst->mb_type_buf = av_buffer_ref(src->mb_type_buf);
  291. if (!dst->qscale_table_buf || !dst->mb_type_buf)
  292. goto fail;
  293. dst->qscale_table = src->qscale_table;
  294. dst->mb_type = src->mb_type;
  295. for (i = 0; i < 2; i++) {
  296. dst->motion_val_buf[i] = av_buffer_ref(src->motion_val_buf[i]);
  297. dst->ref_index_buf[i] = av_buffer_ref(src->ref_index_buf[i]);
  298. if (!dst->motion_val_buf[i] || !dst->ref_index_buf[i])
  299. goto fail;
  300. dst->motion_val[i] = src->motion_val[i];
  301. dst->ref_index[i] = src->ref_index[i];
  302. }
  303. if (src->hwaccel_picture_private) {
  304. dst->hwaccel_priv_buf = av_buffer_ref(src->hwaccel_priv_buf);
  305. if (!dst->hwaccel_priv_buf)
  306. goto fail;
  307. dst->hwaccel_picture_private = dst->hwaccel_priv_buf->data;
  308. }
  309. for (i = 0; i < 2; i++)
  310. dst->field_poc[i] = src->field_poc[i];
  311. memcpy(dst->ref_poc, src->ref_poc, sizeof(src->ref_poc));
  312. memcpy(dst->ref_count, src->ref_count, sizeof(src->ref_count));
  313. dst->poc = src->poc;
  314. dst->frame_num = src->frame_num;
  315. dst->mmco_reset = src->mmco_reset;
  316. dst->pic_id = src->pic_id;
  317. dst->long_ref = src->long_ref;
  318. dst->mbaff = src->mbaff;
  319. dst->field_picture = src->field_picture;
  320. dst->needs_realloc = src->needs_realloc;
  321. dst->reference = src->reference;
  322. dst->crop = src->crop;
  323. dst->crop_left = src->crop_left;
  324. dst->crop_top = src->crop_top;
  325. dst->recovered = src->recovered;
  326. dst->invalid_gap = src->invalid_gap;
  327. return 0;
  328. fail:
  329. unref_picture(h, dst);
  330. return ret;
  331. }
  332. static int alloc_scratch_buffers(H264Context *h, int linesize)
  333. {
  334. int alloc_size = FFALIGN(FFABS(linesize) + 32, 32);
  335. if (h->bipred_scratchpad)
  336. return 0;
  337. h->bipred_scratchpad = av_malloc(16 * 6 * alloc_size);
  338. // edge emu needs blocksize + filter length - 1
  339. // (= 21x21 for h264)
  340. h->edge_emu_buffer = av_mallocz(alloc_size * 2 * 21);
  341. if (!h->bipred_scratchpad || !h->edge_emu_buffer) {
  342. av_freep(&h->bipred_scratchpad);
  343. av_freep(&h->edge_emu_buffer);
  344. return AVERROR(ENOMEM);
  345. }
  346. return 0;
  347. }
  348. static int init_table_pools(H264Context *h)
  349. {
  350. const int big_mb_num = h->mb_stride * (h->mb_height + 1) + 1;
  351. const int mb_array_size = h->mb_stride * h->mb_height;
  352. const int b4_stride = h->mb_width * 4 + 1;
  353. const int b4_array_size = b4_stride * h->mb_height * 4;
  354. h->qscale_table_pool = av_buffer_pool_init(big_mb_num + h->mb_stride,
  355. av_buffer_allocz);
  356. h->mb_type_pool = av_buffer_pool_init((big_mb_num + h->mb_stride) *
  357. sizeof(uint32_t), av_buffer_allocz);
  358. h->motion_val_pool = av_buffer_pool_init(2 * (b4_array_size + 4) *
  359. sizeof(int16_t), av_buffer_allocz);
  360. h->ref_index_pool = av_buffer_pool_init(4 * mb_array_size, av_buffer_allocz);
  361. if (!h->qscale_table_pool || !h->mb_type_pool || !h->motion_val_pool ||
  362. !h->ref_index_pool) {
  363. av_buffer_pool_uninit(&h->qscale_table_pool);
  364. av_buffer_pool_uninit(&h->mb_type_pool);
  365. av_buffer_pool_uninit(&h->motion_val_pool);
  366. av_buffer_pool_uninit(&h->ref_index_pool);
  367. return AVERROR(ENOMEM);
  368. }
  369. return 0;
  370. }
  371. static int alloc_picture(H264Context *h, H264Picture *pic)
  372. {
  373. int i, ret = 0;
  374. av_assert0(!pic->f.data[0]);
  375. pic->tf.f = &pic->f;
  376. ret = ff_thread_get_buffer(h->avctx, &pic->tf, pic->reference ?
  377. AV_GET_BUFFER_FLAG_REF : 0);
  378. if (ret < 0)
  379. goto fail;
  380. h->linesize = pic->f.linesize[0];
  381. h->uvlinesize = pic->f.linesize[1];
  382. pic->crop = h->sps.crop;
  383. pic->crop_top = h->sps.crop_top;
  384. pic->crop_left= h->sps.crop_left;
  385. if (h->avctx->hwaccel) {
  386. const AVHWAccel *hwaccel = h->avctx->hwaccel;
  387. av_assert0(!pic->hwaccel_picture_private);
  388. if (hwaccel->priv_data_size) {
  389. pic->hwaccel_priv_buf = av_buffer_allocz(hwaccel->priv_data_size);
  390. if (!pic->hwaccel_priv_buf)
  391. return AVERROR(ENOMEM);
  392. pic->hwaccel_picture_private = pic->hwaccel_priv_buf->data;
  393. }
  394. }
  395. if (!h->avctx->hwaccel && CONFIG_GRAY && h->flags & CODEC_FLAG_GRAY && pic->f.data[2]) {
  396. int h_chroma_shift, v_chroma_shift;
  397. av_pix_fmt_get_chroma_sub_sample(pic->f.format,
  398. &h_chroma_shift, &v_chroma_shift);
  399. for(i=0; i<FF_CEIL_RSHIFT(h->avctx->height, v_chroma_shift); i++) {
  400. memset(pic->f.data[1] + pic->f.linesize[1]*i,
  401. 0x80, FF_CEIL_RSHIFT(h->avctx->width, h_chroma_shift));
  402. memset(pic->f.data[2] + pic->f.linesize[2]*i,
  403. 0x80, FF_CEIL_RSHIFT(h->avctx->width, h_chroma_shift));
  404. }
  405. }
  406. if (!h->qscale_table_pool) {
  407. ret = init_table_pools(h);
  408. if (ret < 0)
  409. goto fail;
  410. }
  411. pic->qscale_table_buf = av_buffer_pool_get(h->qscale_table_pool);
  412. pic->mb_type_buf = av_buffer_pool_get(h->mb_type_pool);
  413. if (!pic->qscale_table_buf || !pic->mb_type_buf)
  414. goto fail;
  415. pic->mb_type = (uint32_t*)pic->mb_type_buf->data + 2 * h->mb_stride + 1;
  416. pic->qscale_table = pic->qscale_table_buf->data + 2 * h->mb_stride + 1;
  417. for (i = 0; i < 2; i++) {
  418. pic->motion_val_buf[i] = av_buffer_pool_get(h->motion_val_pool);
  419. pic->ref_index_buf[i] = av_buffer_pool_get(h->ref_index_pool);
  420. if (!pic->motion_val_buf[i] || !pic->ref_index_buf[i])
  421. goto fail;
  422. pic->motion_val[i] = (int16_t (*)[2])pic->motion_val_buf[i]->data + 4;
  423. pic->ref_index[i] = pic->ref_index_buf[i]->data;
  424. }
  425. return 0;
  426. fail:
  427. unref_picture(h, pic);
  428. return (ret < 0) ? ret : AVERROR(ENOMEM);
  429. }
  430. static inline int pic_is_unused(H264Context *h, H264Picture *pic)
  431. {
  432. if (!pic->f.buf[0])
  433. return 1;
  434. if (pic->needs_realloc && !(pic->reference & DELAYED_PIC_REF))
  435. return 1;
  436. return 0;
  437. }
  438. static int find_unused_picture(H264Context *h)
  439. {
  440. int i;
  441. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) {
  442. if (pic_is_unused(h, &h->DPB[i]))
  443. break;
  444. }
  445. if (i == H264_MAX_PICTURE_COUNT)
  446. return AVERROR_INVALIDDATA;
  447. if (h->DPB[i].needs_realloc) {
  448. h->DPB[i].needs_realloc = 0;
  449. unref_picture(h, &h->DPB[i]);
  450. }
  451. return i;
  452. }
  453. /**
  454. * Check if the top & left blocks are available if needed and
  455. * change the dc mode so it only uses the available blocks.
  456. */
  457. int ff_h264_check_intra4x4_pred_mode(H264Context *h)
  458. {
  459. static const int8_t top[12] = {
  460. -1, 0, LEFT_DC_PRED, -1, -1, -1, -1, -1, 0
  461. };
  462. static const int8_t left[12] = {
  463. 0, -1, TOP_DC_PRED, 0, -1, -1, -1, 0, -1, DC_128_PRED
  464. };
  465. int i;
  466. if (!(h->top_samples_available & 0x8000)) {
  467. for (i = 0; i < 4; i++) {
  468. int status = top[h->intra4x4_pred_mode_cache[scan8[0] + i]];
  469. if (status < 0) {
  470. av_log(h->avctx, AV_LOG_ERROR,
  471. "top block unavailable for requested intra4x4 mode %d at %d %d\n",
  472. status, h->mb_x, h->mb_y);
  473. return AVERROR_INVALIDDATA;
  474. } else if (status) {
  475. h->intra4x4_pred_mode_cache[scan8[0] + i] = status;
  476. }
  477. }
  478. }
  479. if ((h->left_samples_available & 0x8888) != 0x8888) {
  480. static const int mask[4] = { 0x8000, 0x2000, 0x80, 0x20 };
  481. for (i = 0; i < 4; i++)
  482. if (!(h->left_samples_available & mask[i])) {
  483. int status = left[h->intra4x4_pred_mode_cache[scan8[0] + 8 * i]];
  484. if (status < 0) {
  485. av_log(h->avctx, AV_LOG_ERROR,
  486. "left block unavailable for requested intra4x4 mode %d at %d %d\n",
  487. status, h->mb_x, h->mb_y);
  488. return AVERROR_INVALIDDATA;
  489. } else if (status) {
  490. h->intra4x4_pred_mode_cache[scan8[0] + 8 * i] = status;
  491. }
  492. }
  493. }
  494. return 0;
  495. } // FIXME cleanup like ff_h264_check_intra_pred_mode
  496. /**
  497. * Check if the top & left blocks are available if needed and
  498. * change the dc mode so it only uses the available blocks.
  499. */
  500. int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)
  501. {
  502. static const int8_t top[4] = { LEFT_DC_PRED8x8, 1, -1, -1 };
  503. static const int8_t left[5] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };
  504. if (mode > 3U) {
  505. av_log(h->avctx, AV_LOG_ERROR,
  506. "out of range intra chroma pred mode at %d %d\n",
  507. h->mb_x, h->mb_y);
  508. return AVERROR_INVALIDDATA;
  509. }
  510. if (!(h->top_samples_available & 0x8000)) {
  511. mode = top[mode];
  512. if (mode < 0) {
  513. av_log(h->avctx, AV_LOG_ERROR,
  514. "top block unavailable for requested intra mode at %d %d\n",
  515. h->mb_x, h->mb_y);
  516. return AVERROR_INVALIDDATA;
  517. }
  518. }
  519. if ((h->left_samples_available & 0x8080) != 0x8080) {
  520. mode = left[mode];
  521. if (is_chroma && (h->left_samples_available & 0x8080)) {
  522. // mad cow disease mode, aka MBAFF + constrained_intra_pred
  523. mode = ALZHEIMER_DC_L0T_PRED8x8 +
  524. (!(h->left_samples_available & 0x8000)) +
  525. 2 * (mode == DC_128_PRED8x8);
  526. }
  527. if (mode < 0) {
  528. av_log(h->avctx, AV_LOG_ERROR,
  529. "left block unavailable for requested intra mode at %d %d\n",
  530. h->mb_x, h->mb_y);
  531. return AVERROR_INVALIDDATA;
  532. }
  533. }
  534. return mode;
  535. }
  536. const uint8_t *ff_h264_decode_nal(H264Context *h, const uint8_t *src,
  537. int *dst_length, int *consumed, int length)
  538. {
  539. int i, si, di;
  540. uint8_t *dst;
  541. int bufidx;
  542. // src[0]&0x80; // forbidden bit
  543. h->nal_ref_idc = src[0] >> 5;
  544. h->nal_unit_type = src[0] & 0x1F;
  545. src++;
  546. length--;
  547. #define STARTCODE_TEST \
  548. if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) { \
  549. if (src[i + 2] != 3) { \
  550. /* startcode, so we must be past the end */ \
  551. length = i; \
  552. } \
  553. break; \
  554. }
  555. #if HAVE_FAST_UNALIGNED
  556. #define FIND_FIRST_ZERO \
  557. if (i > 0 && !src[i]) \
  558. i--; \
  559. while (src[i]) \
  560. i++
  561. #if HAVE_FAST_64BIT
  562. for (i = 0; i + 1 < length; i += 9) {
  563. if (!((~AV_RN64A(src + i) &
  564. (AV_RN64A(src + i) - 0x0100010001000101ULL)) &
  565. 0x8000800080008080ULL))
  566. continue;
  567. FIND_FIRST_ZERO;
  568. STARTCODE_TEST;
  569. i -= 7;
  570. }
  571. #else
  572. for (i = 0; i + 1 < length; i += 5) {
  573. if (!((~AV_RN32A(src + i) &
  574. (AV_RN32A(src + i) - 0x01000101U)) &
  575. 0x80008080U))
  576. continue;
  577. FIND_FIRST_ZERO;
  578. STARTCODE_TEST;
  579. i -= 3;
  580. }
  581. #endif
  582. #else
  583. for (i = 0; i + 1 < length; i += 2) {
  584. if (src[i])
  585. continue;
  586. if (i > 0 && src[i - 1] == 0)
  587. i--;
  588. STARTCODE_TEST;
  589. }
  590. #endif
  591. // use second escape buffer for inter data
  592. bufidx = h->nal_unit_type == NAL_DPC ? 1 : 0;
  593. si = h->rbsp_buffer_size[bufidx];
  594. av_fast_padded_malloc(&h->rbsp_buffer[bufidx], &h->rbsp_buffer_size[bufidx], length+MAX_MBPAIR_SIZE);
  595. dst = h->rbsp_buffer[bufidx];
  596. if (dst == NULL)
  597. return NULL;
  598. if(i>=length-1){ //no escaped 0
  599. *dst_length= length;
  600. *consumed= length+1; //+1 for the header
  601. if(h->avctx->flags2 & CODEC_FLAG2_FAST){
  602. return src;
  603. }else{
  604. memcpy(dst, src, length);
  605. return dst;
  606. }
  607. }
  608. memcpy(dst, src, i);
  609. si = di = i;
  610. while (si + 2 < length) {
  611. // remove escapes (very rare 1:2^22)
  612. if (src[si + 2] > 3) {
  613. dst[di++] = src[si++];
  614. dst[di++] = src[si++];
  615. } else if (src[si] == 0 && src[si + 1] == 0) {
  616. if (src[si + 2] == 3) { // escape
  617. dst[di++] = 0;
  618. dst[di++] = 0;
  619. si += 3;
  620. continue;
  621. } else // next start code
  622. goto nsc;
  623. }
  624. dst[di++] = src[si++];
  625. }
  626. while (si < length)
  627. dst[di++] = src[si++];
  628. nsc:
  629. memset(dst + di, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  630. *dst_length = di;
  631. *consumed = si + 1; // +1 for the header
  632. /* FIXME store exact number of bits in the getbitcontext
  633. * (it is needed for decoding) */
  634. return dst;
  635. }
  636. /**
  637. * Identify the exact end of the bitstream
  638. * @return the length of the trailing, or 0 if damaged
  639. */
  640. static int decode_rbsp_trailing(H264Context *h, const uint8_t *src)
  641. {
  642. int v = *src;
  643. int r;
  644. tprintf(h->avctx, "rbsp trailing %X\n", v);
  645. for (r = 1; r < 9; r++) {
  646. if (v & 1)
  647. return r;
  648. v >>= 1;
  649. }
  650. return 0;
  651. }
  652. static inline int get_lowest_part_list_y(H264Context *h, H264Picture *pic, int n,
  653. int height, int y_offset, int list)
  654. {
  655. int raw_my = h->mv_cache[list][scan8[n]][1];
  656. int filter_height_down = (raw_my & 3) ? 3 : 0;
  657. int full_my = (raw_my >> 2) + y_offset;
  658. int bottom = full_my + filter_height_down + height;
  659. av_assert2(height >= 0);
  660. return FFMAX(0, bottom);
  661. }
  662. static inline void get_lowest_part_y(H264Context *h, int refs[2][48], int n,
  663. int height, int y_offset, int list0,
  664. int list1, int *nrefs)
  665. {
  666. int my;
  667. y_offset += 16 * (h->mb_y >> MB_FIELD(h));
  668. if (list0) {
  669. int ref_n = h->ref_cache[0][scan8[n]];
  670. H264Picture *ref = &h->ref_list[0][ref_n];
  671. // Error resilience puts the current picture in the ref list.
  672. // Don't try to wait on these as it will cause a deadlock.
  673. // Fields can wait on each other, though.
  674. if (ref->tf.progress->data != h->cur_pic.tf.progress->data ||
  675. (ref->reference & 3) != h->picture_structure) {
  676. my = get_lowest_part_list_y(h, ref, n, height, y_offset, 0);
  677. if (refs[0][ref_n] < 0)
  678. nrefs[0] += 1;
  679. refs[0][ref_n] = FFMAX(refs[0][ref_n], my);
  680. }
  681. }
  682. if (list1) {
  683. int ref_n = h->ref_cache[1][scan8[n]];
  684. H264Picture *ref = &h->ref_list[1][ref_n];
  685. if (ref->tf.progress->data != h->cur_pic.tf.progress->data ||
  686. (ref->reference & 3) != h->picture_structure) {
  687. my = get_lowest_part_list_y(h, ref, n, height, y_offset, 1);
  688. if (refs[1][ref_n] < 0)
  689. nrefs[1] += 1;
  690. refs[1][ref_n] = FFMAX(refs[1][ref_n], my);
  691. }
  692. }
  693. }
  694. /**
  695. * Wait until all reference frames are available for MC operations.
  696. *
  697. * @param h the H264 context
  698. */
  699. static void await_references(H264Context *h)
  700. {
  701. const int mb_xy = h->mb_xy;
  702. const int mb_type = h->cur_pic.mb_type[mb_xy];
  703. int refs[2][48];
  704. int nrefs[2] = { 0 };
  705. int ref, list;
  706. memset(refs, -1, sizeof(refs));
  707. if (IS_16X16(mb_type)) {
  708. get_lowest_part_y(h, refs, 0, 16, 0,
  709. IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
  710. } else if (IS_16X8(mb_type)) {
  711. get_lowest_part_y(h, refs, 0, 8, 0,
  712. IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
  713. get_lowest_part_y(h, refs, 8, 8, 8,
  714. IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
  715. } else if (IS_8X16(mb_type)) {
  716. get_lowest_part_y(h, refs, 0, 16, 0,
  717. IS_DIR(mb_type, 0, 0), IS_DIR(mb_type, 0, 1), nrefs);
  718. get_lowest_part_y(h, refs, 4, 16, 0,
  719. IS_DIR(mb_type, 1, 0), IS_DIR(mb_type, 1, 1), nrefs);
  720. } else {
  721. int i;
  722. av_assert2(IS_8X8(mb_type));
  723. for (i = 0; i < 4; i++) {
  724. const int sub_mb_type = h->sub_mb_type[i];
  725. const int n = 4 * i;
  726. int y_offset = (i & 2) << 2;
  727. if (IS_SUB_8X8(sub_mb_type)) {
  728. get_lowest_part_y(h, refs, n, 8, y_offset,
  729. IS_DIR(sub_mb_type, 0, 0),
  730. IS_DIR(sub_mb_type, 0, 1),
  731. nrefs);
  732. } else if (IS_SUB_8X4(sub_mb_type)) {
  733. get_lowest_part_y(h, refs, n, 4, y_offset,
  734. IS_DIR(sub_mb_type, 0, 0),
  735. IS_DIR(sub_mb_type, 0, 1),
  736. nrefs);
  737. get_lowest_part_y(h, refs, n + 2, 4, y_offset + 4,
  738. IS_DIR(sub_mb_type, 0, 0),
  739. IS_DIR(sub_mb_type, 0, 1),
  740. nrefs);
  741. } else if (IS_SUB_4X8(sub_mb_type)) {
  742. get_lowest_part_y(h, refs, n, 8, y_offset,
  743. IS_DIR(sub_mb_type, 0, 0),
  744. IS_DIR(sub_mb_type, 0, 1),
  745. nrefs);
  746. get_lowest_part_y(h, refs, n + 1, 8, y_offset,
  747. IS_DIR(sub_mb_type, 0, 0),
  748. IS_DIR(sub_mb_type, 0, 1),
  749. nrefs);
  750. } else {
  751. int j;
  752. av_assert2(IS_SUB_4X4(sub_mb_type));
  753. for (j = 0; j < 4; j++) {
  754. int sub_y_offset = y_offset + 2 * (j & 2);
  755. get_lowest_part_y(h, refs, n + j, 4, sub_y_offset,
  756. IS_DIR(sub_mb_type, 0, 0),
  757. IS_DIR(sub_mb_type, 0, 1),
  758. nrefs);
  759. }
  760. }
  761. }
  762. }
  763. for (list = h->list_count - 1; list >= 0; list--)
  764. for (ref = 0; ref < 48 && nrefs[list]; ref++) {
  765. int row = refs[list][ref];
  766. if (row >= 0) {
  767. H264Picture *ref_pic = &h->ref_list[list][ref];
  768. int ref_field = ref_pic->reference - 1;
  769. int ref_field_picture = ref_pic->field_picture;
  770. int pic_height = 16 * h->mb_height >> ref_field_picture;
  771. row <<= MB_MBAFF(h);
  772. nrefs[list]--;
  773. if (!FIELD_PICTURE(h) && ref_field_picture) { // frame referencing two fields
  774. ff_thread_await_progress(&ref_pic->tf,
  775. FFMIN((row >> 1) - !(row & 1),
  776. pic_height - 1),
  777. 1);
  778. ff_thread_await_progress(&ref_pic->tf,
  779. FFMIN((row >> 1), pic_height - 1),
  780. 0);
  781. } else if (FIELD_PICTURE(h) && !ref_field_picture) { // field referencing one field of a frame
  782. ff_thread_await_progress(&ref_pic->tf,
  783. FFMIN(row * 2 + ref_field,
  784. pic_height - 1),
  785. 0);
  786. } else if (FIELD_PICTURE(h)) {
  787. ff_thread_await_progress(&ref_pic->tf,
  788. FFMIN(row, pic_height - 1),
  789. ref_field);
  790. } else {
  791. ff_thread_await_progress(&ref_pic->tf,
  792. FFMIN(row, pic_height - 1),
  793. 0);
  794. }
  795. }
  796. }
  797. }
  798. static av_always_inline void mc_dir_part(H264Context *h, H264Picture *pic,
  799. int n, int square, int height,
  800. int delta, int list,
  801. uint8_t *dest_y, uint8_t *dest_cb,
  802. uint8_t *dest_cr,
  803. int src_x_offset, int src_y_offset,
  804. qpel_mc_func *qpix_op,
  805. h264_chroma_mc_func chroma_op,
  806. int pixel_shift, int chroma_idc)
  807. {
  808. const int mx = h->mv_cache[list][scan8[n]][0] + src_x_offset * 8;
  809. int my = h->mv_cache[list][scan8[n]][1] + src_y_offset * 8;
  810. const int luma_xy = (mx & 3) + ((my & 3) << 2);
  811. ptrdiff_t offset = ((mx >> 2) << pixel_shift) + (my >> 2) * h->mb_linesize;
  812. uint8_t *src_y = pic->f.data[0] + offset;
  813. uint8_t *src_cb, *src_cr;
  814. int extra_width = 0;
  815. int extra_height = 0;
  816. int emu = 0;
  817. const int full_mx = mx >> 2;
  818. const int full_my = my >> 2;
  819. const int pic_width = 16 * h->mb_width;
  820. const int pic_height = 16 * h->mb_height >> MB_FIELD(h);
  821. int ysh;
  822. if (mx & 7)
  823. extra_width -= 3;
  824. if (my & 7)
  825. extra_height -= 3;
  826. if (full_mx < 0 - extra_width ||
  827. full_my < 0 - extra_height ||
  828. full_mx + 16 /*FIXME*/ > pic_width + extra_width ||
  829. full_my + 16 /*FIXME*/ > pic_height + extra_height) {
  830. h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
  831. src_y - (2 << pixel_shift) - 2 * h->mb_linesize,
  832. h->mb_linesize, h->mb_linesize,
  833. 16 + 5, 16 + 5 /*FIXME*/, full_mx - 2,
  834. full_my - 2, pic_width, pic_height);
  835. src_y = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
  836. emu = 1;
  837. }
  838. qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); // FIXME try variable height perhaps?
  839. if (!square)
  840. qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize);
  841. if (CONFIG_GRAY && h->flags & CODEC_FLAG_GRAY)
  842. return;
  843. if (chroma_idc == 3 /* yuv444 */) {
  844. src_cb = pic->f.data[1] + offset;
  845. if (emu) {
  846. h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
  847. src_cb - (2 << pixel_shift) - 2 * h->mb_linesize,
  848. h->mb_linesize, h->mb_linesize,
  849. 16 + 5, 16 + 5 /*FIXME*/,
  850. full_mx - 2, full_my - 2,
  851. pic_width, pic_height);
  852. src_cb = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
  853. }
  854. qpix_op[luma_xy](dest_cb, src_cb, h->mb_linesize); // FIXME try variable height perhaps?
  855. if (!square)
  856. qpix_op[luma_xy](dest_cb + delta, src_cb + delta, h->mb_linesize);
  857. src_cr = pic->f.data[2] + offset;
  858. if (emu) {
  859. h->vdsp.emulated_edge_mc(h->edge_emu_buffer,
  860. src_cr - (2 << pixel_shift) - 2 * h->mb_linesize,
  861. h->mb_linesize, h->mb_linesize,
  862. 16 + 5, 16 + 5 /*FIXME*/,
  863. full_mx - 2, full_my - 2,
  864. pic_width, pic_height);
  865. src_cr = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize;
  866. }
  867. qpix_op[luma_xy](dest_cr, src_cr, h->mb_linesize); // FIXME try variable height perhaps?
  868. if (!square)
  869. qpix_op[luma_xy](dest_cr + delta, src_cr + delta, h->mb_linesize);
  870. return;
  871. }
  872. ysh = 3 - (chroma_idc == 2 /* yuv422 */);
  873. if (chroma_idc == 1 /* yuv420 */ && MB_FIELD(h)) {
  874. // chroma offset when predicting from a field of opposite parity
  875. my += 2 * ((h->mb_y & 1) - (pic->reference - 1));
  876. emu |= (my >> 3) < 0 || (my >> 3) + 8 >= (pic_height >> 1);
  877. }
  878. src_cb = pic->f.data[1] + ((mx >> 3) << pixel_shift) +
  879. (my >> ysh) * h->mb_uvlinesize;
  880. src_cr = pic->f.data[2] + ((mx >> 3) << pixel_shift) +
  881. (my >> ysh) * h->mb_uvlinesize;
  882. if (emu) {
  883. h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src_cb,
  884. h->mb_uvlinesize, h->mb_uvlinesize,
  885. 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
  886. pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
  887. src_cb = h->edge_emu_buffer;
  888. }
  889. chroma_op(dest_cb, src_cb, h->mb_uvlinesize,
  890. height >> (chroma_idc == 1 /* yuv420 */),
  891. mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
  892. if (emu) {
  893. h->vdsp.emulated_edge_mc(h->edge_emu_buffer, src_cr,
  894. h->mb_uvlinesize, h->mb_uvlinesize,
  895. 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh),
  896. pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */));
  897. src_cr = h->edge_emu_buffer;
  898. }
  899. chroma_op(dest_cr, src_cr, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */),
  900. mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7);
  901. }
  902. static av_always_inline void mc_part_std(H264Context *h, int n, int square,
  903. int height, int delta,
  904. uint8_t *dest_y, uint8_t *dest_cb,
  905. uint8_t *dest_cr,
  906. int x_offset, int y_offset,
  907. qpel_mc_func *qpix_put,
  908. h264_chroma_mc_func chroma_put,
  909. qpel_mc_func *qpix_avg,
  910. h264_chroma_mc_func chroma_avg,
  911. int list0, int list1,
  912. int pixel_shift, int chroma_idc)
  913. {
  914. qpel_mc_func *qpix_op = qpix_put;
  915. h264_chroma_mc_func chroma_op = chroma_put;
  916. dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
  917. if (chroma_idc == 3 /* yuv444 */) {
  918. dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
  919. dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
  920. } else if (chroma_idc == 2 /* yuv422 */) {
  921. dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
  922. dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
  923. } else { /* yuv420 */
  924. dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
  925. dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
  926. }
  927. x_offset += 8 * h->mb_x;
  928. y_offset += 8 * (h->mb_y >> MB_FIELD(h));
  929. if (list0) {
  930. H264Picture *ref = &h->ref_list[0][h->ref_cache[0][scan8[n]]];
  931. mc_dir_part(h, ref, n, square, height, delta, 0,
  932. dest_y, dest_cb, dest_cr, x_offset, y_offset,
  933. qpix_op, chroma_op, pixel_shift, chroma_idc);
  934. qpix_op = qpix_avg;
  935. chroma_op = chroma_avg;
  936. }
  937. if (list1) {
  938. H264Picture *ref = &h->ref_list[1][h->ref_cache[1][scan8[n]]];
  939. mc_dir_part(h, ref, n, square, height, delta, 1,
  940. dest_y, dest_cb, dest_cr, x_offset, y_offset,
  941. qpix_op, chroma_op, pixel_shift, chroma_idc);
  942. }
  943. }
  944. static av_always_inline void mc_part_weighted(H264Context *h, int n, int square,
  945. int height, int delta,
  946. uint8_t *dest_y, uint8_t *dest_cb,
  947. uint8_t *dest_cr,
  948. int x_offset, int y_offset,
  949. qpel_mc_func *qpix_put,
  950. h264_chroma_mc_func chroma_put,
  951. h264_weight_func luma_weight_op,
  952. h264_weight_func chroma_weight_op,
  953. h264_biweight_func luma_weight_avg,
  954. h264_biweight_func chroma_weight_avg,
  955. int list0, int list1,
  956. int pixel_shift, int chroma_idc)
  957. {
  958. int chroma_height;
  959. dest_y += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
  960. if (chroma_idc == 3 /* yuv444 */) {
  961. chroma_height = height;
  962. chroma_weight_avg = luma_weight_avg;
  963. chroma_weight_op = luma_weight_op;
  964. dest_cb += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
  965. dest_cr += (2 * x_offset << pixel_shift) + 2 * y_offset * h->mb_linesize;
  966. } else if (chroma_idc == 2 /* yuv422 */) {
  967. chroma_height = height;
  968. dest_cb += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
  969. dest_cr += (x_offset << pixel_shift) + 2 * y_offset * h->mb_uvlinesize;
  970. } else { /* yuv420 */
  971. chroma_height = height >> 1;
  972. dest_cb += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
  973. dest_cr += (x_offset << pixel_shift) + y_offset * h->mb_uvlinesize;
  974. }
  975. x_offset += 8 * h->mb_x;
  976. y_offset += 8 * (h->mb_y >> MB_FIELD(h));
  977. if (list0 && list1) {
  978. /* don't optimize for luma-only case, since B-frames usually
  979. * use implicit weights => chroma too. */
  980. uint8_t *tmp_cb = h->bipred_scratchpad;
  981. uint8_t *tmp_cr = h->bipred_scratchpad + (16 << pixel_shift);
  982. uint8_t *tmp_y = h->bipred_scratchpad + 16 * h->mb_uvlinesize;
  983. int refn0 = h->ref_cache[0][scan8[n]];
  984. int refn1 = h->ref_cache[1][scan8[n]];
  985. mc_dir_part(h, &h->ref_list[0][refn0], n, square, height, delta, 0,
  986. dest_y, dest_cb, dest_cr,
  987. x_offset, y_offset, qpix_put, chroma_put,
  988. pixel_shift, chroma_idc);
  989. mc_dir_part(h, &h->ref_list[1][refn1], n, square, height, delta, 1,
  990. tmp_y, tmp_cb, tmp_cr,
  991. x_offset, y_offset, qpix_put, chroma_put,
  992. pixel_shift, chroma_idc);
  993. if (h->use_weight == 2) {
  994. int weight0 = h->implicit_weight[refn0][refn1][h->mb_y & 1];
  995. int weight1 = 64 - weight0;
  996. luma_weight_avg(dest_y, tmp_y, h->mb_linesize,
  997. height, 5, weight0, weight1, 0);
  998. chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize,
  999. chroma_height, 5, weight0, weight1, 0);
  1000. chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize,
  1001. chroma_height, 5, weight0, weight1, 0);
  1002. } else {
  1003. luma_weight_avg(dest_y, tmp_y, h->mb_linesize, height,
  1004. h->luma_log2_weight_denom,
  1005. h->luma_weight[refn0][0][0],
  1006. h->luma_weight[refn1][1][0],
  1007. h->luma_weight[refn0][0][1] +
  1008. h->luma_weight[refn1][1][1]);
  1009. chroma_weight_avg(dest_cb, tmp_cb, h->mb_uvlinesize, chroma_height,
  1010. h->chroma_log2_weight_denom,
  1011. h->chroma_weight[refn0][0][0][0],
  1012. h->chroma_weight[refn1][1][0][0],
  1013. h->chroma_weight[refn0][0][0][1] +
  1014. h->chroma_weight[refn1][1][0][1]);
  1015. chroma_weight_avg(dest_cr, tmp_cr, h->mb_uvlinesize, chroma_height,
  1016. h->chroma_log2_weight_denom,
  1017. h->chroma_weight[refn0][0][1][0],
  1018. h->chroma_weight[refn1][1][1][0],
  1019. h->chroma_weight[refn0][0][1][1] +
  1020. h->chroma_weight[refn1][1][1][1]);
  1021. }
  1022. } else {
  1023. int list = list1 ? 1 : 0;
  1024. int refn = h->ref_cache[list][scan8[n]];
  1025. H264Picture *ref = &h->ref_list[list][refn];
  1026. mc_dir_part(h, ref, n, square, height, delta, list,
  1027. dest_y, dest_cb, dest_cr, x_offset, y_offset,
  1028. qpix_put, chroma_put, pixel_shift, chroma_idc);
  1029. luma_weight_op(dest_y, h->mb_linesize, height,
  1030. h->luma_log2_weight_denom,
  1031. h->luma_weight[refn][list][0],
  1032. h->luma_weight[refn][list][1]);
  1033. if (h->use_weight_chroma) {
  1034. chroma_weight_op(dest_cb, h->mb_uvlinesize, chroma_height,
  1035. h->chroma_log2_weight_denom,
  1036. h->chroma_weight[refn][list][0][0],
  1037. h->chroma_weight[refn][list][0][1]);
  1038. chroma_weight_op(dest_cr, h->mb_uvlinesize, chroma_height,
  1039. h->chroma_log2_weight_denom,
  1040. h->chroma_weight[refn][list][1][0],
  1041. h->chroma_weight[refn][list][1][1]);
  1042. }
  1043. }
  1044. }
  1045. static av_always_inline void prefetch_motion(H264Context *h, int list,
  1046. int pixel_shift, int chroma_idc)
  1047. {
  1048. /* fetch pixels for estimated mv 4 macroblocks ahead
  1049. * optimized for 64byte cache lines */
  1050. const int refn = h->ref_cache[list][scan8[0]];
  1051. if (refn >= 0) {
  1052. const int mx = (h->mv_cache[list][scan8[0]][0] >> 2) + 16 * h->mb_x + 8;
  1053. const int my = (h->mv_cache[list][scan8[0]][1] >> 2) + 16 * h->mb_y;
  1054. uint8_t **src = h->ref_list[list][refn].f.data;
  1055. int off = (mx << pixel_shift) +
  1056. (my + (h->mb_x & 3) * 4) * h->mb_linesize +
  1057. (64 << pixel_shift);
  1058. h->vdsp.prefetch(src[0] + off, h->linesize, 4);
  1059. if (chroma_idc == 3 /* yuv444 */) {
  1060. h->vdsp.prefetch(src[1] + off, h->linesize, 4);
  1061. h->vdsp.prefetch(src[2] + off, h->linesize, 4);
  1062. } else {
  1063. off= (((mx>>1)+64)<<pixel_shift) + ((my>>1) + (h->mb_x&7))*h->uvlinesize;
  1064. h->vdsp.prefetch(src[1] + off, src[2] - src[1], 2);
  1065. }
  1066. }
  1067. }
  1068. static void free_tables(H264Context *h, int free_rbsp)
  1069. {
  1070. int i;
  1071. H264Context *hx;
  1072. av_freep(&h->intra4x4_pred_mode);
  1073. av_freep(&h->chroma_pred_mode_table);
  1074. av_freep(&h->cbp_table);
  1075. av_freep(&h->mvd_table[0]);
  1076. av_freep(&h->mvd_table[1]);
  1077. av_freep(&h->direct_table);
  1078. av_freep(&h->non_zero_count);
  1079. av_freep(&h->slice_table_base);
  1080. h->slice_table = NULL;
  1081. av_freep(&h->list_counts);
  1082. av_freep(&h->mb2b_xy);
  1083. av_freep(&h->mb2br_xy);
  1084. av_buffer_pool_uninit(&h->qscale_table_pool);
  1085. av_buffer_pool_uninit(&h->mb_type_pool);
  1086. av_buffer_pool_uninit(&h->motion_val_pool);
  1087. av_buffer_pool_uninit(&h->ref_index_pool);
  1088. if (free_rbsp && h->DPB) {
  1089. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
  1090. unref_picture(h, &h->DPB[i]);
  1091. av_freep(&h->DPB);
  1092. } else if (h->DPB) {
  1093. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
  1094. h->DPB[i].needs_realloc = 1;
  1095. }
  1096. h->cur_pic_ptr = NULL;
  1097. for (i = 0; i < H264_MAX_THREADS; i++) {
  1098. hx = h->thread_context[i];
  1099. if (!hx)
  1100. continue;
  1101. av_freep(&hx->top_borders[1]);
  1102. av_freep(&hx->top_borders[0]);
  1103. av_freep(&hx->bipred_scratchpad);
  1104. av_freep(&hx->edge_emu_buffer);
  1105. av_freep(&hx->dc_val_base);
  1106. av_freep(&hx->er.mb_index2xy);
  1107. av_freep(&hx->er.error_status_table);
  1108. av_freep(&hx->er.er_temp_buffer);
  1109. av_freep(&hx->er.mbintra_table);
  1110. av_freep(&hx->er.mbskip_table);
  1111. if (free_rbsp) {
  1112. av_freep(&hx->rbsp_buffer[1]);
  1113. av_freep(&hx->rbsp_buffer[0]);
  1114. hx->rbsp_buffer_size[0] = 0;
  1115. hx->rbsp_buffer_size[1] = 0;
  1116. }
  1117. if (i)
  1118. av_freep(&h->thread_context[i]);
  1119. }
  1120. }
  1121. static void init_dequant8_coeff_table(H264Context *h)
  1122. {
  1123. int i, j, q, x;
  1124. const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
  1125. for (i = 0; i < 6; i++) {
  1126. h->dequant8_coeff[i] = h->dequant8_buffer[i];
  1127. for (j = 0; j < i; j++)
  1128. if (!memcmp(h->pps.scaling_matrix8[j], h->pps.scaling_matrix8[i],
  1129. 64 * sizeof(uint8_t))) {
  1130. h->dequant8_coeff[i] = h->dequant8_buffer[j];
  1131. break;
  1132. }
  1133. if (j < i)
  1134. continue;
  1135. for (q = 0; q < max_qp + 1; q++) {
  1136. int shift = div6[q];
  1137. int idx = rem6[q];
  1138. for (x = 0; x < 64; x++)
  1139. h->dequant8_coeff[i][q][(x >> 3) | ((x & 7) << 3)] =
  1140. ((uint32_t)dequant8_coeff_init[idx][dequant8_coeff_init_scan[((x >> 1) & 12) | (x & 3)]] *
  1141. h->pps.scaling_matrix8[i][x]) << shift;
  1142. }
  1143. }
  1144. }
  1145. static void init_dequant4_coeff_table(H264Context *h)
  1146. {
  1147. int i, j, q, x;
  1148. const int max_qp = 51 + 6 * (h->sps.bit_depth_luma - 8);
  1149. for (i = 0; i < 6; i++) {
  1150. h->dequant4_coeff[i] = h->dequant4_buffer[i];
  1151. for (j = 0; j < i; j++)
  1152. if (!memcmp(h->pps.scaling_matrix4[j], h->pps.scaling_matrix4[i],
  1153. 16 * sizeof(uint8_t))) {
  1154. h->dequant4_coeff[i] = h->dequant4_buffer[j];
  1155. break;
  1156. }
  1157. if (j < i)
  1158. continue;
  1159. for (q = 0; q < max_qp + 1; q++) {
  1160. int shift = div6[q] + 2;
  1161. int idx = rem6[q];
  1162. for (x = 0; x < 16; x++)
  1163. h->dequant4_coeff[i][q][(x >> 2) | ((x << 2) & 0xF)] =
  1164. ((uint32_t)dequant4_coeff_init[idx][(x & 1) + ((x >> 2) & 1)] *
  1165. h->pps.scaling_matrix4[i][x]) << shift;
  1166. }
  1167. }
  1168. }
  1169. static void init_dequant_tables(H264Context *h)
  1170. {
  1171. int i, x;
  1172. init_dequant4_coeff_table(h);
  1173. memset(h->dequant8_coeff, 0, sizeof(h->dequant8_coeff));
  1174. if (h->pps.transform_8x8_mode)
  1175. init_dequant8_coeff_table(h);
  1176. if (h->sps.transform_bypass) {
  1177. for (i = 0; i < 6; i++)
  1178. for (x = 0; x < 16; x++)
  1179. h->dequant4_coeff[i][0][x] = 1 << 6;
  1180. if (h->pps.transform_8x8_mode)
  1181. for (i = 0; i < 6; i++)
  1182. for (x = 0; x < 64; x++)
  1183. h->dequant8_coeff[i][0][x] = 1 << 6;
  1184. }
  1185. }
  1186. int ff_h264_alloc_tables(H264Context *h)
  1187. {
  1188. const int big_mb_num = h->mb_stride * (h->mb_height + 1);
  1189. const int row_mb_num = 2*h->mb_stride*FFMAX(h->avctx->thread_count, 1);
  1190. int x, y, i;
  1191. FF_ALLOCZ_OR_GOTO(h->avctx, h->intra4x4_pred_mode,
  1192. row_mb_num * 8 * sizeof(uint8_t), fail)
  1193. FF_ALLOCZ_OR_GOTO(h->avctx, h->non_zero_count,
  1194. big_mb_num * 48 * sizeof(uint8_t), fail)
  1195. FF_ALLOCZ_OR_GOTO(h->avctx, h->slice_table_base,
  1196. (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base), fail)
  1197. FF_ALLOCZ_OR_GOTO(h->avctx, h->cbp_table,
  1198. big_mb_num * sizeof(uint16_t), fail)
  1199. FF_ALLOCZ_OR_GOTO(h->avctx, h->chroma_pred_mode_table,
  1200. big_mb_num * sizeof(uint8_t), fail)
  1201. FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[0],
  1202. 16 * row_mb_num * sizeof(uint8_t), fail);
  1203. FF_ALLOCZ_OR_GOTO(h->avctx, h->mvd_table[1],
  1204. 16 * row_mb_num * sizeof(uint8_t), fail);
  1205. FF_ALLOCZ_OR_GOTO(h->avctx, h->direct_table,
  1206. 4 * big_mb_num * sizeof(uint8_t), fail);
  1207. FF_ALLOCZ_OR_GOTO(h->avctx, h->list_counts,
  1208. big_mb_num * sizeof(uint8_t), fail)
  1209. memset(h->slice_table_base, -1,
  1210. (big_mb_num + h->mb_stride) * sizeof(*h->slice_table_base));
  1211. h->slice_table = h->slice_table_base + h->mb_stride * 2 + 1;
  1212. FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2b_xy,
  1213. big_mb_num * sizeof(uint32_t), fail);
  1214. FF_ALLOCZ_OR_GOTO(h->avctx, h->mb2br_xy,
  1215. big_mb_num * sizeof(uint32_t), fail);
  1216. for (y = 0; y < h->mb_height; y++)
  1217. for (x = 0; x < h->mb_width; x++) {
  1218. const int mb_xy = x + y * h->mb_stride;
  1219. const int b_xy = 4 * x + 4 * y * h->b_stride;
  1220. h->mb2b_xy[mb_xy] = b_xy;
  1221. h->mb2br_xy[mb_xy] = 8 * (FMO ? mb_xy : (mb_xy % (2 * h->mb_stride)));
  1222. }
  1223. if (!h->dequant4_coeff[0])
  1224. init_dequant_tables(h);
  1225. if (!h->DPB) {
  1226. h->DPB = av_mallocz_array(H264_MAX_PICTURE_COUNT, sizeof(*h->DPB));
  1227. if (!h->DPB)
  1228. return AVERROR(ENOMEM);
  1229. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
  1230. av_frame_unref(&h->DPB[i].f);
  1231. av_frame_unref(&h->cur_pic.f);
  1232. }
  1233. return 0;
  1234. fail:
  1235. free_tables(h, 1);
  1236. return AVERROR(ENOMEM);
  1237. }
  1238. /**
  1239. * Mimic alloc_tables(), but for every context thread.
  1240. */
  1241. static void clone_tables(H264Context *dst, H264Context *src, int i)
  1242. {
  1243. dst->intra4x4_pred_mode = src->intra4x4_pred_mode + i * 8 * 2 * src->mb_stride;
  1244. dst->non_zero_count = src->non_zero_count;
  1245. dst->slice_table = src->slice_table;
  1246. dst->cbp_table = src->cbp_table;
  1247. dst->mb2b_xy = src->mb2b_xy;
  1248. dst->mb2br_xy = src->mb2br_xy;
  1249. dst->chroma_pred_mode_table = src->chroma_pred_mode_table;
  1250. dst->mvd_table[0] = src->mvd_table[0] + i * 8 * 2 * src->mb_stride;
  1251. dst->mvd_table[1] = src->mvd_table[1] + i * 8 * 2 * src->mb_stride;
  1252. dst->direct_table = src->direct_table;
  1253. dst->list_counts = src->list_counts;
  1254. dst->DPB = src->DPB;
  1255. dst->cur_pic_ptr = src->cur_pic_ptr;
  1256. dst->cur_pic = src->cur_pic;
  1257. dst->bipred_scratchpad = NULL;
  1258. dst->edge_emu_buffer = NULL;
  1259. ff_h264_pred_init(&dst->hpc, src->avctx->codec_id, src->sps.bit_depth_luma,
  1260. src->sps.chroma_format_idc);
  1261. }
  1262. /**
  1263. * Init context
  1264. * Allocate buffers which are not shared amongst multiple threads.
  1265. */
  1266. static int context_init(H264Context *h)
  1267. {
  1268. ERContext *er = &h->er;
  1269. int mb_array_size = h->mb_height * h->mb_stride;
  1270. int y_size = (2 * h->mb_width + 1) * (2 * h->mb_height + 1);
  1271. int c_size = h->mb_stride * (h->mb_height + 1);
  1272. int yc_size = y_size + 2 * c_size;
  1273. int x, y, i;
  1274. FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[0],
  1275. h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
  1276. FF_ALLOCZ_OR_GOTO(h->avctx, h->top_borders[1],
  1277. h->mb_width * 16 * 3 * sizeof(uint8_t) * 2, fail)
  1278. h->ref_cache[0][scan8[5] + 1] =
  1279. h->ref_cache[0][scan8[7] + 1] =
  1280. h->ref_cache[0][scan8[13] + 1] =
  1281. h->ref_cache[1][scan8[5] + 1] =
  1282. h->ref_cache[1][scan8[7] + 1] =
  1283. h->ref_cache[1][scan8[13] + 1] = PART_NOT_AVAILABLE;
  1284. if (CONFIG_ERROR_RESILIENCE) {
  1285. /* init ER */
  1286. er->avctx = h->avctx;
  1287. er->dsp = &h->dsp;
  1288. er->decode_mb = h264_er_decode_mb;
  1289. er->opaque = h;
  1290. er->quarter_sample = 1;
  1291. er->mb_num = h->mb_num;
  1292. er->mb_width = h->mb_width;
  1293. er->mb_height = h->mb_height;
  1294. er->mb_stride = h->mb_stride;
  1295. er->b8_stride = h->mb_width * 2 + 1;
  1296. FF_ALLOCZ_OR_GOTO(h->avctx, er->mb_index2xy, (h->mb_num + 1) * sizeof(int),
  1297. fail); // error ressilience code looks cleaner with this
  1298. for (y = 0; y < h->mb_height; y++)
  1299. for (x = 0; x < h->mb_width; x++)
  1300. er->mb_index2xy[x + y * h->mb_width] = x + y * h->mb_stride;
  1301. er->mb_index2xy[h->mb_height * h->mb_width] = (h->mb_height - 1) *
  1302. h->mb_stride + h->mb_width;
  1303. FF_ALLOCZ_OR_GOTO(h->avctx, er->error_status_table,
  1304. mb_array_size * sizeof(uint8_t), fail);
  1305. FF_ALLOC_OR_GOTO(h->avctx, er->mbintra_table, mb_array_size, fail);
  1306. memset(er->mbintra_table, 1, mb_array_size);
  1307. FF_ALLOCZ_OR_GOTO(h->avctx, er->mbskip_table, mb_array_size + 2, fail);
  1308. FF_ALLOC_OR_GOTO(h->avctx, er->er_temp_buffer, h->mb_height * h->mb_stride,
  1309. fail);
  1310. FF_ALLOCZ_OR_GOTO(h->avctx, h->dc_val_base, yc_size * sizeof(int16_t), fail);
  1311. er->dc_val[0] = h->dc_val_base + h->mb_width * 2 + 2;
  1312. er->dc_val[1] = h->dc_val_base + y_size + h->mb_stride + 1;
  1313. er->dc_val[2] = er->dc_val[1] + c_size;
  1314. for (i = 0; i < yc_size; i++)
  1315. h->dc_val_base[i] = 1024;
  1316. }
  1317. return 0;
  1318. fail:
  1319. return AVERROR(ENOMEM); // free_tables will clean up for us
  1320. }
  1321. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
  1322. int parse_extradata);
  1323. int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
  1324. {
  1325. AVCodecContext *avctx = h->avctx;
  1326. int ret;
  1327. if (!buf || size <= 0)
  1328. return -1;
  1329. if (buf[0] == 1) {
  1330. int i, cnt, nalsize;
  1331. const unsigned char *p = buf;
  1332. h->is_avc = 1;
  1333. if (size < 7) {
  1334. av_log(avctx, AV_LOG_ERROR,
  1335. "avcC %d too short\n", size);
  1336. return AVERROR_INVALIDDATA;
  1337. }
  1338. /* sps and pps in the avcC always have length coded with 2 bytes,
  1339. * so put a fake nal_length_size = 2 while parsing them */
  1340. h->nal_length_size = 2;
  1341. // Decode sps from avcC
  1342. cnt = *(p + 5) & 0x1f; // Number of sps
  1343. p += 6;
  1344. for (i = 0; i < cnt; i++) {
  1345. nalsize = AV_RB16(p) + 2;
  1346. if(nalsize > size - (p-buf))
  1347. return AVERROR_INVALIDDATA;
  1348. ret = decode_nal_units(h, p, nalsize, 1);
  1349. if (ret < 0) {
  1350. av_log(avctx, AV_LOG_ERROR,
  1351. "Decoding sps %d from avcC failed\n", i);
  1352. return ret;
  1353. }
  1354. p += nalsize;
  1355. }
  1356. // Decode pps from avcC
  1357. cnt = *(p++); // Number of pps
  1358. for (i = 0; i < cnt; i++) {
  1359. nalsize = AV_RB16(p) + 2;
  1360. if(nalsize > size - (p-buf))
  1361. return AVERROR_INVALIDDATA;
  1362. ret = decode_nal_units(h, p, nalsize, 1);
  1363. if (ret < 0) {
  1364. av_log(avctx, AV_LOG_ERROR,
  1365. "Decoding pps %d from avcC failed\n", i);
  1366. return ret;
  1367. }
  1368. p += nalsize;
  1369. }
  1370. // Now store right nal length size, that will be used to parse all other nals
  1371. h->nal_length_size = (buf[4] & 0x03) + 1;
  1372. } else {
  1373. h->is_avc = 0;
  1374. ret = decode_nal_units(h, buf, size, 1);
  1375. if (ret < 0)
  1376. return ret;
  1377. }
  1378. return size;
  1379. }
  1380. av_cold int ff_h264_decode_init(AVCodecContext *avctx)
  1381. {
  1382. H264Context *h = avctx->priv_data;
  1383. int i;
  1384. int ret;
  1385. h->avctx = avctx;
  1386. h->bit_depth_luma = 8;
  1387. h->chroma_format_idc = 1;
  1388. h->avctx->bits_per_raw_sample = 8;
  1389. h->cur_chroma_format_idc = 1;
  1390. ff_h264dsp_init(&h->h264dsp, 8, 1);
  1391. av_assert0(h->sps.bit_depth_chroma == 0);
  1392. ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
  1393. ff_h264qpel_init(&h->h264qpel, 8);
  1394. ff_h264_pred_init(&h->hpc, h->avctx->codec_id, 8, 1);
  1395. h->dequant_coeff_pps = -1;
  1396. h->current_sps_id = -1;
  1397. /* needed so that IDCT permutation is known early */
  1398. if (CONFIG_ERROR_RESILIENCE)
  1399. ff_dsputil_init(&h->dsp, h->avctx);
  1400. ff_videodsp_init(&h->vdsp, 8);
  1401. memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
  1402. memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
  1403. h->picture_structure = PICT_FRAME;
  1404. h->slice_context_count = 1;
  1405. h->workaround_bugs = avctx->workaround_bugs;
  1406. h->flags = avctx->flags;
  1407. /* set defaults */
  1408. // s->decode_mb = ff_h263_decode_mb;
  1409. if (!avctx->has_b_frames)
  1410. h->low_delay = 1;
  1411. avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
  1412. ff_h264_decode_init_vlc();
  1413. ff_init_cabac_states();
  1414. h->pixel_shift = 0;
  1415. h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
  1416. h->thread_context[0] = h;
  1417. h->outputed_poc = h->next_outputed_poc = INT_MIN;
  1418. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  1419. h->last_pocs[i] = INT_MIN;
  1420. h->prev_poc_msb = 1 << 16;
  1421. h->prev_frame_num = -1;
  1422. h->x264_build = -1;
  1423. h->sei_fpa.frame_packing_arrangement_cancel_flag = -1;
  1424. ff_h264_reset_sei(h);
  1425. if (avctx->codec_id == AV_CODEC_ID_H264) {
  1426. if (avctx->ticks_per_frame == 1) {
  1427. if(h->avctx->time_base.den < INT_MAX/2) {
  1428. h->avctx->time_base.den *= 2;
  1429. } else
  1430. h->avctx->time_base.num /= 2;
  1431. }
  1432. avctx->ticks_per_frame = 2;
  1433. }
  1434. if (avctx->extradata_size > 0 && avctx->extradata) {
  1435. ret = ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size);
  1436. if (ret < 0) {
  1437. ff_h264_free_context(h);
  1438. return ret;
  1439. }
  1440. }
  1441. if (h->sps.bitstream_restriction_flag &&
  1442. h->avctx->has_b_frames < h->sps.num_reorder_frames) {
  1443. h->avctx->has_b_frames = h->sps.num_reorder_frames;
  1444. h->low_delay = 0;
  1445. }
  1446. avctx->internal->allocate_progress = 1;
  1447. flush_change(h);
  1448. return 0;
  1449. }
  1450. #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
  1451. #undef REBASE_PICTURE
  1452. #define REBASE_PICTURE(pic, new_ctx, old_ctx) \
  1453. ((pic && pic >= old_ctx->DPB && \
  1454. pic < old_ctx->DPB + H264_MAX_PICTURE_COUNT) ? \
  1455. &new_ctx->DPB[pic - old_ctx->DPB] : NULL)
  1456. static void copy_picture_range(H264Picture **to, H264Picture **from, int count,
  1457. H264Context *new_base,
  1458. H264Context *old_base)
  1459. {
  1460. int i;
  1461. for (i = 0; i < count; i++) {
  1462. assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
  1463. IN_RANGE(from[i], old_base->DPB,
  1464. sizeof(H264Picture) * H264_MAX_PICTURE_COUNT) ||
  1465. !from[i]));
  1466. to[i] = REBASE_PICTURE(from[i], new_base, old_base);
  1467. }
  1468. }
  1469. static int copy_parameter_set(void **to, void **from, int count, int size)
  1470. {
  1471. int i;
  1472. for (i = 0; i < count; i++) {
  1473. if (to[i] && !from[i]) {
  1474. av_freep(&to[i]);
  1475. } else if (from[i] && !to[i]) {
  1476. to[i] = av_malloc(size);
  1477. if (!to[i])
  1478. return AVERROR(ENOMEM);
  1479. }
  1480. if (from[i])
  1481. memcpy(to[i], from[i], size);
  1482. }
  1483. return 0;
  1484. }
  1485. static int decode_init_thread_copy(AVCodecContext *avctx)
  1486. {
  1487. H264Context *h = avctx->priv_data;
  1488. if (!avctx->internal->is_copy)
  1489. return 0;
  1490. memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
  1491. memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
  1492. h->rbsp_buffer[0] = NULL;
  1493. h->rbsp_buffer[1] = NULL;
  1494. h->rbsp_buffer_size[0] = 0;
  1495. h->rbsp_buffer_size[1] = 0;
  1496. h->context_initialized = 0;
  1497. return 0;
  1498. }
  1499. #define copy_fields(to, from, start_field, end_field) \
  1500. memcpy(&to->start_field, &from->start_field, \
  1501. (char *)&to->end_field - (char *)&to->start_field)
  1502. static int h264_slice_header_init(H264Context *, int);
  1503. static int h264_set_parameter_from_sps(H264Context *h);
  1504. static int decode_update_thread_context(AVCodecContext *dst,
  1505. const AVCodecContext *src)
  1506. {
  1507. H264Context *h = dst->priv_data, *h1 = src->priv_data;
  1508. int inited = h->context_initialized, err = 0;
  1509. int context_reinitialized = 0;
  1510. int i, ret;
  1511. if (dst == src)
  1512. return 0;
  1513. if (inited &&
  1514. (h->width != h1->width ||
  1515. h->height != h1->height ||
  1516. h->mb_width != h1->mb_width ||
  1517. h->mb_height != h1->mb_height ||
  1518. h->sps.bit_depth_luma != h1->sps.bit_depth_luma ||
  1519. h->sps.chroma_format_idc != h1->sps.chroma_format_idc ||
  1520. h->sps.colorspace != h1->sps.colorspace)) {
  1521. /* set bits_per_raw_sample to the previous value. the check for changed
  1522. * bit depth in h264_set_parameter_from_sps() uses it and sets it to
  1523. * the current value */
  1524. h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
  1525. av_freep(&h->bipred_scratchpad);
  1526. h->width = h1->width;
  1527. h->height = h1->height;
  1528. h->mb_height = h1->mb_height;
  1529. h->mb_width = h1->mb_width;
  1530. h->mb_num = h1->mb_num;
  1531. h->mb_stride = h1->mb_stride;
  1532. h->b_stride = h1->b_stride;
  1533. // SPS/PPS
  1534. if ((ret = copy_parameter_set((void **)h->sps_buffers,
  1535. (void **)h1->sps_buffers,
  1536. MAX_SPS_COUNT, sizeof(SPS))) < 0)
  1537. return ret;
  1538. h->sps = h1->sps;
  1539. if ((ret = copy_parameter_set((void **)h->pps_buffers,
  1540. (void **)h1->pps_buffers,
  1541. MAX_PPS_COUNT, sizeof(PPS))) < 0)
  1542. return ret;
  1543. h->pps = h1->pps;
  1544. if ((err = h264_slice_header_init(h, 1)) < 0) {
  1545. av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed");
  1546. return err;
  1547. }
  1548. context_reinitialized = 1;
  1549. #if 0
  1550. h264_set_parameter_from_sps(h);
  1551. //Note we set context_reinitialized which will cause h264_set_parameter_from_sps to be reexecuted
  1552. h->cur_chroma_format_idc = h1->cur_chroma_format_idc;
  1553. #endif
  1554. }
  1555. /* update linesize on resize for h264. The h264 decoder doesn't
  1556. * necessarily call ff_MPV_frame_start in the new thread */
  1557. h->linesize = h1->linesize;
  1558. h->uvlinesize = h1->uvlinesize;
  1559. /* copy block_offset since frame_start may not be called */
  1560. memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));
  1561. if (!inited) {
  1562. for (i = 0; i < MAX_SPS_COUNT; i++)
  1563. av_freep(h->sps_buffers + i);
  1564. for (i = 0; i < MAX_PPS_COUNT; i++)
  1565. av_freep(h->pps_buffers + i);
  1566. av_freep(&h->rbsp_buffer[0]);
  1567. av_freep(&h->rbsp_buffer[1]);
  1568. memcpy(h, h1, offsetof(H264Context, intra_pcm_ptr));
  1569. memcpy(&h->cabac, &h1->cabac,
  1570. sizeof(H264Context) - offsetof(H264Context, cabac));
  1571. av_assert0((void*)&h->cabac == &h->mb_padding + 1);
  1572. memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
  1573. memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
  1574. memset(&h->er, 0, sizeof(h->er));
  1575. memset(&h->mb, 0, sizeof(h->mb));
  1576. memset(&h->mb_luma_dc, 0, sizeof(h->mb_luma_dc));
  1577. memset(&h->mb_padding, 0, sizeof(h->mb_padding));
  1578. h->avctx = dst;
  1579. h->DPB = NULL;
  1580. h->qscale_table_pool = NULL;
  1581. h->mb_type_pool = NULL;
  1582. h->ref_index_pool = NULL;
  1583. h->motion_val_pool = NULL;
  1584. for (i = 0; i < 2; i++) {
  1585. h->rbsp_buffer[i] = NULL;
  1586. h->rbsp_buffer_size[i] = 0;
  1587. }
  1588. if (h1->context_initialized) {
  1589. h->context_initialized = 0;
  1590. memset(&h->cur_pic, 0, sizeof(h->cur_pic));
  1591. av_frame_unref(&h->cur_pic.f);
  1592. h->cur_pic.tf.f = &h->cur_pic.f;
  1593. ret = ff_h264_alloc_tables(h);
  1594. if (ret < 0) {
  1595. av_log(dst, AV_LOG_ERROR, "Could not allocate memory\n");
  1596. return ret;
  1597. }
  1598. ret = context_init(h);
  1599. if (ret < 0) {
  1600. av_log(dst, AV_LOG_ERROR, "context_init() failed.\n");
  1601. return ret;
  1602. }
  1603. }
  1604. h->bipred_scratchpad = NULL;
  1605. h->edge_emu_buffer = NULL;
  1606. h->thread_context[0] = h;
  1607. h->context_initialized = h1->context_initialized;
  1608. }
  1609. h->avctx->coded_height = h1->avctx->coded_height;
  1610. h->avctx->coded_width = h1->avctx->coded_width;
  1611. h->avctx->width = h1->avctx->width;
  1612. h->avctx->height = h1->avctx->height;
  1613. h->coded_picture_number = h1->coded_picture_number;
  1614. h->first_field = h1->first_field;
  1615. h->picture_structure = h1->picture_structure;
  1616. h->qscale = h1->qscale;
  1617. h->droppable = h1->droppable;
  1618. h->low_delay = h1->low_delay;
  1619. for (i = 0; h->DPB && i < H264_MAX_PICTURE_COUNT; i++) {
  1620. unref_picture(h, &h->DPB[i]);
  1621. if (h1->DPB && h1->DPB[i].f.buf[0] &&
  1622. (ret = ref_picture(h, &h->DPB[i], &h1->DPB[i])) < 0)
  1623. return ret;
  1624. }
  1625. h->cur_pic_ptr = REBASE_PICTURE(h1->cur_pic_ptr, h, h1);
  1626. unref_picture(h, &h->cur_pic);
  1627. if (h1->cur_pic.f.buf[0] && (ret = ref_picture(h, &h->cur_pic, &h1->cur_pic)) < 0)
  1628. return ret;
  1629. h->workaround_bugs = h1->workaround_bugs;
  1630. h->low_delay = h1->low_delay;
  1631. h->droppable = h1->droppable;
  1632. // extradata/NAL handling
  1633. h->is_avc = h1->is_avc;
  1634. // SPS/PPS
  1635. if ((ret = copy_parameter_set((void **)h->sps_buffers,
  1636. (void **)h1->sps_buffers,
  1637. MAX_SPS_COUNT, sizeof(SPS))) < 0)
  1638. return ret;
  1639. h->sps = h1->sps;
  1640. if ((ret = copy_parameter_set((void **)h->pps_buffers,
  1641. (void **)h1->pps_buffers,
  1642. MAX_PPS_COUNT, sizeof(PPS))) < 0)
  1643. return ret;
  1644. h->pps = h1->pps;
  1645. // Dequantization matrices
  1646. // FIXME these are big - can they be only copied when PPS changes?
  1647. copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
  1648. for (i = 0; i < 6; i++)
  1649. h->dequant4_coeff[i] = h->dequant4_buffer[0] +
  1650. (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
  1651. for (i = 0; i < 6; i++)
  1652. h->dequant8_coeff[i] = h->dequant8_buffer[0] +
  1653. (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
  1654. h->dequant_coeff_pps = h1->dequant_coeff_pps;
  1655. // POC timing
  1656. copy_fields(h, h1, poc_lsb, redundant_pic_count);
  1657. // reference lists
  1658. copy_fields(h, h1, short_ref, cabac_init_idc);
  1659. copy_picture_range(h->short_ref, h1->short_ref, 32, h, h1);
  1660. copy_picture_range(h->long_ref, h1->long_ref, 32, h, h1);
  1661. copy_picture_range(h->delayed_pic, h1->delayed_pic,
  1662. MAX_DELAYED_PIC_COUNT + 2, h, h1);
  1663. h->frame_recovered = h1->frame_recovered;
  1664. if (context_reinitialized)
  1665. h264_set_parameter_from_sps(h);
  1666. if (!h->cur_pic_ptr)
  1667. return 0;
  1668. if (!h->droppable) {
  1669. err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
  1670. h->prev_poc_msb = h->poc_msb;
  1671. h->prev_poc_lsb = h->poc_lsb;
  1672. }
  1673. h->prev_frame_num_offset = h->frame_num_offset;
  1674. h->prev_frame_num = h->frame_num;
  1675. h->outputed_poc = h->next_outputed_poc;
  1676. h->recovery_frame = h1->recovery_frame;
  1677. return err;
  1678. }
  1679. static int h264_frame_start(H264Context *h)
  1680. {
  1681. H264Picture *pic;
  1682. int i, ret;
  1683. const int pixel_shift = h->pixel_shift;
  1684. int c[4] = {
  1685. 1<<(h->sps.bit_depth_luma-1),
  1686. 1<<(h->sps.bit_depth_chroma-1),
  1687. 1<<(h->sps.bit_depth_chroma-1),
  1688. -1
  1689. };
  1690. if (!ff_thread_can_start_frame(h->avctx)) {
  1691. av_log(h->avctx, AV_LOG_ERROR, "Attempt to start a frame outside SETUP state\n");
  1692. return -1;
  1693. }
  1694. release_unused_pictures(h, 1);
  1695. h->cur_pic_ptr = NULL;
  1696. i = find_unused_picture(h);
  1697. if (i < 0) {
  1698. av_log(h->avctx, AV_LOG_ERROR, "no frame buffer available\n");
  1699. return i;
  1700. }
  1701. pic = &h->DPB[i];
  1702. pic->reference = h->droppable ? 0 : h->picture_structure;
  1703. pic->f.coded_picture_number = h->coded_picture_number++;
  1704. pic->field_picture = h->picture_structure != PICT_FRAME;
  1705. /*
  1706. * Zero key_frame here; IDR markings per slice in frame or fields are ORed
  1707. * in later.
  1708. * See decode_nal_units().
  1709. */
  1710. pic->f.key_frame = 0;
  1711. pic->mmco_reset = 0;
  1712. pic->recovered = 0;
  1713. pic->invalid_gap = 0;
  1714. if ((ret = alloc_picture(h, pic)) < 0)
  1715. return ret;
  1716. if(!h->frame_recovered && !h->avctx->hwaccel &&
  1717. !(h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU))
  1718. avpriv_color_frame(&pic->f, c);
  1719. h->cur_pic_ptr = pic;
  1720. unref_picture(h, &h->cur_pic);
  1721. if (CONFIG_ERROR_RESILIENCE) {
  1722. memset(&h->er.cur_pic, 0, sizeof(h->er.cur_pic));
  1723. }
  1724. if ((ret = ref_picture(h, &h->cur_pic, h->cur_pic_ptr)) < 0)
  1725. return ret;
  1726. if (CONFIG_ERROR_RESILIENCE) {
  1727. ff_er_frame_start(&h->er);
  1728. memset(&h->er.last_pic, 0, sizeof(h->er.last_pic));
  1729. memset(&h->er.next_pic, 0, sizeof(h->er.next_pic));
  1730. }
  1731. assert(h->linesize && h->uvlinesize);
  1732. for (i = 0; i < 16; i++) {
  1733. h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
  1734. h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->linesize * ((scan8[i] - scan8[0]) >> 3);
  1735. }
  1736. for (i = 0; i < 16; i++) {
  1737. h->block_offset[16 + i] =
  1738. h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
  1739. h->block_offset[48 + 16 + i] =
  1740. h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * h->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
  1741. }
  1742. // s->decode = (h->flags & CODEC_FLAG_PSNR) || !s->encoding ||
  1743. // h->cur_pic.reference /* || h->contains_intra */ || 1;
  1744. /* We mark the current picture as non-reference after allocating it, so
  1745. * that if we break out due to an error it can be released automatically
  1746. * in the next ff_MPV_frame_start().
  1747. */
  1748. h->cur_pic_ptr->reference = 0;
  1749. h->cur_pic_ptr->field_poc[0] = h->cur_pic_ptr->field_poc[1] = INT_MAX;
  1750. h->next_output_pic = NULL;
  1751. assert(h->cur_pic_ptr->long_ref == 0);
  1752. return 0;
  1753. }
  1754. /**
  1755. * Run setup operations that must be run after slice header decoding.
  1756. * This includes finding the next displayed frame.
  1757. *
  1758. * @param h h264 master context
  1759. * @param setup_finished enough NALs have been read that we can call
  1760. * ff_thread_finish_setup()
  1761. */
  1762. static void decode_postinit(H264Context *h, int setup_finished)
  1763. {
  1764. H264Picture *out = h->cur_pic_ptr;
  1765. H264Picture *cur = h->cur_pic_ptr;
  1766. int i, pics, out_of_order, out_idx;
  1767. h->cur_pic_ptr->f.pict_type = h->pict_type;
  1768. if (h->next_output_pic)
  1769. return;
  1770. if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
  1771. /* FIXME: if we have two PAFF fields in one packet, we can't start
  1772. * the next thread here. If we have one field per packet, we can.
  1773. * The check in decode_nal_units() is not good enough to find this
  1774. * yet, so we assume the worst for now. */
  1775. // if (setup_finished)
  1776. // ff_thread_finish_setup(h->avctx);
  1777. return;
  1778. }
  1779. cur->f.interlaced_frame = 0;
  1780. cur->f.repeat_pict = 0;
  1781. /* Signal interlacing information externally. */
  1782. /* Prioritize picture timing SEI information over used
  1783. * decoding process if it exists. */
  1784. if (h->sps.pic_struct_present_flag) {
  1785. switch (h->sei_pic_struct) {
  1786. case SEI_PIC_STRUCT_FRAME:
  1787. break;
  1788. case SEI_PIC_STRUCT_TOP_FIELD:
  1789. case SEI_PIC_STRUCT_BOTTOM_FIELD:
  1790. cur->f.interlaced_frame = 1;
  1791. break;
  1792. case SEI_PIC_STRUCT_TOP_BOTTOM:
  1793. case SEI_PIC_STRUCT_BOTTOM_TOP:
  1794. if (FIELD_OR_MBAFF_PICTURE(h))
  1795. cur->f.interlaced_frame = 1;
  1796. else
  1797. // try to flag soft telecine progressive
  1798. cur->f.interlaced_frame = h->prev_interlaced_frame;
  1799. break;
  1800. case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
  1801. case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
  1802. /* Signal the possibility of telecined film externally
  1803. * (pic_struct 5,6). From these hints, let the applications
  1804. * decide if they apply deinterlacing. */
  1805. cur->f.repeat_pict = 1;
  1806. break;
  1807. case SEI_PIC_STRUCT_FRAME_DOUBLING:
  1808. cur->f.repeat_pict = 2;
  1809. break;
  1810. case SEI_PIC_STRUCT_FRAME_TRIPLING:
  1811. cur->f.repeat_pict = 4;
  1812. break;
  1813. }
  1814. if ((h->sei_ct_type & 3) &&
  1815. h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
  1816. cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
  1817. } else {
  1818. /* Derive interlacing flag from used decoding process. */
  1819. cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE(h);
  1820. }
  1821. h->prev_interlaced_frame = cur->f.interlaced_frame;
  1822. if (cur->field_poc[0] != cur->field_poc[1]) {
  1823. /* Derive top_field_first from field pocs. */
  1824. cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
  1825. } else {
  1826. if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
  1827. /* Use picture timing SEI information. Even if it is a
  1828. * information of a past frame, better than nothing. */
  1829. if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
  1830. h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
  1831. cur->f.top_field_first = 1;
  1832. else
  1833. cur->f.top_field_first = 0;
  1834. } else {
  1835. /* Most likely progressive */
  1836. cur->f.top_field_first = 0;
  1837. }
  1838. }
  1839. if (h->sei_frame_packing_present &&
  1840. h->frame_packing_arrangement_type >= 0 &&
  1841. h->frame_packing_arrangement_type <= 6 &&
  1842. h->content_interpretation_type > 0 &&
  1843. h->content_interpretation_type < 3) {
  1844. AVStereo3D *stereo = av_stereo3d_create_side_data(&cur->f);
  1845. if (!stereo)
  1846. return;
  1847. switch (h->frame_packing_arrangement_type) {
  1848. case 0:
  1849. stereo->type = AV_STEREO3D_CHECKERBOARD;
  1850. break;
  1851. case 1:
  1852. stereo->type = AV_STEREO3D_LINES;
  1853. break;
  1854. case 2:
  1855. stereo->type = AV_STEREO3D_COLUMNS;
  1856. break;
  1857. case 3:
  1858. if (h->quincunx_subsampling)
  1859. stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
  1860. else
  1861. stereo->type = AV_STEREO3D_SIDEBYSIDE;
  1862. break;
  1863. case 4:
  1864. stereo->type = AV_STEREO3D_TOPBOTTOM;
  1865. break;
  1866. case 5:
  1867. stereo->type = AV_STEREO3D_FRAMESEQUENCE;
  1868. break;
  1869. case 6:
  1870. stereo->type = AV_STEREO3D_2D;
  1871. break;
  1872. }
  1873. if (h->content_interpretation_type == 2)
  1874. stereo->flags = AV_STEREO3D_FLAG_INVERT;
  1875. }
  1876. cur->mmco_reset = h->mmco_reset;
  1877. h->mmco_reset = 0;
  1878. // FIXME do something with unavailable reference frames
  1879. /* Sort B-frames into display order */
  1880. if (h->sps.bitstream_restriction_flag &&
  1881. h->avctx->has_b_frames < h->sps.num_reorder_frames) {
  1882. h->avctx->has_b_frames = h->sps.num_reorder_frames;
  1883. h->low_delay = 0;
  1884. }
  1885. if (h->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
  1886. !h->sps.bitstream_restriction_flag) {
  1887. h->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
  1888. h->low_delay = 0;
  1889. }
  1890. for (i = 0; 1; i++) {
  1891. if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
  1892. if(i)
  1893. h->last_pocs[i-1] = cur->poc;
  1894. break;
  1895. } else if(i) {
  1896. h->last_pocs[i-1]= h->last_pocs[i];
  1897. }
  1898. }
  1899. out_of_order = MAX_DELAYED_PIC_COUNT - i;
  1900. if( cur->f.pict_type == AV_PICTURE_TYPE_B
  1901. || (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))
  1902. out_of_order = FFMAX(out_of_order, 1);
  1903. if (out_of_order == MAX_DELAYED_PIC_COUNT) {
  1904. av_log(h->avctx, AV_LOG_VERBOSE, "Invalid POC %d<%d\n", cur->poc, h->last_pocs[0]);
  1905. for (i = 1; i < MAX_DELAYED_PIC_COUNT; i++)
  1906. h->last_pocs[i] = INT_MIN;
  1907. h->last_pocs[0] = cur->poc;
  1908. cur->mmco_reset = 1;
  1909. } else if(h->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
  1910. av_log(h->avctx, AV_LOG_VERBOSE, "Increasing reorder buffer to %d\n", out_of_order);
  1911. h->avctx->has_b_frames = out_of_order;
  1912. h->low_delay = 0;
  1913. }
  1914. pics = 0;
  1915. while (h->delayed_pic[pics])
  1916. pics++;
  1917. av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
  1918. h->delayed_pic[pics++] = cur;
  1919. if (cur->reference == 0)
  1920. cur->reference = DELAYED_PIC_REF;
  1921. out = h->delayed_pic[0];
  1922. out_idx = 0;
  1923. for (i = 1; h->delayed_pic[i] &&
  1924. !h->delayed_pic[i]->f.key_frame &&
  1925. !h->delayed_pic[i]->mmco_reset;
  1926. i++)
  1927. if (h->delayed_pic[i]->poc < out->poc) {
  1928. out = h->delayed_pic[i];
  1929. out_idx = i;
  1930. }
  1931. if (h->avctx->has_b_frames == 0 &&
  1932. (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset))
  1933. h->next_outputed_poc = INT_MIN;
  1934. out_of_order = out->poc < h->next_outputed_poc;
  1935. if (out_of_order || pics > h->avctx->has_b_frames) {
  1936. out->reference &= ~DELAYED_PIC_REF;
  1937. // for frame threading, the owner must be the second field's thread or
  1938. // else the first thread can release the picture and reuse it unsafely
  1939. for (i = out_idx; h->delayed_pic[i]; i++)
  1940. h->delayed_pic[i] = h->delayed_pic[i + 1];
  1941. }
  1942. if (!out_of_order && pics > h->avctx->has_b_frames) {
  1943. h->next_output_pic = out;
  1944. if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset)) {
  1945. h->next_outputed_poc = INT_MIN;
  1946. } else
  1947. h->next_outputed_poc = out->poc;
  1948. } else {
  1949. av_log(h->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
  1950. }
  1951. if (h->next_output_pic) {
  1952. if (h->next_output_pic->recovered) {
  1953. // We have reached an recovery point and all frames after it in
  1954. // display order are "recovered".
  1955. h->frame_recovered |= FRAME_RECOVERED_SEI;
  1956. }
  1957. h->next_output_pic->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_SEI);
  1958. }
  1959. if (setup_finished && !h->avctx->hwaccel)
  1960. ff_thread_finish_setup(h->avctx);
  1961. }
  1962. static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
  1963. uint8_t *src_cb, uint8_t *src_cr,
  1964. int linesize, int uvlinesize,
  1965. int simple)
  1966. {
  1967. uint8_t *top_border;
  1968. int top_idx = 1;
  1969. const int pixel_shift = h->pixel_shift;
  1970. int chroma444 = CHROMA444(h);
  1971. int chroma422 = CHROMA422(h);
  1972. src_y -= linesize;
  1973. src_cb -= uvlinesize;
  1974. src_cr -= uvlinesize;
  1975. if (!simple && FRAME_MBAFF(h)) {
  1976. if (h->mb_y & 1) {
  1977. if (!MB_MBAFF(h)) {
  1978. top_border = h->top_borders[0][h->mb_x];
  1979. AV_COPY128(top_border, src_y + 15 * linesize);
  1980. if (pixel_shift)
  1981. AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
  1982. if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
  1983. if (chroma444) {
  1984. if (pixel_shift) {
  1985. AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
  1986. AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
  1987. AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
  1988. AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
  1989. } else {
  1990. AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
  1991. AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
  1992. }
  1993. } else if (chroma422) {
  1994. if (pixel_shift) {
  1995. AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
  1996. AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
  1997. } else {
  1998. AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
  1999. AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
  2000. }
  2001. } else {
  2002. if (pixel_shift) {
  2003. AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
  2004. AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
  2005. } else {
  2006. AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
  2007. AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
  2008. }
  2009. }
  2010. }
  2011. }
  2012. } else if (MB_MBAFF(h)) {
  2013. top_idx = 0;
  2014. } else
  2015. return;
  2016. }
  2017. top_border = h->top_borders[top_idx][h->mb_x];
  2018. /* There are two lines saved, the line above the top macroblock
  2019. * of a pair, and the line above the bottom macroblock. */
  2020. AV_COPY128(top_border, src_y + 16 * linesize);
  2021. if (pixel_shift)
  2022. AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
  2023. if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
  2024. if (chroma444) {
  2025. if (pixel_shift) {
  2026. AV_COPY128(top_border + 32, src_cb + 16 * linesize);
  2027. AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
  2028. AV_COPY128(top_border + 64, src_cr + 16 * linesize);
  2029. AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
  2030. } else {
  2031. AV_COPY128(top_border + 16, src_cb + 16 * linesize);
  2032. AV_COPY128(top_border + 32, src_cr + 16 * linesize);
  2033. }
  2034. } else if (chroma422) {
  2035. if (pixel_shift) {
  2036. AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
  2037. AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
  2038. } else {
  2039. AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
  2040. AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
  2041. }
  2042. } else {
  2043. if (pixel_shift) {
  2044. AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
  2045. AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
  2046. } else {
  2047. AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
  2048. AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
  2049. }
  2050. }
  2051. }
  2052. }
  2053. static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
  2054. uint8_t *src_cb, uint8_t *src_cr,
  2055. int linesize, int uvlinesize,
  2056. int xchg, int chroma444,
  2057. int simple, int pixel_shift)
  2058. {
  2059. int deblock_topleft;
  2060. int deblock_top;
  2061. int top_idx = 1;
  2062. uint8_t *top_border_m1;
  2063. uint8_t *top_border;
  2064. if (!simple && FRAME_MBAFF(h)) {
  2065. if (h->mb_y & 1) {
  2066. if (!MB_MBAFF(h))
  2067. return;
  2068. } else {
  2069. top_idx = MB_MBAFF(h) ? 0 : 1;
  2070. }
  2071. }
  2072. if (h->deblocking_filter == 2) {
  2073. deblock_topleft = h->slice_table[h->mb_xy - 1 - h->mb_stride] == h->slice_num;
  2074. deblock_top = h->top_type;
  2075. } else {
  2076. deblock_topleft = (h->mb_x > 0);
  2077. deblock_top = (h->mb_y > !!MB_FIELD(h));
  2078. }
  2079. src_y -= linesize + 1 + pixel_shift;
  2080. src_cb -= uvlinesize + 1 + pixel_shift;
  2081. src_cr -= uvlinesize + 1 + pixel_shift;
  2082. top_border_m1 = h->top_borders[top_idx][h->mb_x - 1];
  2083. top_border = h->top_borders[top_idx][h->mb_x];
  2084. #define XCHG(a, b, xchg) \
  2085. if (pixel_shift) { \
  2086. if (xchg) { \
  2087. AV_SWAP64(b + 0, a + 0); \
  2088. AV_SWAP64(b + 8, a + 8); \
  2089. } else { \
  2090. AV_COPY128(b, a); \
  2091. } \
  2092. } else if (xchg) \
  2093. AV_SWAP64(b, a); \
  2094. else \
  2095. AV_COPY64(b, a);
  2096. if (deblock_top) {
  2097. if (deblock_topleft) {
  2098. XCHG(top_border_m1 + (8 << pixel_shift),
  2099. src_y - (7 << pixel_shift), 1);
  2100. }
  2101. XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
  2102. XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
  2103. if (h->mb_x + 1 < h->mb_width) {
  2104. XCHG(h->top_borders[top_idx][h->mb_x + 1],
  2105. src_y + (17 << pixel_shift), 1);
  2106. }
  2107. if (simple || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) {
  2108. if (chroma444) {
  2109. if (deblock_topleft) {
  2110. XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
  2111. XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
  2112. }
  2113. XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
  2114. XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
  2115. XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
  2116. XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
  2117. if (h->mb_x + 1 < h->mb_width) {
  2118. XCHG(h->top_borders[top_idx][h->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
  2119. XCHG(h->top_borders[top_idx][h->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
  2120. }
  2121. } else {
  2122. if (deblock_topleft) {
  2123. XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
  2124. XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
  2125. }
  2126. XCHG(top_border + (16 << pixel_shift), src_cb + 1 + pixel_shift, 1);
  2127. XCHG(top_border + (24 << pixel_shift), src_cr + 1 + pixel_shift, 1);
  2128. }
  2129. }
  2130. }
  2131. }
  2132. static av_always_inline int dctcoef_get(int16_t *mb, int high_bit_depth,
  2133. int index)
  2134. {
  2135. if (high_bit_depth) {
  2136. return AV_RN32A(((int32_t *)mb) + index);
  2137. } else
  2138. return AV_RN16A(mb + index);
  2139. }
  2140. static av_always_inline void dctcoef_set(int16_t *mb, int high_bit_depth,
  2141. int index, int value)
  2142. {
  2143. if (high_bit_depth) {
  2144. AV_WN32A(((int32_t *)mb) + index, value);
  2145. } else
  2146. AV_WN16A(mb + index, value);
  2147. }
  2148. static av_always_inline void hl_decode_mb_predict_luma(H264Context *h,
  2149. int mb_type, int is_h264,
  2150. int simple,
  2151. int transform_bypass,
  2152. int pixel_shift,
  2153. int *block_offset,
  2154. int linesize,
  2155. uint8_t *dest_y, int p)
  2156. {
  2157. void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
  2158. void (*idct_dc_add)(uint8_t *dst, int16_t *block, int stride);
  2159. int i;
  2160. int qscale = p == 0 ? h->qscale : h->chroma_qp[p - 1];
  2161. block_offset += 16 * p;
  2162. if (IS_INTRA4x4(mb_type)) {
  2163. if (IS_8x8DCT(mb_type)) {
  2164. if (transform_bypass) {
  2165. idct_dc_add =
  2166. idct_add = h->h264dsp.h264_add_pixels8_clear;
  2167. } else {
  2168. idct_dc_add = h->h264dsp.h264_idct8_dc_add;
  2169. idct_add = h->h264dsp.h264_idct8_add;
  2170. }
  2171. for (i = 0; i < 16; i += 4) {
  2172. uint8_t *const ptr = dest_y + block_offset[i];
  2173. const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
  2174. if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
  2175. h->hpc.pred8x8l_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  2176. } else {
  2177. const int nnz = h->non_zero_count_cache[scan8[i + p * 16]];
  2178. h->hpc.pred8x8l[dir](ptr, (h->topleft_samples_available << i) & 0x8000,
  2179. (h->topright_samples_available << i) & 0x4000, linesize);
  2180. if (nnz) {
  2181. if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
  2182. idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  2183. else
  2184. idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  2185. }
  2186. }
  2187. }
  2188. } else {
  2189. if (transform_bypass) {
  2190. idct_dc_add =
  2191. idct_add = h->h264dsp.h264_add_pixels4_clear;
  2192. } else {
  2193. idct_dc_add = h->h264dsp.h264_idct_dc_add;
  2194. idct_add = h->h264dsp.h264_idct_add;
  2195. }
  2196. for (i = 0; i < 16; i++) {
  2197. uint8_t *const ptr = dest_y + block_offset[i];
  2198. const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
  2199. if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
  2200. h->hpc.pred4x4_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  2201. } else {
  2202. uint8_t *topright;
  2203. int nnz, tr;
  2204. uint64_t tr_high;
  2205. if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
  2206. const int topright_avail = (h->topright_samples_available << i) & 0x8000;
  2207. av_assert2(h->mb_y || linesize <= block_offset[i]);
  2208. if (!topright_avail) {
  2209. if (pixel_shift) {
  2210. tr_high = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
  2211. topright = (uint8_t *)&tr_high;
  2212. } else {
  2213. tr = ptr[3 - linesize] * 0x01010101u;
  2214. topright = (uint8_t *)&tr;
  2215. }
  2216. } else
  2217. topright = ptr + (4 << pixel_shift) - linesize;
  2218. } else
  2219. topright = NULL;
  2220. h->hpc.pred4x4[dir](ptr, topright, linesize);
  2221. nnz = h->non_zero_count_cache[scan8[i + p * 16]];
  2222. if (nnz) {
  2223. if (is_h264) {
  2224. if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
  2225. idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  2226. else
  2227. idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  2228. } else if (CONFIG_SVQ3_DECODER)
  2229. ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize, qscale, 0);
  2230. }
  2231. }
  2232. }
  2233. }
  2234. } else {
  2235. h->hpc.pred16x16[h->intra16x16_pred_mode](dest_y, linesize);
  2236. if (is_h264) {
  2237. if (h->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {
  2238. if (!transform_bypass)
  2239. h->h264dsp.h264_luma_dc_dequant_idct(h->mb + (p * 256 << pixel_shift),
  2240. h->mb_luma_dc[p],
  2241. h->dequant4_coeff[p][qscale][0]);
  2242. else {
  2243. static const uint8_t dc_mapping[16] = {
  2244. 0 * 16, 1 * 16, 4 * 16, 5 * 16,
  2245. 2 * 16, 3 * 16, 6 * 16, 7 * 16,
  2246. 8 * 16, 9 * 16, 12 * 16, 13 * 16,
  2247. 10 * 16, 11 * 16, 14 * 16, 15 * 16
  2248. };
  2249. for (i = 0; i < 16; i++)
  2250. dctcoef_set(h->mb + (p * 256 << pixel_shift),
  2251. pixel_shift, dc_mapping[i],
  2252. dctcoef_get(h->mb_luma_dc[p],
  2253. pixel_shift, i));
  2254. }
  2255. }
  2256. } else if (CONFIG_SVQ3_DECODER)
  2257. ff_svq3_luma_dc_dequant_idct_c(h->mb + p * 256,
  2258. h->mb_luma_dc[p], qscale);
  2259. }
  2260. }
  2261. static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type,
  2262. int is_h264, int simple,
  2263. int transform_bypass,
  2264. int pixel_shift,
  2265. int *block_offset,
  2266. int linesize,
  2267. uint8_t *dest_y, int p)
  2268. {
  2269. void (*idct_add)(uint8_t *dst, int16_t *block, int stride);
  2270. int i;
  2271. block_offset += 16 * p;
  2272. if (!IS_INTRA4x4(mb_type)) {
  2273. if (is_h264) {
  2274. if (IS_INTRA16x16(mb_type)) {
  2275. if (transform_bypass) {
  2276. if (h->sps.profile_idc == 244 &&
  2277. (h->intra16x16_pred_mode == VERT_PRED8x8 ||
  2278. h->intra16x16_pred_mode == HOR_PRED8x8)) {
  2279. h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset,
  2280. h->mb + (p * 256 << pixel_shift),
  2281. linesize);
  2282. } else {
  2283. for (i = 0; i < 16; i++)
  2284. if (h->non_zero_count_cache[scan8[i + p * 16]] ||
  2285. dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
  2286. h->h264dsp.h264_add_pixels4_clear(dest_y + block_offset[i],
  2287. h->mb + (i * 16 + p * 256 << pixel_shift),
  2288. linesize);
  2289. }
  2290. } else {
  2291. h->h264dsp.h264_idct_add16intra(dest_y, block_offset,
  2292. h->mb + (p * 256 << pixel_shift),
  2293. linesize,
  2294. h->non_zero_count_cache + p * 5 * 8);
  2295. }
  2296. } else if (h->cbp & 15) {
  2297. if (transform_bypass) {
  2298. const int di = IS_8x8DCT(mb_type) ? 4 : 1;
  2299. idct_add = IS_8x8DCT(mb_type) ? h->h264dsp.h264_add_pixels8_clear
  2300. : h->h264dsp.h264_add_pixels4_clear;
  2301. for (i = 0; i < 16; i += di)
  2302. if (h->non_zero_count_cache[scan8[i + p * 16]])
  2303. idct_add(dest_y + block_offset[i],
  2304. h->mb + (i * 16 + p * 256 << pixel_shift),
  2305. linesize);
  2306. } else {
  2307. if (IS_8x8DCT(mb_type))
  2308. h->h264dsp.h264_idct8_add4(dest_y, block_offset,
  2309. h->mb + (p * 256 << pixel_shift),
  2310. linesize,
  2311. h->non_zero_count_cache + p * 5 * 8);
  2312. else
  2313. h->h264dsp.h264_idct_add16(dest_y, block_offset,
  2314. h->mb + (p * 256 << pixel_shift),
  2315. linesize,
  2316. h->non_zero_count_cache + p * 5 * 8);
  2317. }
  2318. }
  2319. } else if (CONFIG_SVQ3_DECODER) {
  2320. for (i = 0; i < 16; i++)
  2321. if (h->non_zero_count_cache[scan8[i + p * 16]] || h->mb[i * 16 + p * 256]) {
  2322. // FIXME benchmark weird rule, & below
  2323. uint8_t *const ptr = dest_y + block_offset[i];
  2324. ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize,
  2325. h->qscale, IS_INTRA(mb_type) ? 1 : 0);
  2326. }
  2327. }
  2328. }
  2329. }
  2330. #define BITS 8
  2331. #define SIMPLE 1
  2332. #include "h264_mb_template.c"
  2333. #undef BITS
  2334. #define BITS 16
  2335. #include "h264_mb_template.c"
  2336. #undef SIMPLE
  2337. #define SIMPLE 0
  2338. #include "h264_mb_template.c"
  2339. void ff_h264_hl_decode_mb(H264Context *h)
  2340. {
  2341. const int mb_xy = h->mb_xy;
  2342. const int mb_type = h->cur_pic.mb_type[mb_xy];
  2343. int is_complex = CONFIG_SMALL || h->is_complex ||
  2344. IS_INTRA_PCM(mb_type) || h->qscale == 0;
  2345. if (CHROMA444(h)) {
  2346. if (is_complex || h->pixel_shift)
  2347. hl_decode_mb_444_complex(h);
  2348. else
  2349. hl_decode_mb_444_simple_8(h);
  2350. } else if (is_complex) {
  2351. hl_decode_mb_complex(h);
  2352. } else if (h->pixel_shift) {
  2353. hl_decode_mb_simple_16(h);
  2354. } else
  2355. hl_decode_mb_simple_8(h);
  2356. }
  2357. int ff_pred_weight_table(H264Context *h)
  2358. {
  2359. int list, i;
  2360. int luma_def, chroma_def;
  2361. h->use_weight = 0;
  2362. h->use_weight_chroma = 0;
  2363. h->luma_log2_weight_denom = get_ue_golomb(&h->gb);
  2364. if (h->sps.chroma_format_idc)
  2365. h->chroma_log2_weight_denom = get_ue_golomb(&h->gb);
  2366. luma_def = 1 << h->luma_log2_weight_denom;
  2367. chroma_def = 1 << h->chroma_log2_weight_denom;
  2368. for (list = 0; list < 2; list++) {
  2369. h->luma_weight_flag[list] = 0;
  2370. h->chroma_weight_flag[list] = 0;
  2371. for (i = 0; i < h->ref_count[list]; i++) {
  2372. int luma_weight_flag, chroma_weight_flag;
  2373. luma_weight_flag = get_bits1(&h->gb);
  2374. if (luma_weight_flag) {
  2375. h->luma_weight[i][list][0] = get_se_golomb(&h->gb);
  2376. h->luma_weight[i][list][1] = get_se_golomb(&h->gb);
  2377. if (h->luma_weight[i][list][0] != luma_def ||
  2378. h->luma_weight[i][list][1] != 0) {
  2379. h->use_weight = 1;
  2380. h->luma_weight_flag[list] = 1;
  2381. }
  2382. } else {
  2383. h->luma_weight[i][list][0] = luma_def;
  2384. h->luma_weight[i][list][1] = 0;
  2385. }
  2386. if (h->sps.chroma_format_idc) {
  2387. chroma_weight_flag = get_bits1(&h->gb);
  2388. if (chroma_weight_flag) {
  2389. int j;
  2390. for (j = 0; j < 2; j++) {
  2391. h->chroma_weight[i][list][j][0] = get_se_golomb(&h->gb);
  2392. h->chroma_weight[i][list][j][1] = get_se_golomb(&h->gb);
  2393. if (h->chroma_weight[i][list][j][0] != chroma_def ||
  2394. h->chroma_weight[i][list][j][1] != 0) {
  2395. h->use_weight_chroma = 1;
  2396. h->chroma_weight_flag[list] = 1;
  2397. }
  2398. }
  2399. } else {
  2400. int j;
  2401. for (j = 0; j < 2; j++) {
  2402. h->chroma_weight[i][list][j][0] = chroma_def;
  2403. h->chroma_weight[i][list][j][1] = 0;
  2404. }
  2405. }
  2406. }
  2407. }
  2408. if (h->slice_type_nos != AV_PICTURE_TYPE_B)
  2409. break;
  2410. }
  2411. h->use_weight = h->use_weight || h->use_weight_chroma;
  2412. return 0;
  2413. }
  2414. /**
  2415. * Initialize implicit_weight table.
  2416. * @param field 0/1 initialize the weight for interlaced MBAFF
  2417. * -1 initializes the rest
  2418. */
  2419. static void implicit_weight_table(H264Context *h, int field)
  2420. {
  2421. int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
  2422. for (i = 0; i < 2; i++) {
  2423. h->luma_weight_flag[i] = 0;
  2424. h->chroma_weight_flag[i] = 0;
  2425. }
  2426. if (field < 0) {
  2427. if (h->picture_structure == PICT_FRAME) {
  2428. cur_poc = h->cur_pic_ptr->poc;
  2429. } else {
  2430. cur_poc = h->cur_pic_ptr->field_poc[h->picture_structure - 1];
  2431. }
  2432. if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF(h) &&
  2433. h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) {
  2434. h->use_weight = 0;
  2435. h->use_weight_chroma = 0;
  2436. return;
  2437. }
  2438. ref_start = 0;
  2439. ref_count0 = h->ref_count[0];
  2440. ref_count1 = h->ref_count[1];
  2441. } else {
  2442. cur_poc = h->cur_pic_ptr->field_poc[field];
  2443. ref_start = 16;
  2444. ref_count0 = 16 + 2 * h->ref_count[0];
  2445. ref_count1 = 16 + 2 * h->ref_count[1];
  2446. }
  2447. h->use_weight = 2;
  2448. h->use_weight_chroma = 2;
  2449. h->luma_log2_weight_denom = 5;
  2450. h->chroma_log2_weight_denom = 5;
  2451. for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
  2452. int poc0 = h->ref_list[0][ref0].poc;
  2453. for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
  2454. int w = 32;
  2455. if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
  2456. int poc1 = h->ref_list[1][ref1].poc;
  2457. int td = av_clip(poc1 - poc0, -128, 127);
  2458. if (td) {
  2459. int tb = av_clip(cur_poc - poc0, -128, 127);
  2460. int tx = (16384 + (FFABS(td) >> 1)) / td;
  2461. int dist_scale_factor = (tb * tx + 32) >> 8;
  2462. if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
  2463. w = 64 - dist_scale_factor;
  2464. }
  2465. }
  2466. if (field < 0) {
  2467. h->implicit_weight[ref0][ref1][0] =
  2468. h->implicit_weight[ref0][ref1][1] = w;
  2469. } else {
  2470. h->implicit_weight[ref0][ref1][field] = w;
  2471. }
  2472. }
  2473. }
  2474. }
  2475. /**
  2476. * instantaneous decoder refresh.
  2477. */
  2478. static void idr(H264Context *h)
  2479. {
  2480. int i;
  2481. ff_h264_remove_all_refs(h);
  2482. h->prev_frame_num = 0;
  2483. h->prev_frame_num_offset = 0;
  2484. h->prev_poc_msb = 1<<16;
  2485. h->prev_poc_lsb = 0;
  2486. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  2487. h->last_pocs[i] = INT_MIN;
  2488. }
  2489. /* forget old pics after a seek */
  2490. static void flush_change(H264Context *h)
  2491. {
  2492. int i, j;
  2493. h->outputed_poc = h->next_outputed_poc = INT_MIN;
  2494. h->prev_interlaced_frame = 1;
  2495. idr(h);
  2496. h->prev_frame_num = -1;
  2497. if (h->cur_pic_ptr) {
  2498. h->cur_pic_ptr->reference = 0;
  2499. for (j=i=0; h->delayed_pic[i]; i++)
  2500. if (h->delayed_pic[i] != h->cur_pic_ptr)
  2501. h->delayed_pic[j++] = h->delayed_pic[i];
  2502. h->delayed_pic[j] = NULL;
  2503. }
  2504. h->first_field = 0;
  2505. memset(h->ref_list[0], 0, sizeof(h->ref_list[0]));
  2506. memset(h->ref_list[1], 0, sizeof(h->ref_list[1]));
  2507. memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0]));
  2508. memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1]));
  2509. ff_h264_reset_sei(h);
  2510. h->recovery_frame = -1;
  2511. h->frame_recovered = 0;
  2512. h->list_count = 0;
  2513. h->current_slice = 0;
  2514. h->mmco_reset = 1;
  2515. }
  2516. /* forget old pics after a seek */
  2517. static void flush_dpb(AVCodecContext *avctx)
  2518. {
  2519. H264Context *h = avctx->priv_data;
  2520. int i;
  2521. for (i = 0; i <= MAX_DELAYED_PIC_COUNT; i++) {
  2522. if (h->delayed_pic[i])
  2523. h->delayed_pic[i]->reference = 0;
  2524. h->delayed_pic[i] = NULL;
  2525. }
  2526. flush_change(h);
  2527. if (h->DPB)
  2528. for (i = 0; i < H264_MAX_PICTURE_COUNT; i++)
  2529. unref_picture(h, &h->DPB[i]);
  2530. h->cur_pic_ptr = NULL;
  2531. unref_picture(h, &h->cur_pic);
  2532. h->mb_x = h->mb_y = 0;
  2533. h->parse_context.state = -1;
  2534. h->parse_context.frame_start_found = 0;
  2535. h->parse_context.overread = 0;
  2536. h->parse_context.overread_index = 0;
  2537. h->parse_context.index = 0;
  2538. h->parse_context.last_index = 0;
  2539. free_tables(h, 1);
  2540. h->context_initialized = 0;
  2541. }
  2542. int ff_init_poc(H264Context *h, int pic_field_poc[2], int *pic_poc)
  2543. {
  2544. const int max_frame_num = 1 << h->sps.log2_max_frame_num;
  2545. int field_poc[2];
  2546. h->frame_num_offset = h->prev_frame_num_offset;
  2547. if (h->frame_num < h->prev_frame_num)
  2548. h->frame_num_offset += max_frame_num;
  2549. if (h->sps.poc_type == 0) {
  2550. const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
  2551. if (h->poc_lsb < h->prev_poc_lsb &&
  2552. h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
  2553. h->poc_msb = h->prev_poc_msb + max_poc_lsb;
  2554. else if (h->poc_lsb > h->prev_poc_lsb &&
  2555. h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
  2556. h->poc_msb = h->prev_poc_msb - max_poc_lsb;
  2557. else
  2558. h->poc_msb = h->prev_poc_msb;
  2559. field_poc[0] =
  2560. field_poc[1] = h->poc_msb + h->poc_lsb;
  2561. if (h->picture_structure == PICT_FRAME)
  2562. field_poc[1] += h->delta_poc_bottom;
  2563. } else if (h->sps.poc_type == 1) {
  2564. int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
  2565. int i;
  2566. if (h->sps.poc_cycle_length != 0)
  2567. abs_frame_num = h->frame_num_offset + h->frame_num;
  2568. else
  2569. abs_frame_num = 0;
  2570. if (h->nal_ref_idc == 0 && abs_frame_num > 0)
  2571. abs_frame_num--;
  2572. expected_delta_per_poc_cycle = 0;
  2573. for (i = 0; i < h->sps.poc_cycle_length; i++)
  2574. // FIXME integrate during sps parse
  2575. expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
  2576. if (abs_frame_num > 0) {
  2577. int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
  2578. int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
  2579. expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
  2580. for (i = 0; i <= frame_num_in_poc_cycle; i++)
  2581. expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
  2582. } else
  2583. expectedpoc = 0;
  2584. if (h->nal_ref_idc == 0)
  2585. expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
  2586. field_poc[0] = expectedpoc + h->delta_poc[0];
  2587. field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
  2588. if (h->picture_structure == PICT_FRAME)
  2589. field_poc[1] += h->delta_poc[1];
  2590. } else {
  2591. int poc = 2 * (h->frame_num_offset + h->frame_num);
  2592. if (!h->nal_ref_idc)
  2593. poc--;
  2594. field_poc[0] = poc;
  2595. field_poc[1] = poc;
  2596. }
  2597. if (h->picture_structure != PICT_BOTTOM_FIELD)
  2598. pic_field_poc[0] = field_poc[0];
  2599. if (h->picture_structure != PICT_TOP_FIELD)
  2600. pic_field_poc[1] = field_poc[1];
  2601. *pic_poc = FFMIN(pic_field_poc[0], pic_field_poc[1]);
  2602. return 0;
  2603. }
  2604. /**
  2605. * initialize scan tables
  2606. */
  2607. static void init_scan_tables(H264Context *h)
  2608. {
  2609. int i;
  2610. for (i = 0; i < 16; i++) {
  2611. #define TRANSPOSE(x) (x >> 2) | ((x << 2) & 0xF)
  2612. h->zigzag_scan[i] = TRANSPOSE(zigzag_scan[i]);
  2613. h->field_scan[i] = TRANSPOSE(field_scan[i]);
  2614. #undef TRANSPOSE
  2615. }
  2616. for (i = 0; i < 64; i++) {
  2617. #define TRANSPOSE(x) (x >> 3) | ((x & 7) << 3)
  2618. h->zigzag_scan8x8[i] = TRANSPOSE(ff_zigzag_direct[i]);
  2619. h->zigzag_scan8x8_cavlc[i] = TRANSPOSE(zigzag_scan8x8_cavlc[i]);
  2620. h->field_scan8x8[i] = TRANSPOSE(field_scan8x8[i]);
  2621. h->field_scan8x8_cavlc[i] = TRANSPOSE(field_scan8x8_cavlc[i]);
  2622. #undef TRANSPOSE
  2623. }
  2624. if (h->sps.transform_bypass) { // FIXME same ugly
  2625. memcpy(h->zigzag_scan_q0 , zigzag_scan , sizeof(h->zigzag_scan_q0 ));
  2626. memcpy(h->zigzag_scan8x8_q0 , ff_zigzag_direct , sizeof(h->zigzag_scan8x8_q0 ));
  2627. memcpy(h->zigzag_scan8x8_cavlc_q0 , zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
  2628. memcpy(h->field_scan_q0 , field_scan , sizeof(h->field_scan_q0 ));
  2629. memcpy(h->field_scan8x8_q0 , field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
  2630. memcpy(h->field_scan8x8_cavlc_q0 , field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
  2631. } else {
  2632. memcpy(h->zigzag_scan_q0 , h->zigzag_scan , sizeof(h->zigzag_scan_q0 ));
  2633. memcpy(h->zigzag_scan8x8_q0 , h->zigzag_scan8x8 , sizeof(h->zigzag_scan8x8_q0 ));
  2634. memcpy(h->zigzag_scan8x8_cavlc_q0 , h->zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
  2635. memcpy(h->field_scan_q0 , h->field_scan , sizeof(h->field_scan_q0 ));
  2636. memcpy(h->field_scan8x8_q0 , h->field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
  2637. memcpy(h->field_scan8x8_cavlc_q0 , h->field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
  2638. }
  2639. }
  2640. #if CONFIG_ERROR_RESILIENCE
  2641. static void h264_set_erpic(ERPicture *dst, H264Picture *src)
  2642. {
  2643. int i;
  2644. memset(dst, 0, sizeof(*dst));
  2645. if (!src)
  2646. return;
  2647. dst->f = &src->f;
  2648. dst->tf = &src->tf;
  2649. for (i = 0; i < 2; i++) {
  2650. dst->motion_val[i] = src->motion_val[i];
  2651. dst->ref_index[i] = src->ref_index[i];
  2652. }
  2653. dst->mb_type = src->mb_type;
  2654. dst->field_picture = src->field_picture;
  2655. }
  2656. #endif /* CONFIG_ERROR_RESILIENCE */
  2657. static int field_end(H264Context *h, int in_setup)
  2658. {
  2659. AVCodecContext *const avctx = h->avctx;
  2660. int err = 0;
  2661. h->mb_y = 0;
  2662. if (CONFIG_H264_VDPAU_DECODER &&
  2663. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  2664. ff_vdpau_h264_set_reference_frames(h);
  2665. if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
  2666. if (!h->droppable) {
  2667. err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
  2668. h->prev_poc_msb = h->poc_msb;
  2669. h->prev_poc_lsb = h->poc_lsb;
  2670. }
  2671. h->prev_frame_num_offset = h->frame_num_offset;
  2672. h->prev_frame_num = h->frame_num;
  2673. h->outputed_poc = h->next_outputed_poc;
  2674. }
  2675. if (avctx->hwaccel) {
  2676. if (avctx->hwaccel->end_frame(avctx) < 0)
  2677. av_log(avctx, AV_LOG_ERROR,
  2678. "hardware accelerator failed to decode picture\n");
  2679. }
  2680. if (CONFIG_H264_VDPAU_DECODER &&
  2681. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  2682. ff_vdpau_h264_picture_complete(h);
  2683. /*
  2684. * FIXME: Error handling code does not seem to support interlaced
  2685. * when slices span multiple rows
  2686. * The ff_er_add_slice calls don't work right for bottom
  2687. * fields; they cause massive erroneous error concealing
  2688. * Error marking covers both fields (top and bottom).
  2689. * This causes a mismatched s->error_count
  2690. * and a bad error table. Further, the error count goes to
  2691. * INT_MAX when called for bottom field, because mb_y is
  2692. * past end by one (callers fault) and resync_mb_y != 0
  2693. * causes problems for the first MB line, too.
  2694. */
  2695. if (CONFIG_ERROR_RESILIENCE && !FIELD_PICTURE(h) && h->current_slice && !h->sps.new) {
  2696. h264_set_erpic(&h->er.cur_pic, h->cur_pic_ptr);
  2697. ff_er_frame_end(&h->er);
  2698. }
  2699. if (!in_setup && !h->droppable)
  2700. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
  2701. h->picture_structure == PICT_BOTTOM_FIELD);
  2702. emms_c();
  2703. h->current_slice = 0;
  2704. return err;
  2705. }
  2706. /**
  2707. * Replicate H264 "master" context to thread contexts.
  2708. */
  2709. static int clone_slice(H264Context *dst, H264Context *src)
  2710. {
  2711. memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
  2712. dst->cur_pic_ptr = src->cur_pic_ptr;
  2713. dst->cur_pic = src->cur_pic;
  2714. dst->linesize = src->linesize;
  2715. dst->uvlinesize = src->uvlinesize;
  2716. dst->first_field = src->first_field;
  2717. dst->prev_poc_msb = src->prev_poc_msb;
  2718. dst->prev_poc_lsb = src->prev_poc_lsb;
  2719. dst->prev_frame_num_offset = src->prev_frame_num_offset;
  2720. dst->prev_frame_num = src->prev_frame_num;
  2721. dst->short_ref_count = src->short_ref_count;
  2722. memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
  2723. memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
  2724. memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
  2725. memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
  2726. memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
  2727. return 0;
  2728. }
  2729. /**
  2730. * Compute profile from profile_idc and constraint_set?_flags.
  2731. *
  2732. * @param sps SPS
  2733. *
  2734. * @return profile as defined by FF_PROFILE_H264_*
  2735. */
  2736. int ff_h264_get_profile(SPS *sps)
  2737. {
  2738. int profile = sps->profile_idc;
  2739. switch (sps->profile_idc) {
  2740. case FF_PROFILE_H264_BASELINE:
  2741. // constraint_set1_flag set to 1
  2742. profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
  2743. break;
  2744. case FF_PROFILE_H264_HIGH_10:
  2745. case FF_PROFILE_H264_HIGH_422:
  2746. case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
  2747. // constraint_set3_flag set to 1
  2748. profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
  2749. break;
  2750. }
  2751. return profile;
  2752. }
  2753. static int h264_set_parameter_from_sps(H264Context *h)
  2754. {
  2755. if (h->flags & CODEC_FLAG_LOW_DELAY ||
  2756. (h->sps.bitstream_restriction_flag &&
  2757. !h->sps.num_reorder_frames)) {
  2758. if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
  2759. av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
  2760. "Reenabling low delay requires a codec flush.\n");
  2761. else
  2762. h->low_delay = 1;
  2763. }
  2764. if (h->avctx->has_b_frames < 2)
  2765. h->avctx->has_b_frames = !h->low_delay;
  2766. if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
  2767. h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
  2768. if (h->avctx->codec &&
  2769. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU &&
  2770. (h->sps.bit_depth_luma != 8 || h->sps.chroma_format_idc > 1)) {
  2771. av_log(h->avctx, AV_LOG_ERROR,
  2772. "VDPAU decoding does not support video colorspace.\n");
  2773. return AVERROR_INVALIDDATA;
  2774. }
  2775. if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 14 &&
  2776. h->sps.bit_depth_luma != 11 && h->sps.bit_depth_luma != 13) {
  2777. h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
  2778. h->cur_chroma_format_idc = h->sps.chroma_format_idc;
  2779. h->pixel_shift = h->sps.bit_depth_luma > 8;
  2780. ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
  2781. h->sps.chroma_format_idc);
  2782. ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
  2783. ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
  2784. ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
  2785. h->sps.chroma_format_idc);
  2786. if (CONFIG_ERROR_RESILIENCE)
  2787. ff_dsputil_init(&h->dsp, h->avctx);
  2788. ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
  2789. } else {
  2790. av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth %d\n",
  2791. h->sps.bit_depth_luma);
  2792. return AVERROR_INVALIDDATA;
  2793. }
  2794. }
  2795. return 0;
  2796. }
  2797. static enum AVPixelFormat get_pixel_format(H264Context *h, int force_callback)
  2798. {
  2799. switch (h->sps.bit_depth_luma) {
  2800. case 9:
  2801. if (CHROMA444(h)) {
  2802. if (h->avctx->colorspace == AVCOL_SPC_RGB) {
  2803. return AV_PIX_FMT_GBRP9;
  2804. } else
  2805. return AV_PIX_FMT_YUV444P9;
  2806. } else if (CHROMA422(h))
  2807. return AV_PIX_FMT_YUV422P9;
  2808. else
  2809. return AV_PIX_FMT_YUV420P9;
  2810. break;
  2811. case 10:
  2812. if (CHROMA444(h)) {
  2813. if (h->avctx->colorspace == AVCOL_SPC_RGB) {
  2814. return AV_PIX_FMT_GBRP10;
  2815. } else
  2816. return AV_PIX_FMT_YUV444P10;
  2817. } else if (CHROMA422(h))
  2818. return AV_PIX_FMT_YUV422P10;
  2819. else
  2820. return AV_PIX_FMT_YUV420P10;
  2821. break;
  2822. case 12:
  2823. if (CHROMA444(h)) {
  2824. if (h->avctx->colorspace == AVCOL_SPC_RGB) {
  2825. return AV_PIX_FMT_GBRP12;
  2826. } else
  2827. return AV_PIX_FMT_YUV444P12;
  2828. } else if (CHROMA422(h))
  2829. return AV_PIX_FMT_YUV422P12;
  2830. else
  2831. return AV_PIX_FMT_YUV420P12;
  2832. break;
  2833. case 14:
  2834. if (CHROMA444(h)) {
  2835. if (h->avctx->colorspace == AVCOL_SPC_RGB) {
  2836. return AV_PIX_FMT_GBRP14;
  2837. } else
  2838. return AV_PIX_FMT_YUV444P14;
  2839. } else if (CHROMA422(h))
  2840. return AV_PIX_FMT_YUV422P14;
  2841. else
  2842. return AV_PIX_FMT_YUV420P14;
  2843. break;
  2844. case 8:
  2845. if (CHROMA444(h)) {
  2846. if (h->avctx->colorspace == AVCOL_SPC_RGB) {
  2847. av_log(h->avctx, AV_LOG_DEBUG, "Detected GBR colorspace.\n");
  2848. return AV_PIX_FMT_GBR24P;
  2849. } else if (h->avctx->colorspace == AVCOL_SPC_YCGCO) {
  2850. av_log(h->avctx, AV_LOG_WARNING, "Detected unsupported YCgCo colorspace.\n");
  2851. }
  2852. return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ444P
  2853. : AV_PIX_FMT_YUV444P;
  2854. } else if (CHROMA422(h)) {
  2855. return h->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ422P
  2856. : AV_PIX_FMT_YUV422P;
  2857. } else {
  2858. int i;
  2859. const enum AVPixelFormat * fmt = h->avctx->codec->pix_fmts ?
  2860. h->avctx->codec->pix_fmts :
  2861. h->avctx->color_range == AVCOL_RANGE_JPEG ?
  2862. h264_hwaccel_pixfmt_list_jpeg_420 :
  2863. h264_hwaccel_pixfmt_list_420;
  2864. for (i=0; fmt[i] != AV_PIX_FMT_NONE; i++)
  2865. if (fmt[i] == h->avctx->pix_fmt && !force_callback)
  2866. return fmt[i];
  2867. return ff_thread_get_format(h->avctx, fmt);
  2868. }
  2869. break;
  2870. default:
  2871. av_log(h->avctx, AV_LOG_ERROR,
  2872. "Unsupported bit depth %d\n", h->sps.bit_depth_luma);
  2873. return AVERROR_INVALIDDATA;
  2874. }
  2875. }
  2876. /* export coded and cropped frame dimensions to AVCodecContext */
  2877. static int init_dimensions(H264Context *h)
  2878. {
  2879. int width = h->width - (h->sps.crop_right + h->sps.crop_left);
  2880. int height = h->height - (h->sps.crop_top + h->sps.crop_bottom);
  2881. av_assert0(h->sps.crop_right + h->sps.crop_left < (unsigned)h->width);
  2882. av_assert0(h->sps.crop_top + h->sps.crop_bottom < (unsigned)h->height);
  2883. /* handle container cropping */
  2884. if (!h->sps.crop &&
  2885. FFALIGN(h->avctx->width, 16) == h->width &&
  2886. FFALIGN(h->avctx->height, 16) == h->height) {
  2887. width = h->avctx->width;
  2888. height = h->avctx->height;
  2889. }
  2890. if (width <= 0 || height <= 0) {
  2891. av_log(h->avctx, AV_LOG_ERROR, "Invalid cropped dimensions: %dx%d.\n",
  2892. width, height);
  2893. if (h->avctx->err_recognition & AV_EF_EXPLODE)
  2894. return AVERROR_INVALIDDATA;
  2895. av_log(h->avctx, AV_LOG_WARNING, "Ignoring cropping information.\n");
  2896. h->sps.crop_bottom = h->sps.crop_top = h->sps.crop_right = h->sps.crop_left = 0;
  2897. h->sps.crop = 0;
  2898. width = h->width;
  2899. height = h->height;
  2900. }
  2901. h->avctx->coded_width = h->width;
  2902. h->avctx->coded_height = h->height;
  2903. h->avctx->width = width;
  2904. h->avctx->height = height;
  2905. return 0;
  2906. }
  2907. static int h264_slice_header_init(H264Context *h, int reinit)
  2908. {
  2909. int nb_slices = (HAVE_THREADS &&
  2910. h->avctx->active_thread_type & FF_THREAD_SLICE) ?
  2911. h->avctx->thread_count : 1;
  2912. int i, ret;
  2913. h->avctx->sample_aspect_ratio = h->sps.sar;
  2914. av_assert0(h->avctx->sample_aspect_ratio.den);
  2915. av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt,
  2916. &h->chroma_x_shift, &h->chroma_y_shift);
  2917. if (h->sps.timing_info_present_flag) {
  2918. int64_t den = h->sps.time_scale;
  2919. if (h->x264_build < 44U)
  2920. den *= 2;
  2921. av_reduce(&h->avctx->time_base.num, &h->avctx->time_base.den,
  2922. h->sps.num_units_in_tick, den, 1 << 30);
  2923. }
  2924. h->avctx->hwaccel = ff_find_hwaccel(h->avctx);
  2925. if (reinit)
  2926. free_tables(h, 0);
  2927. h->first_field = 0;
  2928. h->prev_interlaced_frame = 1;
  2929. init_scan_tables(h);
  2930. ret = ff_h264_alloc_tables(h);
  2931. if (ret < 0) {
  2932. av_log(h->avctx, AV_LOG_ERROR, "Could not allocate memory\n");
  2933. return ret;
  2934. }
  2935. if (nb_slices > H264_MAX_THREADS || (nb_slices > h->mb_height && h->mb_height)) {
  2936. int max_slices;
  2937. if (h->mb_height)
  2938. max_slices = FFMIN(H264_MAX_THREADS, h->mb_height);
  2939. else
  2940. max_slices = H264_MAX_THREADS;
  2941. av_log(h->avctx, AV_LOG_WARNING, "too many threads/slices %d,"
  2942. " reducing to %d\n", nb_slices, max_slices);
  2943. nb_slices = max_slices;
  2944. }
  2945. h->slice_context_count = nb_slices;
  2946. if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {
  2947. ret = context_init(h);
  2948. if (ret < 0) {
  2949. av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
  2950. return ret;
  2951. }
  2952. } else {
  2953. for (i = 1; i < h->slice_context_count; i++) {
  2954. H264Context *c;
  2955. c = h->thread_context[i] = av_mallocz(sizeof(H264Context));
  2956. if (!c)
  2957. return AVERROR(ENOMEM);
  2958. c->avctx = h->avctx;
  2959. if (CONFIG_ERROR_RESILIENCE) {
  2960. c->dsp = h->dsp;
  2961. }
  2962. c->vdsp = h->vdsp;
  2963. c->h264dsp = h->h264dsp;
  2964. c->h264qpel = h->h264qpel;
  2965. c->h264chroma = h->h264chroma;
  2966. c->sps = h->sps;
  2967. c->pps = h->pps;
  2968. c->pixel_shift = h->pixel_shift;
  2969. c->cur_chroma_format_idc = h->cur_chroma_format_idc;
  2970. c->width = h->width;
  2971. c->height = h->height;
  2972. c->linesize = h->linesize;
  2973. c->uvlinesize = h->uvlinesize;
  2974. c->chroma_x_shift = h->chroma_x_shift;
  2975. c->chroma_y_shift = h->chroma_y_shift;
  2976. c->qscale = h->qscale;
  2977. c->droppable = h->droppable;
  2978. c->data_partitioning = h->data_partitioning;
  2979. c->low_delay = h->low_delay;
  2980. c->mb_width = h->mb_width;
  2981. c->mb_height = h->mb_height;
  2982. c->mb_stride = h->mb_stride;
  2983. c->mb_num = h->mb_num;
  2984. c->flags = h->flags;
  2985. c->workaround_bugs = h->workaround_bugs;
  2986. c->pict_type = h->pict_type;
  2987. init_scan_tables(c);
  2988. clone_tables(c, h, i);
  2989. c->context_initialized = 1;
  2990. }
  2991. for (i = 0; i < h->slice_context_count; i++)
  2992. if ((ret = context_init(h->thread_context[i])) < 0) {
  2993. av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");
  2994. return ret;
  2995. }
  2996. }
  2997. h->context_initialized = 1;
  2998. return 0;
  2999. }
  3000. int ff_set_ref_count(H264Context *h)
  3001. {
  3002. int ref_count[2], list_count;
  3003. int num_ref_idx_active_override_flag;
  3004. // set defaults, might be overridden a few lines later
  3005. ref_count[0] = h->pps.ref_count[0];
  3006. ref_count[1] = h->pps.ref_count[1];
  3007. if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
  3008. unsigned max[2];
  3009. max[0] = max[1] = h->picture_structure == PICT_FRAME ? 15 : 31;
  3010. if (h->slice_type_nos == AV_PICTURE_TYPE_B)
  3011. h->direct_spatial_mv_pred = get_bits1(&h->gb);
  3012. num_ref_idx_active_override_flag = get_bits1(&h->gb);
  3013. if (num_ref_idx_active_override_flag) {
  3014. ref_count[0] = get_ue_golomb(&h->gb) + 1;
  3015. if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
  3016. ref_count[1] = get_ue_golomb(&h->gb) + 1;
  3017. } else
  3018. // full range is spec-ok in this case, even for frames
  3019. ref_count[1] = 1;
  3020. }
  3021. if (ref_count[0]-1 > max[0] || ref_count[1]-1 > max[1]){
  3022. av_log(h->avctx, AV_LOG_ERROR, "reference overflow %u > %u or %u > %u\n", ref_count[0]-1, max[0], ref_count[1]-1, max[1]);
  3023. h->ref_count[0] = h->ref_count[1] = 0;
  3024. h->list_count = 0;
  3025. return AVERROR_INVALIDDATA;
  3026. }
  3027. if (h->slice_type_nos == AV_PICTURE_TYPE_B)
  3028. list_count = 2;
  3029. else
  3030. list_count = 1;
  3031. } else {
  3032. list_count = 0;
  3033. ref_count[0] = ref_count[1] = 0;
  3034. }
  3035. if (list_count != h->list_count ||
  3036. ref_count[0] != h->ref_count[0] ||
  3037. ref_count[1] != h->ref_count[1]) {
  3038. h->ref_count[0] = ref_count[0];
  3039. h->ref_count[1] = ref_count[1];
  3040. h->list_count = list_count;
  3041. return 1;
  3042. }
  3043. return 0;
  3044. }
  3045. static enum AVPixelFormat non_j_pixfmt(enum AVPixelFormat a)
  3046. {
  3047. switch (a) {
  3048. case AV_PIX_FMT_YUVJ420P: return AV_PIX_FMT_YUV420P;
  3049. case AV_PIX_FMT_YUVJ422P: return AV_PIX_FMT_YUV422P;
  3050. case AV_PIX_FMT_YUVJ444P: return AV_PIX_FMT_YUV444P;
  3051. default:
  3052. return a;
  3053. }
  3054. }
  3055. /**
  3056. * Decode a slice header.
  3057. * This will (re)intialize the decoder and call h264_frame_start() as needed.
  3058. *
  3059. * @param h h264context
  3060. * @param h0 h264 master context (differs from 'h' when doing sliced based
  3061. * parallel decoding)
  3062. *
  3063. * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
  3064. */
  3065. static int decode_slice_header(H264Context *h, H264Context *h0)
  3066. {
  3067. unsigned int first_mb_in_slice;
  3068. unsigned int pps_id;
  3069. int ret;
  3070. unsigned int slice_type, tmp, i, j;
  3071. int last_pic_structure, last_pic_droppable;
  3072. int must_reinit;
  3073. int needs_reinit = 0;
  3074. int field_pic_flag, bottom_field_flag;
  3075. h->qpel_put = h->h264qpel.put_h264_qpel_pixels_tab;
  3076. h->qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab;
  3077. first_mb_in_slice = get_ue_golomb_long(&h->gb);
  3078. if (first_mb_in_slice == 0) { // FIXME better field boundary detection
  3079. if (h0->current_slice && h->cur_pic_ptr && FIELD_PICTURE(h)) {
  3080. field_end(h, 1);
  3081. }
  3082. h0->current_slice = 0;
  3083. if (!h0->first_field) {
  3084. if (h->cur_pic_ptr && !h->droppable) {
  3085. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
  3086. h->picture_structure == PICT_BOTTOM_FIELD);
  3087. }
  3088. h->cur_pic_ptr = NULL;
  3089. }
  3090. }
  3091. slice_type = get_ue_golomb_31(&h->gb);
  3092. if (slice_type > 9) {
  3093. av_log(h->avctx, AV_LOG_ERROR,
  3094. "slice type %d too large at %d %d\n",
  3095. slice_type, h->mb_x, h->mb_y);
  3096. return AVERROR_INVALIDDATA;
  3097. }
  3098. if (slice_type > 4) {
  3099. slice_type -= 5;
  3100. h->slice_type_fixed = 1;
  3101. } else
  3102. h->slice_type_fixed = 0;
  3103. slice_type = golomb_to_pict_type[slice_type];
  3104. h->slice_type = slice_type;
  3105. h->slice_type_nos = slice_type & 3;
  3106. if (h->nal_unit_type == NAL_IDR_SLICE &&
  3107. h->slice_type_nos != AV_PICTURE_TYPE_I) {
  3108. av_log(h->avctx, AV_LOG_ERROR, "A non-intra slice in an IDR NAL unit.\n");
  3109. return AVERROR_INVALIDDATA;
  3110. }
  3111. // to make a few old functions happy, it's wrong though
  3112. h->pict_type = h->slice_type;
  3113. pps_id = get_ue_golomb(&h->gb);
  3114. if (pps_id >= MAX_PPS_COUNT) {
  3115. av_log(h->avctx, AV_LOG_ERROR, "pps_id %u out of range\n", pps_id);
  3116. return AVERROR_INVALIDDATA;
  3117. }
  3118. if (!h0->pps_buffers[pps_id]) {
  3119. av_log(h->avctx, AV_LOG_ERROR,
  3120. "non-existing PPS %u referenced\n",
  3121. pps_id);
  3122. return AVERROR_INVALIDDATA;
  3123. }
  3124. if (h0->au_pps_id >= 0 && pps_id != h0->au_pps_id) {
  3125. av_log(h->avctx, AV_LOG_ERROR,
  3126. "PPS change from %d to %d forbidden\n",
  3127. h0->au_pps_id, pps_id);
  3128. return AVERROR_INVALIDDATA;
  3129. }
  3130. h->pps = *h0->pps_buffers[pps_id];
  3131. if (!h0->sps_buffers[h->pps.sps_id]) {
  3132. av_log(h->avctx, AV_LOG_ERROR,
  3133. "non-existing SPS %u referenced\n",
  3134. h->pps.sps_id);
  3135. return AVERROR_INVALIDDATA;
  3136. }
  3137. if (h->pps.sps_id != h->sps.sps_id ||
  3138. h->pps.sps_id != h->current_sps_id ||
  3139. h0->sps_buffers[h->pps.sps_id]->new) {
  3140. h->sps = *h0->sps_buffers[h->pps.sps_id];
  3141. if (h->mb_width != h->sps.mb_width ||
  3142. h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) ||
  3143. h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
  3144. h->cur_chroma_format_idc != h->sps.chroma_format_idc
  3145. )
  3146. needs_reinit = 1;
  3147. if (h->bit_depth_luma != h->sps.bit_depth_luma ||
  3148. h->chroma_format_idc != h->sps.chroma_format_idc) {
  3149. h->bit_depth_luma = h->sps.bit_depth_luma;
  3150. h->chroma_format_idc = h->sps.chroma_format_idc;
  3151. needs_reinit = 1;
  3152. }
  3153. if ((ret = h264_set_parameter_from_sps(h)) < 0)
  3154. return ret;
  3155. }
  3156. h->avctx->profile = ff_h264_get_profile(&h->sps);
  3157. h->avctx->level = h->sps.level_idc;
  3158. h->avctx->refs = h->sps.ref_frame_count;
  3159. must_reinit = (h->context_initialized &&
  3160. ( 16*h->sps.mb_width != h->avctx->coded_width
  3161. || 16*h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) != h->avctx->coded_height
  3162. || h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma
  3163. || h->cur_chroma_format_idc != h->sps.chroma_format_idc
  3164. || av_cmp_q(h->sps.sar, h->avctx->sample_aspect_ratio)
  3165. || h->mb_width != h->sps.mb_width
  3166. || h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag)
  3167. ));
  3168. if (non_j_pixfmt(h0->avctx->pix_fmt) != non_j_pixfmt(get_pixel_format(h0, 0)))
  3169. must_reinit = 1;
  3170. h->mb_width = h->sps.mb_width;
  3171. h->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
  3172. h->mb_num = h->mb_width * h->mb_height;
  3173. h->mb_stride = h->mb_width + 1;
  3174. h->b_stride = h->mb_width * 4;
  3175. h->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
  3176. h->width = 16 * h->mb_width;
  3177. h->height = 16 * h->mb_height;
  3178. ret = init_dimensions(h);
  3179. if (ret < 0)
  3180. return ret;
  3181. if (h->sps.video_signal_type_present_flag) {
  3182. h->avctx->color_range = h->sps.full_range>0 ? AVCOL_RANGE_JPEG
  3183. : AVCOL_RANGE_MPEG;
  3184. if (h->sps.colour_description_present_flag) {
  3185. if (h->avctx->colorspace != h->sps.colorspace)
  3186. needs_reinit = 1;
  3187. h->avctx->color_primaries = h->sps.color_primaries;
  3188. h->avctx->color_trc = h->sps.color_trc;
  3189. h->avctx->colorspace = h->sps.colorspace;
  3190. }
  3191. }
  3192. if (h->context_initialized &&
  3193. (h->width != h->avctx->coded_width ||
  3194. h->height != h->avctx->coded_height ||
  3195. must_reinit ||
  3196. needs_reinit)) {
  3197. if (h != h0) {
  3198. av_log(h->avctx, AV_LOG_ERROR,
  3199. "changing width %d -> %d / height %d -> %d on "
  3200. "slice %d\n",
  3201. h->width, h->avctx->coded_width,
  3202. h->height, h->avctx->coded_height,
  3203. h0->current_slice + 1);
  3204. return AVERROR_INVALIDDATA;
  3205. }
  3206. flush_change(h);
  3207. if ((ret = get_pixel_format(h, 1)) < 0)
  3208. return ret;
  3209. h->avctx->pix_fmt = ret;
  3210. av_log(h->avctx, AV_LOG_INFO, "Reinit context to %dx%d, "
  3211. "pix_fmt: %s\n", h->width, h->height, av_get_pix_fmt_name(h->avctx->pix_fmt));
  3212. if ((ret = h264_slice_header_init(h, 1)) < 0) {
  3213. av_log(h->avctx, AV_LOG_ERROR,
  3214. "h264_slice_header_init() failed\n");
  3215. return ret;
  3216. }
  3217. }
  3218. if (!h->context_initialized) {
  3219. if (h != h0) {
  3220. av_log(h->avctx, AV_LOG_ERROR,
  3221. "Cannot (re-)initialize context during parallel decoding.\n");
  3222. return AVERROR_PATCHWELCOME;
  3223. }
  3224. if ((ret = get_pixel_format(h, 1)) < 0)
  3225. return ret;
  3226. h->avctx->pix_fmt = ret;
  3227. if ((ret = h264_slice_header_init(h, 0)) < 0) {
  3228. av_log(h->avctx, AV_LOG_ERROR,
  3229. "h264_slice_header_init() failed\n");
  3230. return ret;
  3231. }
  3232. }
  3233. if (h == h0 && h->dequant_coeff_pps != pps_id) {
  3234. h->dequant_coeff_pps = pps_id;
  3235. init_dequant_tables(h);
  3236. }
  3237. h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num);
  3238. h->mb_mbaff = 0;
  3239. h->mb_aff_frame = 0;
  3240. last_pic_structure = h0->picture_structure;
  3241. last_pic_droppable = h0->droppable;
  3242. h->droppable = h->nal_ref_idc == 0;
  3243. if (h->sps.frame_mbs_only_flag) {
  3244. h->picture_structure = PICT_FRAME;
  3245. } else {
  3246. if (!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B) {
  3247. av_log(h->avctx, AV_LOG_ERROR, "This stream was generated by a broken encoder, invalid 8x8 inference\n");
  3248. return -1;
  3249. }
  3250. field_pic_flag = get_bits1(&h->gb);
  3251. if (field_pic_flag) {
  3252. bottom_field_flag = get_bits1(&h->gb);
  3253. h->picture_structure = PICT_TOP_FIELD + bottom_field_flag;
  3254. } else {
  3255. h->picture_structure = PICT_FRAME;
  3256. h->mb_aff_frame = h->sps.mb_aff;
  3257. }
  3258. }
  3259. h->mb_field_decoding_flag = h->picture_structure != PICT_FRAME;
  3260. if (h0->current_slice != 0) {
  3261. if (last_pic_structure != h->picture_structure ||
  3262. last_pic_droppable != h->droppable) {
  3263. av_log(h->avctx, AV_LOG_ERROR,
  3264. "Changing field mode (%d -> %d) between slices is not allowed\n",
  3265. last_pic_structure, h->picture_structure);
  3266. h->picture_structure = last_pic_structure;
  3267. h->droppable = last_pic_droppable;
  3268. return AVERROR_INVALIDDATA;
  3269. } else if (!h0->cur_pic_ptr) {
  3270. av_log(h->avctx, AV_LOG_ERROR,
  3271. "unset cur_pic_ptr on slice %d\n",
  3272. h0->current_slice + 1);
  3273. return AVERROR_INVALIDDATA;
  3274. }
  3275. } else {
  3276. /* Shorten frame num gaps so we don't have to allocate reference
  3277. * frames just to throw them away */
  3278. if (h->frame_num != h->prev_frame_num) {
  3279. int unwrap_prev_frame_num = h->prev_frame_num;
  3280. int max_frame_num = 1 << h->sps.log2_max_frame_num;
  3281. if (unwrap_prev_frame_num > h->frame_num)
  3282. unwrap_prev_frame_num -= max_frame_num;
  3283. if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
  3284. unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
  3285. if (unwrap_prev_frame_num < 0)
  3286. unwrap_prev_frame_num += max_frame_num;
  3287. h->prev_frame_num = unwrap_prev_frame_num;
  3288. }
  3289. }
  3290. /* See if we have a decoded first field looking for a pair...
  3291. * Here, we're using that to see if we should mark previously
  3292. * decode frames as "finished".
  3293. * We have to do that before the "dummy" in-between frame allocation,
  3294. * since that can modify h->cur_pic_ptr. */
  3295. if (h0->first_field) {
  3296. assert(h0->cur_pic_ptr);
  3297. assert(h0->cur_pic_ptr->f.buf[0]);
  3298. assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);
  3299. /* Mark old field/frame as completed */
  3300. if (h0->cur_pic_ptr->tf.owner == h0->avctx) {
  3301. ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
  3302. last_pic_structure == PICT_BOTTOM_FIELD);
  3303. }
  3304. /* figure out if we have a complementary field pair */
  3305. if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
  3306. /* Previous field is unmatched. Don't display it, but let it
  3307. * remain for reference if marked as such. */
  3308. if (last_pic_structure != PICT_FRAME) {
  3309. ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
  3310. last_pic_structure == PICT_TOP_FIELD);
  3311. }
  3312. } else {
  3313. if (h0->cur_pic_ptr->frame_num != h->frame_num) {
  3314. /* This and previous field were reference, but had
  3315. * different frame_nums. Consider this field first in
  3316. * pair. Throw away previous field except for reference
  3317. * purposes. */
  3318. if (last_pic_structure != PICT_FRAME) {
  3319. ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
  3320. last_pic_structure == PICT_TOP_FIELD);
  3321. }
  3322. } else {
  3323. /* Second field in complementary pair */
  3324. if (!((last_pic_structure == PICT_TOP_FIELD &&
  3325. h->picture_structure == PICT_BOTTOM_FIELD) ||
  3326. (last_pic_structure == PICT_BOTTOM_FIELD &&
  3327. h->picture_structure == PICT_TOP_FIELD))) {
  3328. av_log(h->avctx, AV_LOG_ERROR,
  3329. "Invalid field mode combination %d/%d\n",
  3330. last_pic_structure, h->picture_structure);
  3331. h->picture_structure = last_pic_structure;
  3332. h->droppable = last_pic_droppable;
  3333. return AVERROR_INVALIDDATA;
  3334. } else if (last_pic_droppable != h->droppable) {
  3335. avpriv_request_sample(h->avctx,
  3336. "Found reference and non-reference fields in the same frame, which");
  3337. h->picture_structure = last_pic_structure;
  3338. h->droppable = last_pic_droppable;
  3339. return AVERROR_PATCHWELCOME;
  3340. }
  3341. }
  3342. }
  3343. }
  3344. while (h->frame_num != h->prev_frame_num && !h0->first_field &&
  3345. h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
  3346. H264Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
  3347. av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
  3348. h->frame_num, h->prev_frame_num);
  3349. if (!h->sps.gaps_in_frame_num_allowed_flag)
  3350. for(i=0; i<FF_ARRAY_ELEMS(h->last_pocs); i++)
  3351. h->last_pocs[i] = INT_MIN;
  3352. ret = h264_frame_start(h);
  3353. if (ret < 0) {
  3354. h0->first_field = 0;
  3355. return ret;
  3356. }
  3357. h->prev_frame_num++;
  3358. h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;
  3359. h->cur_pic_ptr->frame_num = h->prev_frame_num;
  3360. h->cur_pic_ptr->invalid_gap = !h->sps.gaps_in_frame_num_allowed_flag;
  3361. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);
  3362. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);
  3363. ret = ff_generate_sliding_window_mmcos(h, 1);
  3364. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  3365. return ret;
  3366. ret = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
  3367. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  3368. return ret;
  3369. /* Error concealment: If a ref is missing, copy the previous ref
  3370. * in its place.
  3371. * FIXME: Avoiding a memcpy would be nice, but ref handling makes
  3372. * many assumptions about there being no actual duplicates.
  3373. * FIXME: This does not copy padding for out-of-frame motion
  3374. * vectors. Given we are concealing a lost frame, this probably
  3375. * is not noticeable by comparison, but it should be fixed. */
  3376. if (h->short_ref_count) {
  3377. if (prev) {
  3378. av_image_copy(h->short_ref[0]->f.data,
  3379. h->short_ref[0]->f.linesize,
  3380. (const uint8_t **)prev->f.data,
  3381. prev->f.linesize,
  3382. h->avctx->pix_fmt,
  3383. h->mb_width * 16,
  3384. h->mb_height * 16);
  3385. h->short_ref[0]->poc = prev->poc + 2;
  3386. }
  3387. h->short_ref[0]->frame_num = h->prev_frame_num;
  3388. }
  3389. }
  3390. /* See if we have a decoded first field looking for a pair...
  3391. * We're using that to see whether to continue decoding in that
  3392. * frame, or to allocate a new one. */
  3393. if (h0->first_field) {
  3394. assert(h0->cur_pic_ptr);
  3395. assert(h0->cur_pic_ptr->f.buf[0]);
  3396. assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF);
  3397. /* figure out if we have a complementary field pair */
  3398. if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {
  3399. /* Previous field is unmatched. Don't display it, but let it
  3400. * remain for reference if marked as such. */
  3401. h0->cur_pic_ptr = NULL;
  3402. h0->first_field = FIELD_PICTURE(h);
  3403. } else {
  3404. if (h0->cur_pic_ptr->frame_num != h->frame_num) {
  3405. ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX,
  3406. h0->picture_structure==PICT_BOTTOM_FIELD);
  3407. /* This and the previous field had different frame_nums.
  3408. * Consider this field first in pair. Throw away previous
  3409. * one except for reference purposes. */
  3410. h0->first_field = 1;
  3411. h0->cur_pic_ptr = NULL;
  3412. } else {
  3413. /* Second field in complementary pair */
  3414. h0->first_field = 0;
  3415. }
  3416. }
  3417. } else {
  3418. /* Frame or first field in a potentially complementary pair */
  3419. h0->first_field = FIELD_PICTURE(h);
  3420. }
  3421. if (!FIELD_PICTURE(h) || h0->first_field) {
  3422. if (h264_frame_start(h) < 0) {
  3423. h0->first_field = 0;
  3424. return AVERROR_INVALIDDATA;
  3425. }
  3426. } else {
  3427. release_unused_pictures(h, 0);
  3428. }
  3429. /* Some macroblocks can be accessed before they're available in case
  3430. * of lost slices, MBAFF or threading. */
  3431. if (FIELD_PICTURE(h)) {
  3432. for(i = (h->picture_structure == PICT_BOTTOM_FIELD); i<h->mb_height; i++)
  3433. memset(h->slice_table + i*h->mb_stride, -1, (h->mb_stride - (i+1==h->mb_height)) * sizeof(*h->slice_table));
  3434. } else {
  3435. memset(h->slice_table, -1,
  3436. (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));
  3437. }
  3438. h0->last_slice_type = -1;
  3439. }
  3440. if (h != h0 && (ret = clone_slice(h, h0)) < 0)
  3441. return ret;
  3442. /* can't be in alloc_tables because linesize isn't known there.
  3443. * FIXME: redo bipred weight to not require extra buffer? */
  3444. for (i = 0; i < h->slice_context_count; i++)
  3445. if (h->thread_context[i]) {
  3446. ret = alloc_scratch_buffers(h->thread_context[i], h->linesize);
  3447. if (ret < 0)
  3448. return ret;
  3449. }
  3450. h->cur_pic_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
  3451. av_assert1(h->mb_num == h->mb_width * h->mb_height);
  3452. if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num ||
  3453. first_mb_in_slice >= h->mb_num) {
  3454. av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
  3455. return AVERROR_INVALIDDATA;
  3456. }
  3457. h->resync_mb_x = h->mb_x = first_mb_in_slice % h->mb_width;
  3458. h->resync_mb_y = h->mb_y = (first_mb_in_slice / h->mb_width) <<
  3459. FIELD_OR_MBAFF_PICTURE(h);
  3460. if (h->picture_structure == PICT_BOTTOM_FIELD)
  3461. h->resync_mb_y = h->mb_y = h->mb_y + 1;
  3462. av_assert1(h->mb_y < h->mb_height);
  3463. if (h->picture_structure == PICT_FRAME) {
  3464. h->curr_pic_num = h->frame_num;
  3465. h->max_pic_num = 1 << h->sps.log2_max_frame_num;
  3466. } else {
  3467. h->curr_pic_num = 2 * h->frame_num + 1;
  3468. h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1);
  3469. }
  3470. if (h->nal_unit_type == NAL_IDR_SLICE)
  3471. get_ue_golomb(&h->gb); /* idr_pic_id */
  3472. if (h->sps.poc_type == 0) {
  3473. h->poc_lsb = get_bits(&h->gb, h->sps.log2_max_poc_lsb);
  3474. if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
  3475. h->delta_poc_bottom = get_se_golomb(&h->gb);
  3476. }
  3477. if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {
  3478. h->delta_poc[0] = get_se_golomb(&h->gb);
  3479. if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)
  3480. h->delta_poc[1] = get_se_golomb(&h->gb);
  3481. }
  3482. ff_init_poc(h, h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc);
  3483. if (h->pps.redundant_pic_cnt_present)
  3484. h->redundant_pic_count = get_ue_golomb(&h->gb);
  3485. ret = ff_set_ref_count(h);
  3486. if (ret < 0)
  3487. return ret;
  3488. if (slice_type != AV_PICTURE_TYPE_I &&
  3489. (h0->current_slice == 0 ||
  3490. slice_type != h0->last_slice_type ||
  3491. memcmp(h0->last_ref_count, h0->ref_count, sizeof(h0->ref_count)))) {
  3492. ff_h264_fill_default_ref_list(h);
  3493. }
  3494. if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
  3495. ret = ff_h264_decode_ref_pic_list_reordering(h);
  3496. if (ret < 0) {
  3497. h->ref_count[1] = h->ref_count[0] = 0;
  3498. return ret;
  3499. }
  3500. }
  3501. if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||
  3502. (h->pps.weighted_bipred_idc == 1 &&
  3503. h->slice_type_nos == AV_PICTURE_TYPE_B))
  3504. ff_pred_weight_table(h);
  3505. else if (h->pps.weighted_bipred_idc == 2 &&
  3506. h->slice_type_nos == AV_PICTURE_TYPE_B) {
  3507. implicit_weight_table(h, -1);
  3508. } else {
  3509. h->use_weight = 0;
  3510. for (i = 0; i < 2; i++) {
  3511. h->luma_weight_flag[i] = 0;
  3512. h->chroma_weight_flag[i] = 0;
  3513. }
  3514. }
  3515. // If frame-mt is enabled, only update mmco tables for the first slice
  3516. // in a field. Subsequent slices can temporarily clobber h->mmco_index
  3517. // or h->mmco, which will cause ref list mix-ups and decoding errors
  3518. // further down the line. This may break decoding if the first slice is
  3519. // corrupt, thus we only do this if frame-mt is enabled.
  3520. if (h->nal_ref_idc) {
  3521. ret = ff_h264_decode_ref_pic_marking(h0, &h->gb,
  3522. !(h->avctx->active_thread_type & FF_THREAD_FRAME) ||
  3523. h0->current_slice == 0);
  3524. if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
  3525. return AVERROR_INVALIDDATA;
  3526. }
  3527. if (FRAME_MBAFF(h)) {
  3528. ff_h264_fill_mbaff_ref_list(h);
  3529. if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) {
  3530. implicit_weight_table(h, 0);
  3531. implicit_weight_table(h, 1);
  3532. }
  3533. }
  3534. if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
  3535. ff_h264_direct_dist_scale_factor(h);
  3536. ff_h264_direct_ref_list_init(h);
  3537. if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {
  3538. tmp = get_ue_golomb_31(&h->gb);
  3539. if (tmp > 2) {
  3540. av_log(h->avctx, AV_LOG_ERROR, "cabac_init_idc %u overflow\n", tmp);
  3541. return AVERROR_INVALIDDATA;
  3542. }
  3543. h->cabac_init_idc = tmp;
  3544. }
  3545. h->last_qscale_diff = 0;
  3546. tmp = h->pps.init_qp + get_se_golomb(&h->gb);
  3547. if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {
  3548. av_log(h->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
  3549. return AVERROR_INVALIDDATA;
  3550. }
  3551. h->qscale = tmp;
  3552. h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
  3553. h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
  3554. // FIXME qscale / qp ... stuff
  3555. if (h->slice_type == AV_PICTURE_TYPE_SP)
  3556. get_bits1(&h->gb); /* sp_for_switch_flag */
  3557. if (h->slice_type == AV_PICTURE_TYPE_SP ||
  3558. h->slice_type == AV_PICTURE_TYPE_SI)
  3559. get_se_golomb(&h->gb); /* slice_qs_delta */
  3560. h->deblocking_filter = 1;
  3561. h->slice_alpha_c0_offset = 0;
  3562. h->slice_beta_offset = 0;
  3563. if (h->pps.deblocking_filter_parameters_present) {
  3564. tmp = get_ue_golomb_31(&h->gb);
  3565. if (tmp > 2) {
  3566. av_log(h->avctx, AV_LOG_ERROR,
  3567. "deblocking_filter_idc %u out of range\n", tmp);
  3568. return AVERROR_INVALIDDATA;
  3569. }
  3570. h->deblocking_filter = tmp;
  3571. if (h->deblocking_filter < 2)
  3572. h->deblocking_filter ^= 1; // 1<->0
  3573. if (h->deblocking_filter) {
  3574. h->slice_alpha_c0_offset = get_se_golomb(&h->gb) * 2;
  3575. h->slice_beta_offset = get_se_golomb(&h->gb) * 2;
  3576. if (h->slice_alpha_c0_offset > 12 ||
  3577. h->slice_alpha_c0_offset < -12 ||
  3578. h->slice_beta_offset > 12 ||
  3579. h->slice_beta_offset < -12) {
  3580. av_log(h->avctx, AV_LOG_ERROR,
  3581. "deblocking filter parameters %d %d out of range\n",
  3582. h->slice_alpha_c0_offset, h->slice_beta_offset);
  3583. return AVERROR_INVALIDDATA;
  3584. }
  3585. }
  3586. }
  3587. if (h->avctx->skip_loop_filter >= AVDISCARD_ALL ||
  3588. (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
  3589. h->slice_type_nos != AV_PICTURE_TYPE_I) ||
  3590. (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&
  3591. h->slice_type_nos == AV_PICTURE_TYPE_B) ||
  3592. (h->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
  3593. h->nal_ref_idc == 0))
  3594. h->deblocking_filter = 0;
  3595. if (h->deblocking_filter == 1 && h0->max_contexts > 1) {
  3596. if (h->avctx->flags2 & CODEC_FLAG2_FAST) {
  3597. /* Cheat slightly for speed:
  3598. * Do not bother to deblock across slices. */
  3599. h->deblocking_filter = 2;
  3600. } else {
  3601. h0->max_contexts = 1;
  3602. if (!h0->single_decode_warning) {
  3603. av_log(h->avctx, AV_LOG_INFO,
  3604. "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
  3605. h0->single_decode_warning = 1;
  3606. }
  3607. if (h != h0) {
  3608. av_log(h->avctx, AV_LOG_ERROR,
  3609. "Deblocking switched inside frame.\n");
  3610. return 1;
  3611. }
  3612. }
  3613. }
  3614. h->qp_thresh = 15 -
  3615. FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) -
  3616. FFMAX3(0,
  3617. h->pps.chroma_qp_index_offset[0],
  3618. h->pps.chroma_qp_index_offset[1]) +
  3619. 6 * (h->sps.bit_depth_luma - 8);
  3620. h0->last_slice_type = slice_type;
  3621. memcpy(h0->last_ref_count, h0->ref_count, sizeof(h0->last_ref_count));
  3622. h->slice_num = ++h0->current_slice;
  3623. if (h->slice_num)
  3624. h0->slice_row[(h->slice_num-1)&(MAX_SLICES-1)]= h->resync_mb_y;
  3625. if ( h0->slice_row[h->slice_num&(MAX_SLICES-1)] + 3 >= h->resync_mb_y
  3626. && h0->slice_row[h->slice_num&(MAX_SLICES-1)] <= h->resync_mb_y
  3627. && h->slice_num >= MAX_SLICES) {
  3628. //in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case
  3629. av_log(h->avctx, AV_LOG_WARNING, "Possibly too many slices (%d >= %d), increase MAX_SLICES and recompile if there are artifacts\n", h->slice_num, MAX_SLICES);
  3630. }
  3631. for (j = 0; j < 2; j++) {
  3632. int id_list[16];
  3633. int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j];
  3634. for (i = 0; i < 16; i++) {
  3635. id_list[i] = 60;
  3636. if (j < h->list_count && i < h->ref_count[j] &&
  3637. h->ref_list[j][i].f.buf[0]) {
  3638. int k;
  3639. AVBuffer *buf = h->ref_list[j][i].f.buf[0]->buffer;
  3640. for (k = 0; k < h->short_ref_count; k++)
  3641. if (h->short_ref[k]->f.buf[0]->buffer == buf) {
  3642. id_list[i] = k;
  3643. break;
  3644. }
  3645. for (k = 0; k < h->long_ref_count; k++)
  3646. if (h->long_ref[k] && h->long_ref[k]->f.buf[0]->buffer == buf) {
  3647. id_list[i] = h->short_ref_count + k;
  3648. break;
  3649. }
  3650. }
  3651. }
  3652. ref2frm[0] =
  3653. ref2frm[1] = -1;
  3654. for (i = 0; i < 16; i++)
  3655. ref2frm[i + 2] = 4 * id_list[i] + (h->ref_list[j][i].reference & 3);
  3656. ref2frm[18 + 0] =
  3657. ref2frm[18 + 1] = -1;
  3658. for (i = 16; i < 48; i++)
  3659. ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
  3660. (h->ref_list[j][i].reference & 3);
  3661. }
  3662. if (h->ref_count[0]) h264_set_erpic(&h->er.last_pic, &h->ref_list[0][0]);
  3663. if (h->ref_count[1]) h264_set_erpic(&h->er.next_pic, &h->ref_list[1][0]);
  3664. h->er.ref_count = h->ref_count[0];
  3665. h0->au_pps_id = pps_id;
  3666. h->sps.new =
  3667. h0->sps_buffers[h->pps.sps_id]->new = 0;
  3668. h->current_sps_id = h->pps.sps_id;
  3669. if (h->avctx->debug & FF_DEBUG_PICT_INFO) {
  3670. av_log(h->avctx, AV_LOG_DEBUG,
  3671. "slice:%d %s mb:%d %c%s%s pps:%u frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d:%d:%d weight:%d%s %s\n",
  3672. h->slice_num,
  3673. (h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
  3674. first_mb_in_slice,
  3675. av_get_picture_type_char(h->slice_type),
  3676. h->slice_type_fixed ? " fix" : "",
  3677. h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
  3678. pps_id, h->frame_num,
  3679. h->cur_pic_ptr->field_poc[0],
  3680. h->cur_pic_ptr->field_poc[1],
  3681. h->ref_count[0], h->ref_count[1],
  3682. h->qscale,
  3683. h->deblocking_filter,
  3684. h->slice_alpha_c0_offset, h->slice_beta_offset,
  3685. h->use_weight,
  3686. h->use_weight == 1 && h->use_weight_chroma ? "c" : "",
  3687. h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
  3688. }
  3689. return 0;
  3690. }
  3691. int ff_h264_get_slice_type(const H264Context *h)
  3692. {
  3693. switch (h->slice_type) {
  3694. case AV_PICTURE_TYPE_P:
  3695. return 0;
  3696. case AV_PICTURE_TYPE_B:
  3697. return 1;
  3698. case AV_PICTURE_TYPE_I:
  3699. return 2;
  3700. case AV_PICTURE_TYPE_SP:
  3701. return 3;
  3702. case AV_PICTURE_TYPE_SI:
  3703. return 4;
  3704. default:
  3705. return AVERROR_INVALIDDATA;
  3706. }
  3707. }
  3708. static av_always_inline void fill_filter_caches_inter(H264Context *h,
  3709. int mb_type, int top_xy,
  3710. int left_xy[LEFT_MBS],
  3711. int top_type,
  3712. int left_type[LEFT_MBS],
  3713. int mb_xy, int list)
  3714. {
  3715. int b_stride = h->b_stride;
  3716. int16_t(*mv_dst)[2] = &h->mv_cache[list][scan8[0]];
  3717. int8_t *ref_cache = &h->ref_cache[list][scan8[0]];
  3718. if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
  3719. if (USES_LIST(top_type, list)) {
  3720. const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride;
  3721. const int b8_xy = 4 * top_xy + 2;
  3722. int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2));
  3723. AV_COPY128(mv_dst - 1 * 8, h->cur_pic.motion_val[list][b_xy + 0]);
  3724. ref_cache[0 - 1 * 8] =
  3725. ref_cache[1 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 0]];
  3726. ref_cache[2 - 1 * 8] =
  3727. ref_cache[3 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 1]];
  3728. } else {
  3729. AV_ZERO128(mv_dst - 1 * 8);
  3730. AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  3731. }
  3732. if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
  3733. if (USES_LIST(left_type[LTOP], list)) {
  3734. const int b_xy = h->mb2b_xy[left_xy[LTOP]] + 3;
  3735. const int b8_xy = 4 * left_xy[LTOP] + 1;
  3736. int (*ref2frm)[64] =(void*)( h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2));
  3737. AV_COPY32(mv_dst - 1 + 0, h->cur_pic.motion_val[list][b_xy + b_stride * 0]);
  3738. AV_COPY32(mv_dst - 1 + 8, h->cur_pic.motion_val[list][b_xy + b_stride * 1]);
  3739. AV_COPY32(mv_dst - 1 + 16, h->cur_pic.motion_val[list][b_xy + b_stride * 2]);
  3740. AV_COPY32(mv_dst - 1 + 24, h->cur_pic.motion_val[list][b_xy + b_stride * 3]);
  3741. ref_cache[-1 + 0] =
  3742. ref_cache[-1 + 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 0]];
  3743. ref_cache[-1 + 16] =
  3744. ref_cache[-1 + 24] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 1]];
  3745. } else {
  3746. AV_ZERO32(mv_dst - 1 + 0);
  3747. AV_ZERO32(mv_dst - 1 + 8);
  3748. AV_ZERO32(mv_dst - 1 + 16);
  3749. AV_ZERO32(mv_dst - 1 + 24);
  3750. ref_cache[-1 + 0] =
  3751. ref_cache[-1 + 8] =
  3752. ref_cache[-1 + 16] =
  3753. ref_cache[-1 + 24] = LIST_NOT_USED;
  3754. }
  3755. }
  3756. }
  3757. if (!USES_LIST(mb_type, list)) {
  3758. fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
  3759. AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  3760. AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  3761. AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  3762. AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  3763. return;
  3764. }
  3765. {
  3766. int8_t *ref = &h->cur_pic.ref_index[list][4 * mb_xy];
  3767. int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF(h) ? 20 : 2));
  3768. uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]], ref2frm[list][ref[1]]) & 0x00FF00FF) * 0x0101;
  3769. uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]], ref2frm[list][ref[3]]) & 0x00FF00FF) * 0x0101;
  3770. AV_WN32A(&ref_cache[0 * 8], ref01);
  3771. AV_WN32A(&ref_cache[1 * 8], ref01);
  3772. AV_WN32A(&ref_cache[2 * 8], ref23);
  3773. AV_WN32A(&ref_cache[3 * 8], ref23);
  3774. }
  3775. {
  3776. int16_t(*mv_src)[2] = &h->cur_pic.motion_val[list][4 * h->mb_x + 4 * h->mb_y * b_stride];
  3777. AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
  3778. AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
  3779. AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
  3780. AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
  3781. }
  3782. }
  3783. /**
  3784. *
  3785. * @return non zero if the loop filter can be skipped
  3786. */
  3787. static int fill_filter_caches(H264Context *h, int mb_type)
  3788. {
  3789. const int mb_xy = h->mb_xy;
  3790. int top_xy, left_xy[LEFT_MBS];
  3791. int top_type, left_type[LEFT_MBS];
  3792. uint8_t *nnz;
  3793. uint8_t *nnz_cache;
  3794. top_xy = mb_xy - (h->mb_stride << MB_FIELD(h));
  3795. /* Wow, what a mess, why didn't they simplify the interlacing & intra
  3796. * stuff, I can't imagine that these complex rules are worth it. */
  3797. left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
  3798. if (FRAME_MBAFF(h)) {
  3799. const int left_mb_field_flag = IS_INTERLACED(h->cur_pic.mb_type[mb_xy - 1]);
  3800. const int curr_mb_field_flag = IS_INTERLACED(mb_type);
  3801. if (h->mb_y & 1) {
  3802. if (left_mb_field_flag != curr_mb_field_flag)
  3803. left_xy[LTOP] -= h->mb_stride;
  3804. } else {
  3805. if (curr_mb_field_flag)
  3806. top_xy += h->mb_stride &
  3807. (((h->cur_pic.mb_type[top_xy] >> 7) & 1) - 1);
  3808. if (left_mb_field_flag != curr_mb_field_flag)
  3809. left_xy[LBOT] += h->mb_stride;
  3810. }
  3811. }
  3812. h->top_mb_xy = top_xy;
  3813. h->left_mb_xy[LTOP] = left_xy[LTOP];
  3814. h->left_mb_xy[LBOT] = left_xy[LBOT];
  3815. {
  3816. /* For sufficiently low qp, filtering wouldn't do anything.
  3817. * This is a conservative estimate: could also check beta_offset
  3818. * and more accurate chroma_qp. */
  3819. int qp_thresh = h->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
  3820. int qp = h->cur_pic.qscale_table[mb_xy];
  3821. if (qp <= qp_thresh &&
  3822. (left_xy[LTOP] < 0 ||
  3823. ((qp + h->cur_pic.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
  3824. (top_xy < 0 ||
  3825. ((qp + h->cur_pic.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
  3826. if (!FRAME_MBAFF(h))
  3827. return 1;
  3828. if ((left_xy[LTOP] < 0 ||
  3829. ((qp + h->cur_pic.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
  3830. (top_xy < h->mb_stride ||
  3831. ((qp + h->cur_pic.qscale_table[top_xy - h->mb_stride] + 1) >> 1) <= qp_thresh))
  3832. return 1;
  3833. }
  3834. }
  3835. top_type = h->cur_pic.mb_type[top_xy];
  3836. left_type[LTOP] = h->cur_pic.mb_type[left_xy[LTOP]];
  3837. left_type[LBOT] = h->cur_pic.mb_type[left_xy[LBOT]];
  3838. if (h->deblocking_filter == 2) {
  3839. if (h->slice_table[top_xy] != h->slice_num)
  3840. top_type = 0;
  3841. if (h->slice_table[left_xy[LBOT]] != h->slice_num)
  3842. left_type[LTOP] = left_type[LBOT] = 0;
  3843. } else {
  3844. if (h->slice_table[top_xy] == 0xFFFF)
  3845. top_type = 0;
  3846. if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
  3847. left_type[LTOP] = left_type[LBOT] = 0;
  3848. }
  3849. h->top_type = top_type;
  3850. h->left_type[LTOP] = left_type[LTOP];
  3851. h->left_type[LBOT] = left_type[LBOT];
  3852. if (IS_INTRA(mb_type))
  3853. return 0;
  3854. fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
  3855. top_type, left_type, mb_xy, 0);
  3856. if (h->list_count == 2)
  3857. fill_filter_caches_inter(h, mb_type, top_xy, left_xy,
  3858. top_type, left_type, mb_xy, 1);
  3859. nnz = h->non_zero_count[mb_xy];
  3860. nnz_cache = h->non_zero_count_cache;
  3861. AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
  3862. AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
  3863. AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
  3864. AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
  3865. h->cbp = h->cbp_table[mb_xy];
  3866. if (top_type) {
  3867. nnz = h->non_zero_count[top_xy];
  3868. AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
  3869. }
  3870. if (left_type[LTOP]) {
  3871. nnz = h->non_zero_count[left_xy[LTOP]];
  3872. nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
  3873. nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
  3874. nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
  3875. nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
  3876. }
  3877. /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
  3878. * from what the loop filter needs */
  3879. if (!CABAC(h) && h->pps.transform_8x8_mode) {
  3880. if (IS_8x8DCT(top_type)) {
  3881. nnz_cache[4 + 8 * 0] =
  3882. nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
  3883. nnz_cache[6 + 8 * 0] =
  3884. nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
  3885. }
  3886. if (IS_8x8DCT(left_type[LTOP])) {
  3887. nnz_cache[3 + 8 * 1] =
  3888. nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
  3889. }
  3890. if (IS_8x8DCT(left_type[LBOT])) {
  3891. nnz_cache[3 + 8 * 3] =
  3892. nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
  3893. }
  3894. if (IS_8x8DCT(mb_type)) {
  3895. nnz_cache[scan8[0]] =
  3896. nnz_cache[scan8[1]] =
  3897. nnz_cache[scan8[2]] =
  3898. nnz_cache[scan8[3]] = (h->cbp & 0x1000) >> 12;
  3899. nnz_cache[scan8[0 + 4]] =
  3900. nnz_cache[scan8[1 + 4]] =
  3901. nnz_cache[scan8[2 + 4]] =
  3902. nnz_cache[scan8[3 + 4]] = (h->cbp & 0x2000) >> 12;
  3903. nnz_cache[scan8[0 + 8]] =
  3904. nnz_cache[scan8[1 + 8]] =
  3905. nnz_cache[scan8[2 + 8]] =
  3906. nnz_cache[scan8[3 + 8]] = (h->cbp & 0x4000) >> 12;
  3907. nnz_cache[scan8[0 + 12]] =
  3908. nnz_cache[scan8[1 + 12]] =
  3909. nnz_cache[scan8[2 + 12]] =
  3910. nnz_cache[scan8[3 + 12]] = (h->cbp & 0x8000) >> 12;
  3911. }
  3912. }
  3913. return 0;
  3914. }
  3915. static void loop_filter(H264Context *h, int start_x, int end_x)
  3916. {
  3917. uint8_t *dest_y, *dest_cb, *dest_cr;
  3918. int linesize, uvlinesize, mb_x, mb_y;
  3919. const int end_mb_y = h->mb_y + FRAME_MBAFF(h);
  3920. const int old_slice_type = h->slice_type;
  3921. const int pixel_shift = h->pixel_shift;
  3922. const int block_h = 16 >> h->chroma_y_shift;
  3923. if (h->deblocking_filter) {
  3924. for (mb_x = start_x; mb_x < end_x; mb_x++)
  3925. for (mb_y = end_mb_y - FRAME_MBAFF(h); mb_y <= end_mb_y; mb_y++) {
  3926. int mb_xy, mb_type;
  3927. mb_xy = h->mb_xy = mb_x + mb_y * h->mb_stride;
  3928. h->slice_num = h->slice_table[mb_xy];
  3929. mb_type = h->cur_pic.mb_type[mb_xy];
  3930. h->list_count = h->list_counts[mb_xy];
  3931. if (FRAME_MBAFF(h))
  3932. h->mb_mbaff =
  3933. h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
  3934. h->mb_x = mb_x;
  3935. h->mb_y = mb_y;
  3936. dest_y = h->cur_pic.f.data[0] +
  3937. ((mb_x << pixel_shift) + mb_y * h->linesize) * 16;
  3938. dest_cb = h->cur_pic.f.data[1] +
  3939. (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
  3940. mb_y * h->uvlinesize * block_h;
  3941. dest_cr = h->cur_pic.f.data[2] +
  3942. (mb_x << pixel_shift) * (8 << CHROMA444(h)) +
  3943. mb_y * h->uvlinesize * block_h;
  3944. // FIXME simplify above
  3945. if (MB_FIELD(h)) {
  3946. linesize = h->mb_linesize = h->linesize * 2;
  3947. uvlinesize = h->mb_uvlinesize = h->uvlinesize * 2;
  3948. if (mb_y & 1) { // FIXME move out of this function?
  3949. dest_y -= h->linesize * 15;
  3950. dest_cb -= h->uvlinesize * (block_h - 1);
  3951. dest_cr -= h->uvlinesize * (block_h - 1);
  3952. }
  3953. } else {
  3954. linesize = h->mb_linesize = h->linesize;
  3955. uvlinesize = h->mb_uvlinesize = h->uvlinesize;
  3956. }
  3957. backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize,
  3958. uvlinesize, 0);
  3959. if (fill_filter_caches(h, mb_type))
  3960. continue;
  3961. h->chroma_qp[0] = get_chroma_qp(h, 0, h->cur_pic.qscale_table[mb_xy]);
  3962. h->chroma_qp[1] = get_chroma_qp(h, 1, h->cur_pic.qscale_table[mb_xy]);
  3963. if (FRAME_MBAFF(h)) {
  3964. ff_h264_filter_mb(h, mb_x, mb_y, dest_y, dest_cb, dest_cr,
  3965. linesize, uvlinesize);
  3966. } else {
  3967. ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb,
  3968. dest_cr, linesize, uvlinesize);
  3969. }
  3970. }
  3971. }
  3972. h->slice_type = old_slice_type;
  3973. h->mb_x = end_x;
  3974. h->mb_y = end_mb_y - FRAME_MBAFF(h);
  3975. h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale);
  3976. h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale);
  3977. }
  3978. static void predict_field_decoding_flag(H264Context *h)
  3979. {
  3980. const int mb_xy = h->mb_x + h->mb_y * h->mb_stride;
  3981. int mb_type = (h->slice_table[mb_xy - 1] == h->slice_num) ?
  3982. h->cur_pic.mb_type[mb_xy - 1] :
  3983. (h->slice_table[mb_xy - h->mb_stride] == h->slice_num) ?
  3984. h->cur_pic.mb_type[mb_xy - h->mb_stride] : 0;
  3985. h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
  3986. }
  3987. /**
  3988. * Draw edges and report progress for the last MB row.
  3989. */
  3990. static void decode_finish_row(H264Context *h)
  3991. {
  3992. int top = 16 * (h->mb_y >> FIELD_PICTURE(h));
  3993. int pic_height = 16 * h->mb_height >> FIELD_PICTURE(h);
  3994. int height = 16 << FRAME_MBAFF(h);
  3995. int deblock_border = (16 + 4) << FRAME_MBAFF(h);
  3996. if (h->deblocking_filter) {
  3997. if ((top + height) >= pic_height)
  3998. height += deblock_border;
  3999. top -= deblock_border;
  4000. }
  4001. if (top >= pic_height || (top + height) < 0)
  4002. return;
  4003. height = FFMIN(height, pic_height - top);
  4004. if (top < 0) {
  4005. height = top + height;
  4006. top = 0;
  4007. }
  4008. ff_h264_draw_horiz_band(h, top, height);
  4009. if (h->droppable || h->er.error_occurred)
  4010. return;
  4011. ff_thread_report_progress(&h->cur_pic_ptr->tf, top + height - 1,
  4012. h->picture_structure == PICT_BOTTOM_FIELD);
  4013. }
  4014. static void er_add_slice(H264Context *h, int startx, int starty,
  4015. int endx, int endy, int status)
  4016. {
  4017. if (CONFIG_ERROR_RESILIENCE) {
  4018. ERContext *er = &h->er;
  4019. ff_er_add_slice(er, startx, starty, endx, endy, status);
  4020. }
  4021. }
  4022. static int decode_slice(struct AVCodecContext *avctx, void *arg)
  4023. {
  4024. H264Context *h = *(void **)arg;
  4025. int lf_x_start = h->mb_x;
  4026. h->mb_skip_run = -1;
  4027. av_assert0(h->block_offset[15] == (4 * ((scan8[15] - scan8[0]) & 7) << h->pixel_shift) + 4 * h->linesize * ((scan8[15] - scan8[0]) >> 3));
  4028. h->is_complex = FRAME_MBAFF(h) || h->picture_structure != PICT_FRAME ||
  4029. avctx->codec_id != AV_CODEC_ID_H264 ||
  4030. (CONFIG_GRAY && (h->flags & CODEC_FLAG_GRAY));
  4031. if (!(h->avctx->active_thread_type & FF_THREAD_SLICE) && h->picture_structure == PICT_FRAME && h->er.error_status_table) {
  4032. const int start_i = av_clip(h->resync_mb_x + h->resync_mb_y * h->mb_width, 0, h->mb_num - 1);
  4033. if (start_i) {
  4034. int prev_status = h->er.error_status_table[h->er.mb_index2xy[start_i - 1]];
  4035. prev_status &= ~ VP_START;
  4036. if (prev_status != (ER_MV_END | ER_DC_END | ER_AC_END))
  4037. h->er.error_occurred = 1;
  4038. }
  4039. }
  4040. if (h->pps.cabac) {
  4041. /* realign */
  4042. align_get_bits(&h->gb);
  4043. /* init cabac */
  4044. ff_init_cabac_decoder(&h->cabac,
  4045. h->gb.buffer + get_bits_count(&h->gb) / 8,
  4046. (get_bits_left(&h->gb) + 7) / 8);
  4047. ff_h264_init_cabac_states(h);
  4048. for (;;) {
  4049. // START_TIMER
  4050. int ret = ff_h264_decode_mb_cabac(h);
  4051. int eos;
  4052. // STOP_TIMER("decode_mb_cabac")
  4053. if (ret >= 0)
  4054. ff_h264_hl_decode_mb(h);
  4055. // FIXME optimal? or let mb_decode decode 16x32 ?
  4056. if (ret >= 0 && FRAME_MBAFF(h)) {
  4057. h->mb_y++;
  4058. ret = ff_h264_decode_mb_cabac(h);
  4059. if (ret >= 0)
  4060. ff_h264_hl_decode_mb(h);
  4061. h->mb_y--;
  4062. }
  4063. eos = get_cabac_terminate(&h->cabac);
  4064. if ((h->workaround_bugs & FF_BUG_TRUNCATED) &&
  4065. h->cabac.bytestream > h->cabac.bytestream_end + 2) {
  4066. er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
  4067. h->mb_y, ER_MB_END);
  4068. if (h->mb_x >= lf_x_start)
  4069. loop_filter(h, lf_x_start, h->mb_x + 1);
  4070. return 0;
  4071. }
  4072. if (h->cabac.bytestream > h->cabac.bytestream_end + 2 )
  4073. av_log(h->avctx, AV_LOG_DEBUG, "bytestream overread %td\n", h->cabac.bytestream_end - h->cabac.bytestream);
  4074. if (ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 4) {
  4075. av_log(h->avctx, AV_LOG_ERROR,
  4076. "error while decoding MB %d %d, bytestream %td\n",
  4077. h->mb_x, h->mb_y,
  4078. h->cabac.bytestream_end - h->cabac.bytestream);
  4079. er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
  4080. h->mb_y, ER_MB_ERROR);
  4081. return AVERROR_INVALIDDATA;
  4082. }
  4083. if (++h->mb_x >= h->mb_width) {
  4084. loop_filter(h, lf_x_start, h->mb_x);
  4085. h->mb_x = lf_x_start = 0;
  4086. decode_finish_row(h);
  4087. ++h->mb_y;
  4088. if (FIELD_OR_MBAFF_PICTURE(h)) {
  4089. ++h->mb_y;
  4090. if (FRAME_MBAFF(h) && h->mb_y < h->mb_height)
  4091. predict_field_decoding_flag(h);
  4092. }
  4093. }
  4094. if (eos || h->mb_y >= h->mb_height) {
  4095. tprintf(h->avctx, "slice end %d %d\n",
  4096. get_bits_count(&h->gb), h->gb.size_in_bits);
  4097. er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,
  4098. h->mb_y, ER_MB_END);
  4099. if (h->mb_x > lf_x_start)
  4100. loop_filter(h, lf_x_start, h->mb_x);
  4101. return 0;
  4102. }
  4103. }
  4104. } else {
  4105. for (;;) {
  4106. int ret = ff_h264_decode_mb_cavlc(h);
  4107. if (ret >= 0)
  4108. ff_h264_hl_decode_mb(h);
  4109. // FIXME optimal? or let mb_decode decode 16x32 ?
  4110. if (ret >= 0 && FRAME_MBAFF(h)) {
  4111. h->mb_y++;
  4112. ret = ff_h264_decode_mb_cavlc(h);
  4113. if (ret >= 0)
  4114. ff_h264_hl_decode_mb(h);
  4115. h->mb_y--;
  4116. }
  4117. if (ret < 0) {
  4118. av_log(h->avctx, AV_LOG_ERROR,
  4119. "error while decoding MB %d %d\n", h->mb_x, h->mb_y);
  4120. er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
  4121. h->mb_y, ER_MB_ERROR);
  4122. return ret;
  4123. }
  4124. if (++h->mb_x >= h->mb_width) {
  4125. loop_filter(h, lf_x_start, h->mb_x);
  4126. h->mb_x = lf_x_start = 0;
  4127. decode_finish_row(h);
  4128. ++h->mb_y;
  4129. if (FIELD_OR_MBAFF_PICTURE(h)) {
  4130. ++h->mb_y;
  4131. if (FRAME_MBAFF(h) && h->mb_y < h->mb_height)
  4132. predict_field_decoding_flag(h);
  4133. }
  4134. if (h->mb_y >= h->mb_height) {
  4135. tprintf(h->avctx, "slice end %d %d\n",
  4136. get_bits_count(&h->gb), h->gb.size_in_bits);
  4137. if ( get_bits_left(&h->gb) == 0
  4138. || get_bits_left(&h->gb) > 0 && !(h->avctx->err_recognition & AV_EF_AGGRESSIVE)) {
  4139. er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
  4140. h->mb_x - 1, h->mb_y,
  4141. ER_MB_END);
  4142. return 0;
  4143. } else {
  4144. er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
  4145. h->mb_x, h->mb_y,
  4146. ER_MB_END);
  4147. return AVERROR_INVALIDDATA;
  4148. }
  4149. }
  4150. }
  4151. if (get_bits_left(&h->gb) <= 0 && h->mb_skip_run <= 0) {
  4152. tprintf(h->avctx, "slice end %d %d\n",
  4153. get_bits_count(&h->gb), h->gb.size_in_bits);
  4154. if (get_bits_left(&h->gb) == 0) {
  4155. er_add_slice(h, h->resync_mb_x, h->resync_mb_y,
  4156. h->mb_x - 1, h->mb_y,
  4157. ER_MB_END);
  4158. if (h->mb_x > lf_x_start)
  4159. loop_filter(h, lf_x_start, h->mb_x);
  4160. return 0;
  4161. } else {
  4162. er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,
  4163. h->mb_y, ER_MB_ERROR);
  4164. return AVERROR_INVALIDDATA;
  4165. }
  4166. }
  4167. }
  4168. }
  4169. }
  4170. /**
  4171. * Call decode_slice() for each context.
  4172. *
  4173. * @param h h264 master context
  4174. * @param context_count number of contexts to execute
  4175. */
  4176. static int execute_decode_slices(H264Context *h, unsigned context_count)
  4177. {
  4178. AVCodecContext *const avctx = h->avctx;
  4179. H264Context *hx;
  4180. int i;
  4181. av_assert0(h->mb_y < h->mb_height);
  4182. if (h->avctx->hwaccel ||
  4183. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  4184. return 0;
  4185. if (context_count == 1) {
  4186. return decode_slice(avctx, &h);
  4187. } else {
  4188. av_assert0(context_count > 0);
  4189. for (i = 1; i < context_count; i++) {
  4190. hx = h->thread_context[i];
  4191. if (CONFIG_ERROR_RESILIENCE) {
  4192. hx->er.error_count = 0;
  4193. }
  4194. hx->x264_build = h->x264_build;
  4195. }
  4196. avctx->execute(avctx, decode_slice, h->thread_context,
  4197. NULL, context_count, sizeof(void *));
  4198. /* pull back stuff from slices to master context */
  4199. hx = h->thread_context[context_count - 1];
  4200. h->mb_x = hx->mb_x;
  4201. h->mb_y = hx->mb_y;
  4202. h->droppable = hx->droppable;
  4203. h->picture_structure = hx->picture_structure;
  4204. if (CONFIG_ERROR_RESILIENCE) {
  4205. for (i = 1; i < context_count; i++)
  4206. h->er.error_count += h->thread_context[i]->er.error_count;
  4207. }
  4208. }
  4209. return 0;
  4210. }
  4211. static const uint8_t start_code[] = { 0x00, 0x00, 0x01 };
  4212. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
  4213. int parse_extradata)
  4214. {
  4215. AVCodecContext *const avctx = h->avctx;
  4216. H264Context *hx; ///< thread context
  4217. int buf_index;
  4218. unsigned context_count;
  4219. int next_avc;
  4220. int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);
  4221. int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
  4222. int nal_index;
  4223. int idr_cleared=0;
  4224. int first_slice = 0;
  4225. int ret = 0;
  4226. h->nal_unit_type= 0;
  4227. if(!h->slice_context_count)
  4228. h->slice_context_count= 1;
  4229. h->max_contexts = h->slice_context_count;
  4230. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS)) {
  4231. h->current_slice = 0;
  4232. if (!h->first_field)
  4233. h->cur_pic_ptr = NULL;
  4234. ff_h264_reset_sei(h);
  4235. }
  4236. if (h->nal_length_size == 4) {
  4237. if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
  4238. h->is_avc = 0;
  4239. }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
  4240. h->is_avc = 1;
  4241. }
  4242. for (; pass <= 1; pass++) {
  4243. buf_index = 0;
  4244. context_count = 0;
  4245. next_avc = h->is_avc ? 0 : buf_size;
  4246. nal_index = 0;
  4247. for (;;) {
  4248. int consumed;
  4249. int dst_length;
  4250. int bit_length;
  4251. const uint8_t *ptr;
  4252. int i, nalsize = 0;
  4253. int err;
  4254. if (buf_index >= next_avc) {
  4255. if (buf_index >= buf_size - h->nal_length_size)
  4256. break;
  4257. nalsize = 0;
  4258. for (i = 0; i < h->nal_length_size; i++)
  4259. nalsize = (nalsize << 8) | buf[buf_index++];
  4260. if (nalsize <= 0 || nalsize > buf_size - buf_index) {
  4261. av_log(h->avctx, AV_LOG_ERROR,
  4262. "AVC: nal size %d\n", nalsize);
  4263. break;
  4264. }
  4265. next_avc = buf_index + nalsize;
  4266. } else {
  4267. // start code prefix search
  4268. for (; buf_index + 3 < next_avc; buf_index++)
  4269. // This should always succeed in the first iteration.
  4270. if (buf[buf_index] == 0 &&
  4271. buf[buf_index + 1] == 0 &&
  4272. buf[buf_index + 2] == 1)
  4273. break;
  4274. if (buf_index + 3 >= buf_size) {
  4275. buf_index = buf_size;
  4276. break;
  4277. }
  4278. buf_index += 3;
  4279. if (buf_index >= next_avc)
  4280. continue;
  4281. }
  4282. hx = h->thread_context[context_count];
  4283. ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
  4284. &consumed, next_avc - buf_index);
  4285. if (ptr == NULL || dst_length < 0) {
  4286. ret = -1;
  4287. goto end;
  4288. }
  4289. i = buf_index + consumed;
  4290. if ((h->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
  4291. buf[i] == 0x00 && buf[i + 1] == 0x00 &&
  4292. buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
  4293. h->workaround_bugs |= FF_BUG_TRUNCATED;
  4294. if (!(h->workaround_bugs & FF_BUG_TRUNCATED))
  4295. while (dst_length > 0 && ptr[dst_length - 1] == 0)
  4296. dst_length--;
  4297. bit_length = !dst_length ? 0
  4298. : (8 * dst_length -
  4299. decode_rbsp_trailing(h, ptr + dst_length - 1));
  4300. if (h->avctx->debug & FF_DEBUG_STARTCODE)
  4301. av_log(h->avctx, AV_LOG_DEBUG,
  4302. "NAL %d/%d at %d/%d length %d pass %d\n",
  4303. hx->nal_unit_type, hx->nal_ref_idc, buf_index, buf_size, dst_length, pass);
  4304. if (h->is_avc && (nalsize != consumed) && nalsize)
  4305. av_log(h->avctx, AV_LOG_DEBUG,
  4306. "AVC: Consumed only %d bytes instead of %d\n",
  4307. consumed, nalsize);
  4308. buf_index += consumed;
  4309. nal_index++;
  4310. if (pass == 0) {
  4311. /* packets can sometimes contain multiple PPS/SPS,
  4312. * e.g. two PAFF field pictures in one packet, or a demuxer
  4313. * which splits NALs strangely if so, when frame threading we
  4314. * can't start the next thread until we've read all of them */
  4315. switch (hx->nal_unit_type) {
  4316. case NAL_SPS:
  4317. case NAL_PPS:
  4318. nals_needed = nal_index;
  4319. break;
  4320. case NAL_DPA:
  4321. case NAL_IDR_SLICE:
  4322. case NAL_SLICE:
  4323. init_get_bits(&hx->gb, ptr, bit_length);
  4324. if (!get_ue_golomb(&hx->gb) ||
  4325. !first_slice ||
  4326. first_slice != hx->nal_unit_type)
  4327. nals_needed = nal_index;
  4328. if (!first_slice)
  4329. first_slice = hx->nal_unit_type;
  4330. }
  4331. continue;
  4332. }
  4333. if (!first_slice)
  4334. switch (hx->nal_unit_type) {
  4335. case NAL_DPA:
  4336. case NAL_IDR_SLICE:
  4337. case NAL_SLICE:
  4338. first_slice = hx->nal_unit_type;
  4339. }
  4340. if (avctx->skip_frame >= AVDISCARD_NONREF &&
  4341. h->nal_ref_idc == 0 &&
  4342. h->nal_unit_type != NAL_SEI)
  4343. continue;
  4344. again:
  4345. if ( !(avctx->active_thread_type & FF_THREAD_FRAME)
  4346. || nals_needed >= nal_index)
  4347. h->au_pps_id = -1;
  4348. /* Ignore per frame NAL unit type during extradata
  4349. * parsing. Decoding slices is not possible in codec init
  4350. * with frame-mt */
  4351. if (parse_extradata) {
  4352. switch (hx->nal_unit_type) {
  4353. case NAL_IDR_SLICE:
  4354. case NAL_SLICE:
  4355. case NAL_DPA:
  4356. case NAL_DPB:
  4357. case NAL_DPC:
  4358. av_log(h->avctx, AV_LOG_WARNING,
  4359. "Ignoring NAL %d in global header/extradata\n",
  4360. hx->nal_unit_type);
  4361. // fall through to next case
  4362. case NAL_AUXILIARY_SLICE:
  4363. hx->nal_unit_type = NAL_FF_IGNORE;
  4364. }
  4365. }
  4366. err = 0;
  4367. switch (hx->nal_unit_type) {
  4368. case NAL_IDR_SLICE:
  4369. if (h->nal_unit_type != NAL_IDR_SLICE) {
  4370. av_log(h->avctx, AV_LOG_ERROR,
  4371. "Invalid mix of idr and non-idr slices\n");
  4372. ret = -1;
  4373. goto end;
  4374. }
  4375. if(!idr_cleared)
  4376. idr(h); // FIXME ensure we don't lose some frames if there is reordering
  4377. idr_cleared = 1;
  4378. case NAL_SLICE:
  4379. init_get_bits(&hx->gb, ptr, bit_length);
  4380. hx->intra_gb_ptr =
  4381. hx->inter_gb_ptr = &hx->gb;
  4382. hx->data_partitioning = 0;
  4383. if ((err = decode_slice_header(hx, h)))
  4384. break;
  4385. if (h->sei_recovery_frame_cnt >= 0) {
  4386. if (h->frame_num != h->sei_recovery_frame_cnt || hx->slice_type_nos != AV_PICTURE_TYPE_I)
  4387. h->valid_recovery_point = 1;
  4388. if ( h->recovery_frame < 0
  4389. || ((h->recovery_frame - h->frame_num) & ((1 << h->sps.log2_max_frame_num)-1)) > h->sei_recovery_frame_cnt) {
  4390. h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) &
  4391. ((1 << h->sps.log2_max_frame_num) - 1);
  4392. if (!h->valid_recovery_point)
  4393. h->recovery_frame = h->frame_num;
  4394. }
  4395. }
  4396. h->cur_pic_ptr->f.key_frame |=
  4397. (hx->nal_unit_type == NAL_IDR_SLICE);
  4398. if (hx->nal_unit_type == NAL_IDR_SLICE ||
  4399. h->recovery_frame == h->frame_num) {
  4400. h->recovery_frame = -1;
  4401. h->cur_pic_ptr->recovered = 1;
  4402. }
  4403. // If we have an IDR, all frames after it in decoded order are
  4404. // "recovered".
  4405. if (hx->nal_unit_type == NAL_IDR_SLICE)
  4406. h->frame_recovered |= FRAME_RECOVERED_IDR;
  4407. h->frame_recovered |= 3*!!(avctx->flags2 & CODEC_FLAG2_SHOW_ALL);
  4408. h->frame_recovered |= 3*!!(avctx->flags & CODEC_FLAG_OUTPUT_CORRUPT);
  4409. #if 1
  4410. h->cur_pic_ptr->recovered |= h->frame_recovered;
  4411. #else
  4412. h->cur_pic_ptr->recovered |= !!(h->frame_recovered & FRAME_RECOVERED_IDR);
  4413. #endif
  4414. if (h->current_slice == 1) {
  4415. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS))
  4416. decode_postinit(h, nal_index >= nals_needed);
  4417. if (h->avctx->hwaccel &&
  4418. (ret = h->avctx->hwaccel->start_frame(h->avctx, NULL, 0)) < 0)
  4419. return ret;
  4420. if (CONFIG_H264_VDPAU_DECODER &&
  4421. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  4422. ff_vdpau_h264_picture_start(h);
  4423. }
  4424. if (hx->redundant_pic_count == 0 &&
  4425. (avctx->skip_frame < AVDISCARD_NONREF ||
  4426. hx->nal_ref_idc) &&
  4427. (avctx->skip_frame < AVDISCARD_BIDIR ||
  4428. hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
  4429. (avctx->skip_frame < AVDISCARD_NONKEY ||
  4430. hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
  4431. avctx->skip_frame < AVDISCARD_ALL) {
  4432. if (avctx->hwaccel) {
  4433. ret = avctx->hwaccel->decode_slice(avctx,
  4434. &buf[buf_index - consumed],
  4435. consumed);
  4436. if (ret < 0)
  4437. return ret;
  4438. } else if (CONFIG_H264_VDPAU_DECODER &&
  4439. h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
  4440. ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0],
  4441. start_code,
  4442. sizeof(start_code));
  4443. ff_vdpau_add_data_chunk(h->cur_pic_ptr->f.data[0],
  4444. &buf[buf_index - consumed],
  4445. consumed);
  4446. } else
  4447. context_count++;
  4448. }
  4449. break;
  4450. case NAL_DPA:
  4451. if (h->avctx->flags & CODEC_FLAG2_CHUNKS) {
  4452. av_log(h->avctx, AV_LOG_ERROR,
  4453. "Decoding in chunks is not supported for "
  4454. "partitioned slices.\n");
  4455. return AVERROR(ENOSYS);
  4456. }
  4457. init_get_bits(&hx->gb, ptr, bit_length);
  4458. hx->intra_gb_ptr =
  4459. hx->inter_gb_ptr = NULL;
  4460. if ((err = decode_slice_header(hx, h)) < 0) {
  4461. /* make sure data_partitioning is cleared if it was set
  4462. * before, so we don't try decoding a slice without a valid
  4463. * slice header later */
  4464. h->data_partitioning = 0;
  4465. break;
  4466. }
  4467. hx->data_partitioning = 1;
  4468. break;
  4469. case NAL_DPB:
  4470. init_get_bits(&hx->intra_gb, ptr, bit_length);
  4471. hx->intra_gb_ptr = &hx->intra_gb;
  4472. break;
  4473. case NAL_DPC:
  4474. init_get_bits(&hx->inter_gb, ptr, bit_length);
  4475. hx->inter_gb_ptr = &hx->inter_gb;
  4476. av_log(h->avctx, AV_LOG_ERROR, "Partitioned H.264 support is incomplete\n");
  4477. break;
  4478. if (hx->redundant_pic_count == 0 &&
  4479. hx->intra_gb_ptr &&
  4480. hx->data_partitioning &&
  4481. h->cur_pic_ptr && h->context_initialized &&
  4482. (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
  4483. (avctx->skip_frame < AVDISCARD_BIDIR ||
  4484. hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
  4485. (avctx->skip_frame < AVDISCARD_NONKEY ||
  4486. hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
  4487. avctx->skip_frame < AVDISCARD_ALL)
  4488. context_count++;
  4489. break;
  4490. case NAL_SEI:
  4491. init_get_bits(&h->gb, ptr, bit_length);
  4492. ff_h264_decode_sei(h);
  4493. break;
  4494. case NAL_SPS:
  4495. init_get_bits(&h->gb, ptr, bit_length);
  4496. if (ff_h264_decode_seq_parameter_set(h) < 0 && (h->is_avc ? nalsize : 1)) {
  4497. av_log(h->avctx, AV_LOG_DEBUG,
  4498. "SPS decoding failure, trying again with the complete NAL\n");
  4499. if (h->is_avc)
  4500. av_assert0(next_avc - buf_index + consumed == nalsize);
  4501. if ((next_avc - buf_index + consumed - 1) >= INT_MAX/8)
  4502. break;
  4503. init_get_bits(&h->gb, &buf[buf_index + 1 - consumed],
  4504. 8*(next_avc - buf_index + consumed - 1));
  4505. ff_h264_decode_seq_parameter_set(h);
  4506. }
  4507. break;
  4508. case NAL_PPS:
  4509. init_get_bits(&h->gb, ptr, bit_length);
  4510. ff_h264_decode_picture_parameter_set(h, bit_length);
  4511. break;
  4512. case NAL_AUD:
  4513. case NAL_END_SEQUENCE:
  4514. case NAL_END_STREAM:
  4515. case NAL_FILLER_DATA:
  4516. case NAL_SPS_EXT:
  4517. case NAL_AUXILIARY_SLICE:
  4518. break;
  4519. case NAL_FF_IGNORE:
  4520. break;
  4521. default:
  4522. av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
  4523. hx->nal_unit_type, bit_length);
  4524. }
  4525. if (context_count == h->max_contexts) {
  4526. execute_decode_slices(h, context_count);
  4527. context_count = 0;
  4528. }
  4529. if (err < 0) {
  4530. av_log(h->avctx, AV_LOG_ERROR, "decode_slice_header error\n");
  4531. h->ref_count[0] = h->ref_count[1] = h->list_count = 0;
  4532. } else if (err == 1) {
  4533. /* Slice could not be decoded in parallel mode, copy down
  4534. * NAL unit stuff to context 0 and restart. Note that
  4535. * rbsp_buffer is not transferred, but since we no longer
  4536. * run in parallel mode this should not be an issue. */
  4537. h->nal_unit_type = hx->nal_unit_type;
  4538. h->nal_ref_idc = hx->nal_ref_idc;
  4539. hx = h;
  4540. goto again;
  4541. }
  4542. }
  4543. }
  4544. if (context_count)
  4545. execute_decode_slices(h, context_count);
  4546. end:
  4547. /* clean up */
  4548. if (h->cur_pic_ptr && !h->droppable) {
  4549. ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,
  4550. h->picture_structure == PICT_BOTTOM_FIELD);
  4551. }
  4552. return (ret < 0) ? ret : buf_index;
  4553. }
  4554. /**
  4555. * Return the number of bytes consumed for building the current frame.
  4556. */
  4557. static int get_consumed_bytes(int pos, int buf_size)
  4558. {
  4559. if (pos == 0)
  4560. pos = 1; // avoid infinite loops (i doubt that is needed but ...)
  4561. if (pos + 10 > buf_size)
  4562. pos = buf_size; // oops ;)
  4563. return pos;
  4564. }
  4565. static int output_frame(H264Context *h, AVFrame *dst, H264Picture *srcp)
  4566. {
  4567. AVFrame *src = &srcp->f;
  4568. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(src->format);
  4569. int i;
  4570. int ret = av_frame_ref(dst, src);
  4571. if (ret < 0)
  4572. return ret;
  4573. av_dict_set(&dst->metadata, "stereo_mode", ff_h264_sei_stereo_mode(h), 0);
  4574. if (!srcp->crop)
  4575. return 0;
  4576. for (i = 0; i < desc->nb_components; i++) {
  4577. int hshift = (i > 0) ? desc->log2_chroma_w : 0;
  4578. int vshift = (i > 0) ? desc->log2_chroma_h : 0;
  4579. int off = ((srcp->crop_left >> hshift) << h->pixel_shift) +
  4580. (srcp->crop_top >> vshift) * dst->linesize[i];
  4581. dst->data[i] += off;
  4582. }
  4583. return 0;
  4584. }
  4585. static int h264_decode_frame(AVCodecContext *avctx, void *data,
  4586. int *got_frame, AVPacket *avpkt)
  4587. {
  4588. const uint8_t *buf = avpkt->data;
  4589. int buf_size = avpkt->size;
  4590. H264Context *h = avctx->priv_data;
  4591. AVFrame *pict = data;
  4592. int buf_index = 0;
  4593. H264Picture *out;
  4594. int i, out_idx;
  4595. int ret;
  4596. h->flags = avctx->flags;
  4597. /* reset data partitioning here, to ensure GetBitContexts from previous
  4598. * packets do not get used. */
  4599. h->data_partitioning = 0;
  4600. /* end of stream, output what is still in the buffers */
  4601. if (buf_size == 0) {
  4602. out:
  4603. h->cur_pic_ptr = NULL;
  4604. h->first_field = 0;
  4605. // FIXME factorize this with the output code below
  4606. out = h->delayed_pic[0];
  4607. out_idx = 0;
  4608. for (i = 1;
  4609. h->delayed_pic[i] &&
  4610. !h->delayed_pic[i]->f.key_frame &&
  4611. !h->delayed_pic[i]->mmco_reset;
  4612. i++)
  4613. if (h->delayed_pic[i]->poc < out->poc) {
  4614. out = h->delayed_pic[i];
  4615. out_idx = i;
  4616. }
  4617. for (i = out_idx; h->delayed_pic[i]; i++)
  4618. h->delayed_pic[i] = h->delayed_pic[i + 1];
  4619. if (out) {
  4620. out->reference &= ~DELAYED_PIC_REF;
  4621. ret = output_frame(h, pict, out);
  4622. if (ret < 0)
  4623. return ret;
  4624. *got_frame = 1;
  4625. }
  4626. return buf_index;
  4627. }
  4628. if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
  4629. int cnt= buf[5]&0x1f;
  4630. const uint8_t *p= buf+6;
  4631. while(cnt--){
  4632. int nalsize= AV_RB16(p) + 2;
  4633. if(nalsize > buf_size - (p-buf) || p[2]!=0x67)
  4634. goto not_extra;
  4635. p += nalsize;
  4636. }
  4637. cnt = *(p++);
  4638. if(!cnt)
  4639. goto not_extra;
  4640. while(cnt--){
  4641. int nalsize= AV_RB16(p) + 2;
  4642. if(nalsize > buf_size - (p-buf) || p[2]!=0x68)
  4643. goto not_extra;
  4644. p += nalsize;
  4645. }
  4646. return ff_h264_decode_extradata(h, buf, buf_size);
  4647. }
  4648. not_extra:
  4649. buf_index = decode_nal_units(h, buf, buf_size, 0);
  4650. if (buf_index < 0)
  4651. return AVERROR_INVALIDDATA;
  4652. if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
  4653. av_assert0(buf_index <= buf_size);
  4654. goto out;
  4655. }
  4656. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {
  4657. if (avctx->skip_frame >= AVDISCARD_NONREF ||
  4658. buf_size >= 4 && !memcmp("Q264", buf, 4))
  4659. return buf_size;
  4660. av_log(avctx, AV_LOG_ERROR, "no frame!\n");
  4661. return AVERROR_INVALIDDATA;
  4662. }
  4663. if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||
  4664. (h->mb_y >= h->mb_height && h->mb_height)) {
  4665. if (avctx->flags2 & CODEC_FLAG2_CHUNKS)
  4666. decode_postinit(h, 1);
  4667. field_end(h, 0);
  4668. /* Wait for second field. */
  4669. *got_frame = 0;
  4670. if (h->next_output_pic && (
  4671. h->next_output_pic->recovered)) {
  4672. if (!h->next_output_pic->recovered)
  4673. h->next_output_pic->f.flags |= AV_FRAME_FLAG_CORRUPT;
  4674. ret = output_frame(h, pict, h->next_output_pic);
  4675. if (ret < 0)
  4676. return ret;
  4677. *got_frame = 1;
  4678. if (CONFIG_MPEGVIDEO) {
  4679. ff_print_debug_info2(h->avctx, h->next_output_pic, pict, h->er.mbskip_table,
  4680. &h->low_delay,
  4681. h->mb_width, h->mb_height, h->mb_stride, 1);
  4682. }
  4683. }
  4684. }
  4685. assert(pict->buf[0] || !*got_frame);
  4686. return get_consumed_bytes(buf_index, buf_size);
  4687. }
  4688. av_cold void ff_h264_free_context(H264Context *h)
  4689. {
  4690. int i;
  4691. free_tables(h, 1); // FIXME cleanup init stuff perhaps
  4692. for (i = 0; i < MAX_SPS_COUNT; i++)
  4693. av_freep(h->sps_buffers + i);
  4694. for (i = 0; i < MAX_PPS_COUNT; i++)
  4695. av_freep(h->pps_buffers + i);
  4696. }
  4697. static av_cold int h264_decode_end(AVCodecContext *avctx)
  4698. {
  4699. H264Context *h = avctx->priv_data;
  4700. ff_h264_remove_all_refs(h);
  4701. ff_h264_free_context(h);
  4702. unref_picture(h, &h->cur_pic);
  4703. return 0;
  4704. }
  4705. static const AVProfile profiles[] = {
  4706. { FF_PROFILE_H264_BASELINE, "Baseline" },
  4707. { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
  4708. { FF_PROFILE_H264_MAIN, "Main" },
  4709. { FF_PROFILE_H264_EXTENDED, "Extended" },
  4710. { FF_PROFILE_H264_HIGH, "High" },
  4711. { FF_PROFILE_H264_HIGH_10, "High 10" },
  4712. { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
  4713. { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
  4714. { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
  4715. { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
  4716. { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
  4717. { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
  4718. { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
  4719. { FF_PROFILE_UNKNOWN },
  4720. };
  4721. static const AVOption h264_options[] = {
  4722. {"is_avc", "is avc", offsetof(H264Context, is_avc), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0},
  4723. {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
  4724. {NULL}
  4725. };
  4726. static const AVClass h264_class = {
  4727. .class_name = "H264 Decoder",
  4728. .item_name = av_default_item_name,
  4729. .option = h264_options,
  4730. .version = LIBAVUTIL_VERSION_INT,
  4731. };
  4732. static const AVClass h264_vdpau_class = {
  4733. .class_name = "H264 VDPAU Decoder",
  4734. .item_name = av_default_item_name,
  4735. .option = h264_options,
  4736. .version = LIBAVUTIL_VERSION_INT,
  4737. };
  4738. AVCodec ff_h264_decoder = {
  4739. .name = "h264",
  4740. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
  4741. .type = AVMEDIA_TYPE_VIDEO,
  4742. .id = AV_CODEC_ID_H264,
  4743. .priv_data_size = sizeof(H264Context),
  4744. .init = ff_h264_decode_init,
  4745. .close = h264_decode_end,
  4746. .decode = h264_decode_frame,
  4747. .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
  4748. CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
  4749. CODEC_CAP_FRAME_THREADS,
  4750. .flush = flush_dpb,
  4751. .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
  4752. .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
  4753. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  4754. .priv_class = &h264_class,
  4755. };
  4756. #if CONFIG_H264_VDPAU_DECODER
  4757. AVCodec ff_h264_vdpau_decoder = {
  4758. .name = "h264_vdpau",
  4759. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
  4760. .type = AVMEDIA_TYPE_VIDEO,
  4761. .id = AV_CODEC_ID_H264,
  4762. .priv_data_size = sizeof(H264Context),
  4763. .init = ff_h264_decode_init,
  4764. .close = h264_decode_end,
  4765. .decode = h264_decode_frame,
  4766. .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
  4767. .flush = flush_dpb,
  4768. .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
  4769. AV_PIX_FMT_NONE},
  4770. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  4771. .priv_class = &h264_vdpau_class,
  4772. };
  4773. #endif