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.

5392 lines
201KB

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