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.

4919 lines
181KB

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