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.

4333 lines
167KB

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