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.

5018 lines
185KB

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