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.

4359 lines
166KB

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