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.

4960 lines
183KB

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