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.

5040 lines
186KB

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