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.

4462 lines
171KB

  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. int parse_extradata);
  879. static av_cold void common_init(H264Context *h)
  880. {
  881. MpegEncContext *const s = &h->s;
  882. s->width = s->avctx->width;
  883. s->height = s->avctx->height;
  884. s->codec_id = s->avctx->codec->id;
  885. s->avctx->bits_per_raw_sample = 8;
  886. h->cur_chroma_format_idc = 1;
  887. ff_h264dsp_init(&h->h264dsp,
  888. s->avctx->bits_per_raw_sample, h->cur_chroma_format_idc);
  889. ff_h264_pred_init(&h->hpc, s->codec_id,
  890. s->avctx->bits_per_raw_sample, h->cur_chroma_format_idc);
  891. h->dequant_coeff_pps = -1;
  892. s->unrestricted_mv = 1;
  893. s->dsp.dct_bits = 16;
  894. /* needed so that IDCT permutation is known early */
  895. ff_dsputil_init(&s->dsp, s->avctx);
  896. memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));
  897. memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));
  898. }
  899. int ff_h264_decode_extradata(H264Context *h, const uint8_t *buf, int size)
  900. {
  901. AVCodecContext *avctx = h->s.avctx;
  902. if (!buf || size <= 0)
  903. return -1;
  904. if (buf[0] == 1) {
  905. int i, cnt, nalsize;
  906. const unsigned char *p = buf;
  907. h->is_avc = 1;
  908. if (size < 7) {
  909. av_log(avctx, AV_LOG_ERROR, "avcC too short\n");
  910. return -1;
  911. }
  912. /* sps and pps in the avcC always have length coded with 2 bytes,
  913. * so put a fake nal_length_size = 2 while parsing them */
  914. h->nal_length_size = 2;
  915. // Decode sps from avcC
  916. cnt = *(p + 5) & 0x1f; // Number of sps
  917. p += 6;
  918. for (i = 0; i < cnt; i++) {
  919. nalsize = AV_RB16(p) + 2;
  920. if(nalsize > size - (p-buf))
  921. return -1;
  922. if (decode_nal_units(h, p, nalsize, 1) < 0) {
  923. av_log(avctx, AV_LOG_ERROR,
  924. "Decoding sps %d from avcC failed\n", i);
  925. return -1;
  926. }
  927. p += nalsize;
  928. }
  929. // Decode pps from avcC
  930. cnt = *(p++); // Number of pps
  931. for (i = 0; i < cnt; i++) {
  932. nalsize = AV_RB16(p) + 2;
  933. if(nalsize > size - (p-buf))
  934. return -1;
  935. if (decode_nal_units(h, p, nalsize, 1) < 0) {
  936. av_log(avctx, AV_LOG_ERROR,
  937. "Decoding pps %d from avcC failed\n", i);
  938. return -1;
  939. }
  940. p += nalsize;
  941. }
  942. // Now store right nal length size, that will be used to parse all other nals
  943. h->nal_length_size = (buf[4] & 0x03) + 1;
  944. } else {
  945. h->is_avc = 0;
  946. if (decode_nal_units(h, buf, size, 1) < 0)
  947. return -1;
  948. }
  949. return size;
  950. }
  951. av_cold int ff_h264_decode_init(AVCodecContext *avctx)
  952. {
  953. H264Context *h = avctx->priv_data;
  954. MpegEncContext *const s = &h->s;
  955. int i;
  956. ff_MPV_decode_defaults(s);
  957. s->avctx = avctx;
  958. common_init(h);
  959. s->out_format = FMT_H264;
  960. s->workaround_bugs = avctx->workaround_bugs;
  961. /* set defaults */
  962. // s->decode_mb = ff_h263_decode_mb;
  963. s->quarter_sample = 1;
  964. if (!avctx->has_b_frames)
  965. s->low_delay = 1;
  966. avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
  967. ff_h264_decode_init_vlc();
  968. h->pixel_shift = 0;
  969. h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;
  970. h->thread_context[0] = h;
  971. h->outputed_poc = h->next_outputed_poc = INT_MIN;
  972. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  973. h->last_pocs[i] = INT_MIN;
  974. h->prev_poc_msb = 1 << 16;
  975. h->prev_frame_num = -1;
  976. h->x264_build = -1;
  977. ff_h264_reset_sei(h);
  978. if (avctx->codec_id == AV_CODEC_ID_H264) {
  979. if (avctx->ticks_per_frame == 1) {
  980. if(s->avctx->time_base.den < INT_MAX/2) {
  981. s->avctx->time_base.den *= 2;
  982. } else
  983. s->avctx->time_base.num /= 2;
  984. }
  985. avctx->ticks_per_frame = 2;
  986. }
  987. if (avctx->extradata_size > 0 && avctx->extradata &&
  988. ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size) < 0) {
  989. ff_h264_free_context(h);
  990. return -1;
  991. }
  992. if (h->sps.bitstream_restriction_flag &&
  993. s->avctx->has_b_frames < h->sps.num_reorder_frames) {
  994. s->avctx->has_b_frames = h->sps.num_reorder_frames;
  995. s->low_delay = 0;
  996. }
  997. ff_init_cabac_states();
  998. return 0;
  999. }
  1000. #define IN_RANGE(a, b, size) (((a) >= (b)) && ((a) < ((b) + (size))))
  1001. static void copy_picture_range(Picture **to, Picture **from, int count,
  1002. MpegEncContext *new_base,
  1003. MpegEncContext *old_base)
  1004. {
  1005. int i;
  1006. for (i = 0; i < count; i++) {
  1007. assert((IN_RANGE(from[i], old_base, sizeof(*old_base)) ||
  1008. IN_RANGE(from[i], old_base->picture,
  1009. sizeof(Picture) * old_base->picture_count) ||
  1010. !from[i]));
  1011. to[i] = REBASE_PICTURE(from[i], new_base, old_base);
  1012. }
  1013. }
  1014. static void copy_parameter_set(void **to, void **from, int count, int size)
  1015. {
  1016. int i;
  1017. for (i = 0; i < count; i++) {
  1018. if (to[i] && !from[i])
  1019. av_freep(&to[i]);
  1020. else if (from[i] && !to[i])
  1021. to[i] = av_malloc(size);
  1022. if (from[i])
  1023. memcpy(to[i], from[i], size);
  1024. }
  1025. }
  1026. static int decode_init_thread_copy(AVCodecContext *avctx)
  1027. {
  1028. H264Context *h = avctx->priv_data;
  1029. if (!avctx->internal->is_copy)
  1030. return 0;
  1031. memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
  1032. memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
  1033. h->s.context_initialized = 0;
  1034. return 0;
  1035. }
  1036. #define copy_fields(to, from, start_field, end_field) \
  1037. memcpy(&to->start_field, &from->start_field, \
  1038. (char *)&to->end_field - (char *)&to->start_field)
  1039. static int h264_slice_header_init(H264Context *, int);
  1040. static int h264_set_parameter_from_sps(H264Context *h);
  1041. static int decode_update_thread_context(AVCodecContext *dst,
  1042. const AVCodecContext *src)
  1043. {
  1044. H264Context *h = dst->priv_data, *h1 = src->priv_data;
  1045. MpegEncContext *const s = &h->s, *const s1 = &h1->s;
  1046. int inited = s->context_initialized, err;
  1047. int i;
  1048. if (dst == src)
  1049. return 0;
  1050. if (inited &&
  1051. (s->width != s1->width ||
  1052. s->height != s1->height ||
  1053. s->mb_width != s1->mb_width ||
  1054. s->mb_height != s1->mb_height ||
  1055. h->sps.bit_depth_luma != h1->sps.bit_depth_luma ||
  1056. h->sps.chroma_format_idc != h1->sps.chroma_format_idc ||
  1057. h->sps.colorspace != h1->sps.colorspace)) {
  1058. av_freep(&h->bipred_scratchpad);
  1059. s->width = s1->width;
  1060. s->height = s1->height;
  1061. s->mb_height = s1->mb_height;
  1062. h->b_stride = h1->b_stride;
  1063. // SPS/PPS
  1064. copy_parameter_set((void **)h->sps_buffers, (void **)h1->sps_buffers,
  1065. MAX_SPS_COUNT, sizeof(SPS));
  1066. h->sps = h1->sps;
  1067. copy_parameter_set((void **)h->pps_buffers, (void **)h1->pps_buffers,
  1068. MAX_PPS_COUNT, sizeof(PPS));
  1069. h->pps = h1->pps;
  1070. if ((err = h264_slice_header_init(h, 1)) < 0) {
  1071. av_log(h->s.avctx, AV_LOG_ERROR, "h264_slice_header_init() failed");
  1072. return err;
  1073. }
  1074. h->context_reinitialized = 1;
  1075. /* update linesize on resize for h264. The h264 decoder doesn't
  1076. * necessarily call ff_MPV_frame_start in the new thread */
  1077. s->linesize = s1->linesize;
  1078. s->uvlinesize = s1->uvlinesize;
  1079. /* copy block_offset since frame_start may not be called */
  1080. memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));
  1081. h264_set_parameter_from_sps(h);
  1082. }
  1083. err = ff_mpeg_update_thread_context(dst, src);
  1084. if (err)
  1085. return err;
  1086. if (!inited) {
  1087. for (i = 0; i < MAX_SPS_COUNT; i++)
  1088. av_freep(h->sps_buffers + i);
  1089. for (i = 0; i < MAX_PPS_COUNT; i++)
  1090. av_freep(h->pps_buffers + i);
  1091. // copy all fields after MpegEnc
  1092. memcpy(&h->s + 1, &h1->s + 1,
  1093. sizeof(H264Context) - sizeof(MpegEncContext));
  1094. memset(h->sps_buffers, 0, sizeof(h->sps_buffers));
  1095. memset(h->pps_buffers, 0, sizeof(h->pps_buffers));
  1096. if (s1->context_initialized) {
  1097. if (ff_h264_alloc_tables(h) < 0) {
  1098. av_log(dst, AV_LOG_ERROR, "Could not allocate memory for h264\n");
  1099. return AVERROR(ENOMEM);
  1100. }
  1101. context_init(h);
  1102. }
  1103. for (i = 0; i < 2; i++) {
  1104. h->rbsp_buffer[i] = NULL;
  1105. h->rbsp_buffer_size[i] = 0;
  1106. }
  1107. h->bipred_scratchpad = NULL;
  1108. h->thread_context[0] = h;
  1109. s->dsp.clear_blocks(h->mb);
  1110. s->dsp.clear_blocks(h->mb + (24 * 16 << h->pixel_shift));
  1111. }
  1112. /* frame_start may not be called for the next thread (if it's decoding
  1113. * a bottom field) so this has to be allocated here */
  1114. if (!h->bipred_scratchpad && s->linesize)
  1115. h->bipred_scratchpad = av_malloc(16 * 6 * s->linesize);
  1116. // extradata/NAL handling
  1117. h->is_avc = h1->is_avc;
  1118. // SPS/PPS
  1119. copy_parameter_set((void **)h->sps_buffers, (void **)h1->sps_buffers,
  1120. MAX_SPS_COUNT, sizeof(SPS));
  1121. h->sps = h1->sps;
  1122. copy_parameter_set((void **)h->pps_buffers, (void **)h1->pps_buffers,
  1123. MAX_PPS_COUNT, sizeof(PPS));
  1124. h->pps = h1->pps;
  1125. // Dequantization matrices
  1126. // FIXME these are big - can they be only copied when PPS changes?
  1127. copy_fields(h, h1, dequant4_buffer, dequant4_coeff);
  1128. for (i = 0; i < 6; i++)
  1129. h->dequant4_coeff[i] = h->dequant4_buffer[0] +
  1130. (h1->dequant4_coeff[i] - h1->dequant4_buffer[0]);
  1131. for (i = 0; i < 6; i++)
  1132. h->dequant8_coeff[i] = h->dequant8_buffer[0] +
  1133. (h1->dequant8_coeff[i] - h1->dequant8_buffer[0]);
  1134. h->dequant_coeff_pps = h1->dequant_coeff_pps;
  1135. // POC timing
  1136. copy_fields(h, h1, poc_lsb, redundant_pic_count);
  1137. // reference lists
  1138. copy_fields(h, h1, ref_count, list_count);
  1139. copy_fields(h, h1, ref_list, intra_gb);
  1140. copy_fields(h, h1, short_ref, cabac_init_idc);
  1141. copy_picture_range(h->short_ref, h1->short_ref, 32, s, s1);
  1142. copy_picture_range(h->long_ref, h1->long_ref, 32, s, s1);
  1143. copy_picture_range(h->delayed_pic, h1->delayed_pic,
  1144. MAX_DELAYED_PIC_COUNT + 2, s, s1);
  1145. h->last_slice_type = h1->last_slice_type;
  1146. h->sync = h1->sync;
  1147. if (!s->current_picture_ptr)
  1148. return 0;
  1149. if (!s->droppable) {
  1150. err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
  1151. h->prev_poc_msb = h->poc_msb;
  1152. h->prev_poc_lsb = h->poc_lsb;
  1153. }
  1154. h->prev_frame_num_offset = h->frame_num_offset;
  1155. h->prev_frame_num = h->frame_num;
  1156. h->outputed_poc = h->next_outputed_poc;
  1157. return err;
  1158. }
  1159. int ff_h264_frame_start(H264Context *h)
  1160. {
  1161. MpegEncContext *const s = &h->s;
  1162. int i;
  1163. const int pixel_shift = h->pixel_shift;
  1164. if (ff_MPV_frame_start(s, s->avctx) < 0)
  1165. return -1;
  1166. ff_er_frame_start(s);
  1167. /*
  1168. * ff_MPV_frame_start uses pict_type to derive key_frame.
  1169. * This is incorrect for H.264; IDR markings must be used.
  1170. * Zero here; IDR markings per slice in frame or fields are ORed in later.
  1171. * See decode_nal_units().
  1172. */
  1173. s->current_picture_ptr->f.key_frame = 0;
  1174. s->current_picture_ptr->sync = 0;
  1175. s->current_picture_ptr->mmco_reset = 0;
  1176. assert(s->linesize && s->uvlinesize);
  1177. for (i = 0; i < 16; i++) {
  1178. h->block_offset[i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * s->linesize * ((scan8[i] - scan8[0]) >> 3);
  1179. h->block_offset[48 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * s->linesize * ((scan8[i] - scan8[0]) >> 3);
  1180. }
  1181. for (i = 0; i < 16; i++) {
  1182. h->block_offset[16 + i] =
  1183. h->block_offset[32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 4 * s->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
  1184. h->block_offset[48 + 16 + i] =
  1185. h->block_offset[48 + 32 + i] = (4 * ((scan8[i] - scan8[0]) & 7) << pixel_shift) + 8 * s->uvlinesize * ((scan8[i] - scan8[0]) >> 3);
  1186. }
  1187. /* can't be in alloc_tables because linesize isn't known there.
  1188. * FIXME: redo bipred weight to not require extra buffer? */
  1189. for (i = 0; i < s->slice_context_count; i++)
  1190. if (h->thread_context[i] && !h->thread_context[i]->bipred_scratchpad)
  1191. h->thread_context[i]->bipred_scratchpad = av_malloc(16 * 6 * s->linesize);
  1192. /* Some macroblocks can be accessed before they're available in case
  1193. * of lost slices, MBAFF or threading. */
  1194. memset(h->slice_table, -1,
  1195. (s->mb_height * s->mb_stride - 1) * sizeof(*h->slice_table));
  1196. // s->decode = (s->flags & CODEC_FLAG_PSNR) || !s->encoding ||
  1197. // s->current_picture.f.reference /* || h->contains_intra */ || 1;
  1198. /* We mark the current picture as non-reference after allocating it, so
  1199. * that if we break out due to an error it can be released automatically
  1200. * in the next ff_MPV_frame_start().
  1201. * SVQ3 as well as most other codecs have only last/next/current and thus
  1202. * get released even with set reference, besides SVQ3 and others do not
  1203. * mark frames as reference later "naturally". */
  1204. if (s->codec_id != AV_CODEC_ID_SVQ3)
  1205. s->current_picture_ptr->f.reference = 0;
  1206. s->current_picture_ptr->field_poc[0] =
  1207. s->current_picture_ptr->field_poc[1] = INT_MAX;
  1208. h->next_output_pic = NULL;
  1209. assert(s->current_picture_ptr->long_ref == 0);
  1210. return 0;
  1211. }
  1212. /**
  1213. * Run setup operations that must be run after slice header decoding.
  1214. * This includes finding the next displayed frame.
  1215. *
  1216. * @param h h264 master context
  1217. * @param setup_finished enough NALs have been read that we can call
  1218. * ff_thread_finish_setup()
  1219. */
  1220. static void decode_postinit(H264Context *h, int setup_finished)
  1221. {
  1222. MpegEncContext *const s = &h->s;
  1223. Picture *out = s->current_picture_ptr;
  1224. Picture *cur = s->current_picture_ptr;
  1225. int i, pics, out_of_order, out_idx;
  1226. s->current_picture_ptr->f.qscale_type = FF_QSCALE_TYPE_H264;
  1227. s->current_picture_ptr->f.pict_type = s->pict_type;
  1228. if (h->next_output_pic)
  1229. return;
  1230. if (cur->field_poc[0] == INT_MAX || cur->field_poc[1] == INT_MAX) {
  1231. /* FIXME: if we have two PAFF fields in one packet, we can't start
  1232. * the next thread here. If we have one field per packet, we can.
  1233. * The check in decode_nal_units() is not good enough to find this
  1234. * yet, so we assume the worst for now. */
  1235. // if (setup_finished)
  1236. // ff_thread_finish_setup(s->avctx);
  1237. return;
  1238. }
  1239. cur->f.interlaced_frame = 0;
  1240. cur->f.repeat_pict = 0;
  1241. /* Signal interlacing information externally. */
  1242. /* Prioritize picture timing SEI information over used
  1243. * decoding process if it exists. */
  1244. if (h->sps.pic_struct_present_flag) {
  1245. switch (h->sei_pic_struct) {
  1246. case SEI_PIC_STRUCT_FRAME:
  1247. break;
  1248. case SEI_PIC_STRUCT_TOP_FIELD:
  1249. case SEI_PIC_STRUCT_BOTTOM_FIELD:
  1250. cur->f.interlaced_frame = 1;
  1251. break;
  1252. case SEI_PIC_STRUCT_TOP_BOTTOM:
  1253. case SEI_PIC_STRUCT_BOTTOM_TOP:
  1254. if (FIELD_OR_MBAFF_PICTURE)
  1255. cur->f.interlaced_frame = 1;
  1256. else
  1257. // try to flag soft telecine progressive
  1258. cur->f.interlaced_frame = h->prev_interlaced_frame;
  1259. break;
  1260. case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:
  1261. case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:
  1262. /* Signal the possibility of telecined film externally
  1263. * (pic_struct 5,6). From these hints, let the applications
  1264. * decide if they apply deinterlacing. */
  1265. cur->f.repeat_pict = 1;
  1266. break;
  1267. case SEI_PIC_STRUCT_FRAME_DOUBLING:
  1268. // Force progressive here, doubling interlaced frame is a bad idea.
  1269. cur->f.repeat_pict = 2;
  1270. break;
  1271. case SEI_PIC_STRUCT_FRAME_TRIPLING:
  1272. cur->f.repeat_pict = 4;
  1273. break;
  1274. }
  1275. if ((h->sei_ct_type & 3) &&
  1276. h->sei_pic_struct <= SEI_PIC_STRUCT_BOTTOM_TOP)
  1277. cur->f.interlaced_frame = (h->sei_ct_type & (1 << 1)) != 0;
  1278. } else {
  1279. /* Derive interlacing flag from used decoding process. */
  1280. cur->f.interlaced_frame = FIELD_OR_MBAFF_PICTURE;
  1281. }
  1282. h->prev_interlaced_frame = cur->f.interlaced_frame;
  1283. if (cur->field_poc[0] != cur->field_poc[1]) {
  1284. /* Derive top_field_first from field pocs. */
  1285. cur->f.top_field_first = cur->field_poc[0] < cur->field_poc[1];
  1286. } else {
  1287. if (cur->f.interlaced_frame || h->sps.pic_struct_present_flag) {
  1288. /* Use picture timing SEI information. Even if it is a
  1289. * information of a past frame, better than nothing. */
  1290. if (h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM ||
  1291. h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)
  1292. cur->f.top_field_first = 1;
  1293. else
  1294. cur->f.top_field_first = 0;
  1295. } else {
  1296. /* Most likely progressive */
  1297. cur->f.top_field_first = 0;
  1298. }
  1299. }
  1300. cur->mmco_reset = h->mmco_reset;
  1301. h->mmco_reset = 0;
  1302. // FIXME do something with unavailable reference frames
  1303. /* Sort B-frames into display order */
  1304. if (h->sps.bitstream_restriction_flag &&
  1305. s->avctx->has_b_frames < h->sps.num_reorder_frames) {
  1306. s->avctx->has_b_frames = h->sps.num_reorder_frames;
  1307. s->low_delay = 0;
  1308. }
  1309. if (s->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT &&
  1310. !h->sps.bitstream_restriction_flag) {
  1311. s->avctx->has_b_frames = MAX_DELAYED_PIC_COUNT - 1;
  1312. s->low_delay = 0;
  1313. }
  1314. for (i = 0; 1; i++) {
  1315. if(i == MAX_DELAYED_PIC_COUNT || cur->poc < h->last_pocs[i]){
  1316. if(i)
  1317. h->last_pocs[i-1] = cur->poc;
  1318. break;
  1319. } else if(i) {
  1320. h->last_pocs[i-1]= h->last_pocs[i];
  1321. }
  1322. }
  1323. out_of_order = MAX_DELAYED_PIC_COUNT - i;
  1324. if( cur->f.pict_type == AV_PICTURE_TYPE_B
  1325. || (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))
  1326. out_of_order = FFMAX(out_of_order, 1);
  1327. if(s->avctx->has_b_frames < out_of_order && !h->sps.bitstream_restriction_flag){
  1328. av_log(s->avctx, AV_LOG_VERBOSE, "Increasing reorder buffer to %d\n", out_of_order);
  1329. s->avctx->has_b_frames = out_of_order;
  1330. s->low_delay = 0;
  1331. }
  1332. pics = 0;
  1333. while (h->delayed_pic[pics])
  1334. pics++;
  1335. av_assert0(pics <= MAX_DELAYED_PIC_COUNT);
  1336. h->delayed_pic[pics++] = cur;
  1337. if (cur->f.reference == 0)
  1338. cur->f.reference = DELAYED_PIC_REF;
  1339. out = h->delayed_pic[0];
  1340. out_idx = 0;
  1341. for (i = 1; h->delayed_pic[i] &&
  1342. !h->delayed_pic[i]->f.key_frame &&
  1343. !h->delayed_pic[i]->mmco_reset;
  1344. i++)
  1345. if (h->delayed_pic[i]->poc < out->poc) {
  1346. out = h->delayed_pic[i];
  1347. out_idx = i;
  1348. }
  1349. if (s->avctx->has_b_frames == 0 &&
  1350. (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset))
  1351. h->next_outputed_poc = INT_MIN;
  1352. out_of_order = out->poc < h->next_outputed_poc;
  1353. if (out_of_order || pics > s->avctx->has_b_frames) {
  1354. out->f.reference &= ~DELAYED_PIC_REF;
  1355. // for frame threading, the owner must be the second field's thread or
  1356. // else the first thread can release the picture and reuse it unsafely
  1357. out->owner2 = s;
  1358. for (i = out_idx; h->delayed_pic[i]; i++)
  1359. h->delayed_pic[i] = h->delayed_pic[i + 1];
  1360. }
  1361. if (!out_of_order && pics > s->avctx->has_b_frames) {
  1362. h->next_output_pic = out;
  1363. if (out_idx == 0 && h->delayed_pic[0] && (h->delayed_pic[0]->f.key_frame || h->delayed_pic[0]->mmco_reset)) {
  1364. h->next_outputed_poc = INT_MIN;
  1365. } else
  1366. h->next_outputed_poc = out->poc;
  1367. } else {
  1368. av_log(s->avctx, AV_LOG_DEBUG, "no picture %s\n", out_of_order ? "ooo" : "");
  1369. }
  1370. if (h->next_output_pic && h->next_output_pic->sync) {
  1371. h->sync |= 2;
  1372. }
  1373. if (setup_finished)
  1374. ff_thread_finish_setup(s->avctx);
  1375. }
  1376. static av_always_inline void backup_mb_border(H264Context *h, uint8_t *src_y,
  1377. uint8_t *src_cb, uint8_t *src_cr,
  1378. int linesize, int uvlinesize,
  1379. int simple)
  1380. {
  1381. MpegEncContext *const s = &h->s;
  1382. uint8_t *top_border;
  1383. int top_idx = 1;
  1384. const int pixel_shift = h->pixel_shift;
  1385. int chroma444 = CHROMA444;
  1386. int chroma422 = CHROMA422;
  1387. src_y -= linesize;
  1388. src_cb -= uvlinesize;
  1389. src_cr -= uvlinesize;
  1390. if (!simple && FRAME_MBAFF) {
  1391. if (s->mb_y & 1) {
  1392. if (!MB_MBAFF) {
  1393. top_border = h->top_borders[0][s->mb_x];
  1394. AV_COPY128(top_border, src_y + 15 * linesize);
  1395. if (pixel_shift)
  1396. AV_COPY128(top_border + 16, src_y + 15 * linesize + 16);
  1397. if (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
  1398. if (chroma444) {
  1399. if (pixel_shift) {
  1400. AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
  1401. AV_COPY128(top_border + 48, src_cb + 15 * uvlinesize + 16);
  1402. AV_COPY128(top_border + 64, src_cr + 15 * uvlinesize);
  1403. AV_COPY128(top_border + 80, src_cr + 15 * uvlinesize + 16);
  1404. } else {
  1405. AV_COPY128(top_border + 16, src_cb + 15 * uvlinesize);
  1406. AV_COPY128(top_border + 32, src_cr + 15 * uvlinesize);
  1407. }
  1408. } else if (chroma422) {
  1409. if (pixel_shift) {
  1410. AV_COPY128(top_border + 32, src_cb + 15 * uvlinesize);
  1411. AV_COPY128(top_border + 48, src_cr + 15 * uvlinesize);
  1412. } else {
  1413. AV_COPY64(top_border + 16, src_cb + 15 * uvlinesize);
  1414. AV_COPY64(top_border + 24, src_cr + 15 * uvlinesize);
  1415. }
  1416. } else {
  1417. if (pixel_shift) {
  1418. AV_COPY128(top_border + 32, src_cb + 7 * uvlinesize);
  1419. AV_COPY128(top_border + 48, src_cr + 7 * uvlinesize);
  1420. } else {
  1421. AV_COPY64(top_border + 16, src_cb + 7 * uvlinesize);
  1422. AV_COPY64(top_border + 24, src_cr + 7 * uvlinesize);
  1423. }
  1424. }
  1425. }
  1426. }
  1427. } else if (MB_MBAFF) {
  1428. top_idx = 0;
  1429. } else
  1430. return;
  1431. }
  1432. top_border = h->top_borders[top_idx][s->mb_x];
  1433. /* There are two lines saved, the line above the top macroblock
  1434. * of a pair, and the line above the bottom macroblock. */
  1435. AV_COPY128(top_border, src_y + 16 * linesize);
  1436. if (pixel_shift)
  1437. AV_COPY128(top_border + 16, src_y + 16 * linesize + 16);
  1438. if (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
  1439. if (chroma444) {
  1440. if (pixel_shift) {
  1441. AV_COPY128(top_border + 32, src_cb + 16 * linesize);
  1442. AV_COPY128(top_border + 48, src_cb + 16 * linesize + 16);
  1443. AV_COPY128(top_border + 64, src_cr + 16 * linesize);
  1444. AV_COPY128(top_border + 80, src_cr + 16 * linesize + 16);
  1445. } else {
  1446. AV_COPY128(top_border + 16, src_cb + 16 * linesize);
  1447. AV_COPY128(top_border + 32, src_cr + 16 * linesize);
  1448. }
  1449. } else if (chroma422) {
  1450. if (pixel_shift) {
  1451. AV_COPY128(top_border + 32, src_cb + 16 * uvlinesize);
  1452. AV_COPY128(top_border + 48, src_cr + 16 * uvlinesize);
  1453. } else {
  1454. AV_COPY64(top_border + 16, src_cb + 16 * uvlinesize);
  1455. AV_COPY64(top_border + 24, src_cr + 16 * uvlinesize);
  1456. }
  1457. } else {
  1458. if (pixel_shift) {
  1459. AV_COPY128(top_border + 32, src_cb + 8 * uvlinesize);
  1460. AV_COPY128(top_border + 48, src_cr + 8 * uvlinesize);
  1461. } else {
  1462. AV_COPY64(top_border + 16, src_cb + 8 * uvlinesize);
  1463. AV_COPY64(top_border + 24, src_cr + 8 * uvlinesize);
  1464. }
  1465. }
  1466. }
  1467. }
  1468. static av_always_inline void xchg_mb_border(H264Context *h, uint8_t *src_y,
  1469. uint8_t *src_cb, uint8_t *src_cr,
  1470. int linesize, int uvlinesize,
  1471. int xchg, int chroma444,
  1472. int simple, int pixel_shift)
  1473. {
  1474. MpegEncContext *const s = &h->s;
  1475. int deblock_topleft;
  1476. int deblock_top;
  1477. int top_idx = 1;
  1478. uint8_t *top_border_m1;
  1479. uint8_t *top_border;
  1480. if (!simple && FRAME_MBAFF) {
  1481. if (s->mb_y & 1) {
  1482. if (!MB_MBAFF)
  1483. return;
  1484. } else {
  1485. top_idx = MB_MBAFF ? 0 : 1;
  1486. }
  1487. }
  1488. if (h->deblocking_filter == 2) {
  1489. deblock_topleft = h->slice_table[h->mb_xy - 1 - s->mb_stride] == h->slice_num;
  1490. deblock_top = h->top_type;
  1491. } else {
  1492. deblock_topleft = (s->mb_x > 0);
  1493. deblock_top = (s->mb_y > !!MB_FIELD);
  1494. }
  1495. src_y -= linesize + 1 + pixel_shift;
  1496. src_cb -= uvlinesize + 1 + pixel_shift;
  1497. src_cr -= uvlinesize + 1 + pixel_shift;
  1498. top_border_m1 = h->top_borders[top_idx][s->mb_x - 1];
  1499. top_border = h->top_borders[top_idx][s->mb_x];
  1500. #define XCHG(a, b, xchg) \
  1501. if (pixel_shift) { \
  1502. if (xchg) { \
  1503. AV_SWAP64(b + 0, a + 0); \
  1504. AV_SWAP64(b + 8, a + 8); \
  1505. } else { \
  1506. AV_COPY128(b, a); \
  1507. } \
  1508. } else if (xchg) \
  1509. AV_SWAP64(b, a); \
  1510. else \
  1511. AV_COPY64(b, a);
  1512. if (deblock_top) {
  1513. if (deblock_topleft) {
  1514. XCHG(top_border_m1 + (8 << pixel_shift),
  1515. src_y - (7 << pixel_shift), 1);
  1516. }
  1517. XCHG(top_border + (0 << pixel_shift), src_y + (1 << pixel_shift), xchg);
  1518. XCHG(top_border + (8 << pixel_shift), src_y + (9 << pixel_shift), 1);
  1519. if (s->mb_x + 1 < s->mb_width) {
  1520. XCHG(h->top_borders[top_idx][s->mb_x + 1],
  1521. src_y + (17 << pixel_shift), 1);
  1522. }
  1523. }
  1524. if (simple || !CONFIG_GRAY || !(s->flags & CODEC_FLAG_GRAY)) {
  1525. if (chroma444) {
  1526. if (deblock_topleft) {
  1527. XCHG(top_border_m1 + (24 << pixel_shift), src_cb - (7 << pixel_shift), 1);
  1528. XCHG(top_border_m1 + (40 << pixel_shift), src_cr - (7 << pixel_shift), 1);
  1529. }
  1530. XCHG(top_border + (16 << pixel_shift), src_cb + (1 << pixel_shift), xchg);
  1531. XCHG(top_border + (24 << pixel_shift), src_cb + (9 << pixel_shift), 1);
  1532. XCHG(top_border + (32 << pixel_shift), src_cr + (1 << pixel_shift), xchg);
  1533. XCHG(top_border + (40 << pixel_shift), src_cr + (9 << pixel_shift), 1);
  1534. if (s->mb_x + 1 < s->mb_width) {
  1535. XCHG(h->top_borders[top_idx][s->mb_x + 1] + (16 << pixel_shift), src_cb + (17 << pixel_shift), 1);
  1536. XCHG(h->top_borders[top_idx][s->mb_x + 1] + (32 << pixel_shift), src_cr + (17 << pixel_shift), 1);
  1537. }
  1538. } else {
  1539. if (deblock_top) {
  1540. if (deblock_topleft) {
  1541. XCHG(top_border_m1 + (16 << pixel_shift), src_cb - (7 << pixel_shift), 1);
  1542. XCHG(top_border_m1 + (24 << pixel_shift), src_cr - (7 << pixel_shift), 1);
  1543. }
  1544. XCHG(top_border + (16 << pixel_shift), src_cb + 1 + pixel_shift, 1);
  1545. XCHG(top_border + (24 << pixel_shift), src_cr + 1 + pixel_shift, 1);
  1546. }
  1547. }
  1548. }
  1549. }
  1550. static av_always_inline int dctcoef_get(DCTELEM *mb, int high_bit_depth,
  1551. int index)
  1552. {
  1553. if (high_bit_depth) {
  1554. return AV_RN32A(((int32_t *)mb) + index);
  1555. } else
  1556. return AV_RN16A(mb + index);
  1557. }
  1558. static av_always_inline void dctcoef_set(DCTELEM *mb, int high_bit_depth,
  1559. int index, int value)
  1560. {
  1561. if (high_bit_depth) {
  1562. AV_WN32A(((int32_t *)mb) + index, value);
  1563. } else
  1564. AV_WN16A(mb + index, value);
  1565. }
  1566. static av_always_inline void hl_decode_mb_predict_luma(H264Context *h,
  1567. int mb_type, int is_h264,
  1568. int simple,
  1569. int transform_bypass,
  1570. int pixel_shift,
  1571. int *block_offset,
  1572. int linesize,
  1573. uint8_t *dest_y, int p)
  1574. {
  1575. MpegEncContext *const s = &h->s;
  1576. void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
  1577. void (*idct_dc_add)(uint8_t *dst, DCTELEM *block, int stride);
  1578. int i;
  1579. int qscale = p == 0 ? s->qscale : h->chroma_qp[p - 1];
  1580. block_offset += 16 * p;
  1581. if (IS_INTRA4x4(mb_type)) {
  1582. if (simple || !s->encoding) {
  1583. if (IS_8x8DCT(mb_type)) {
  1584. if (transform_bypass) {
  1585. idct_dc_add =
  1586. idct_add = s->dsp.add_pixels8;
  1587. } else {
  1588. idct_dc_add = h->h264dsp.h264_idct8_dc_add;
  1589. idct_add = h->h264dsp.h264_idct8_add;
  1590. }
  1591. for (i = 0; i < 16; i += 4) {
  1592. uint8_t *const ptr = dest_y + block_offset[i];
  1593. const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
  1594. if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
  1595. h->hpc.pred8x8l_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  1596. } else {
  1597. const int nnz = h->non_zero_count_cache[scan8[i + p * 16]];
  1598. h->hpc.pred8x8l[dir](ptr, (h->topleft_samples_available << i) & 0x8000,
  1599. (h->topright_samples_available << i) & 0x4000, linesize);
  1600. if (nnz) {
  1601. if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
  1602. idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  1603. else
  1604. idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  1605. }
  1606. }
  1607. }
  1608. } else {
  1609. if (transform_bypass) {
  1610. idct_dc_add =
  1611. idct_add = s->dsp.add_pixels4;
  1612. } else {
  1613. idct_dc_add = h->h264dsp.h264_idct_dc_add;
  1614. idct_add = h->h264dsp.h264_idct_add;
  1615. }
  1616. for (i = 0; i < 16; i++) {
  1617. uint8_t *const ptr = dest_y + block_offset[i];
  1618. const int dir = h->intra4x4_pred_mode_cache[scan8[i]];
  1619. if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {
  1620. h->hpc.pred4x4_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  1621. } else {
  1622. uint8_t *topright;
  1623. int nnz, tr;
  1624. uint64_t tr_high;
  1625. if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {
  1626. const int topright_avail = (h->topright_samples_available << i) & 0x8000;
  1627. av_assert2(s->mb_y || linesize <= block_offset[i]);
  1628. if (!topright_avail) {
  1629. if (pixel_shift) {
  1630. tr_high = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;
  1631. topright = (uint8_t *)&tr_high;
  1632. } else {
  1633. tr = ptr[3 - linesize] * 0x01010101u;
  1634. topright = (uint8_t *)&tr;
  1635. }
  1636. } else
  1637. topright = ptr + (4 << pixel_shift) - linesize;
  1638. } else
  1639. topright = NULL;
  1640. h->hpc.pred4x4[dir](ptr, topright, linesize);
  1641. nnz = h->non_zero_count_cache[scan8[i + p * 16]];
  1642. if (nnz) {
  1643. if (is_h264) {
  1644. if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
  1645. idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  1646. else
  1647. idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);
  1648. } else if (CONFIG_SVQ3_DECODER)
  1649. ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize, qscale, 0);
  1650. }
  1651. }
  1652. }
  1653. }
  1654. }
  1655. } else {
  1656. h->hpc.pred16x16[h->intra16x16_pred_mode](dest_y, linesize);
  1657. if (is_h264) {
  1658. if (h->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {
  1659. if (!transform_bypass)
  1660. h->h264dsp.h264_luma_dc_dequant_idct(h->mb + (p * 256 << pixel_shift),
  1661. h->mb_luma_dc[p],
  1662. h->dequant4_coeff[p][qscale][0]);
  1663. else {
  1664. static const uint8_t dc_mapping[16] = {
  1665. 0 * 16, 1 * 16, 4 * 16, 5 * 16,
  1666. 2 * 16, 3 * 16, 6 * 16, 7 * 16,
  1667. 8 * 16, 9 * 16, 12 * 16, 13 * 16,
  1668. 10 * 16, 11 * 16, 14 * 16, 15 * 16 };
  1669. for (i = 0; i < 16; i++)
  1670. dctcoef_set(h->mb + (p * 256 << pixel_shift),
  1671. pixel_shift, dc_mapping[i],
  1672. dctcoef_get(h->mb_luma_dc[p],
  1673. pixel_shift, i));
  1674. }
  1675. }
  1676. } else if (CONFIG_SVQ3_DECODER)
  1677. ff_svq3_luma_dc_dequant_idct_c(h->mb + p * 256,
  1678. h->mb_luma_dc[p], qscale);
  1679. }
  1680. }
  1681. static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type,
  1682. int is_h264, int simple,
  1683. int transform_bypass,
  1684. int pixel_shift,
  1685. int *block_offset,
  1686. int linesize,
  1687. uint8_t *dest_y, int p)
  1688. {
  1689. MpegEncContext *const s = &h->s;
  1690. void (*idct_add)(uint8_t *dst, DCTELEM *block, int stride);
  1691. int i;
  1692. block_offset += 16 * p;
  1693. if (!IS_INTRA4x4(mb_type)) {
  1694. if (is_h264) {
  1695. if (IS_INTRA16x16(mb_type)) {
  1696. if (transform_bypass) {
  1697. if (h->sps.profile_idc == 244 &&
  1698. (h->intra16x16_pred_mode == VERT_PRED8x8 ||
  1699. h->intra16x16_pred_mode == HOR_PRED8x8)) {
  1700. h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset,
  1701. h->mb + (p * 256 << pixel_shift),
  1702. linesize);
  1703. } else {
  1704. for (i = 0; i < 16; i++)
  1705. if (h->non_zero_count_cache[scan8[i + p * 16]] ||
  1706. dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))
  1707. s->dsp.add_pixels4(dest_y + block_offset[i],
  1708. h->mb + (i * 16 + p * 256 << pixel_shift),
  1709. linesize);
  1710. }
  1711. } else {
  1712. h->h264dsp.h264_idct_add16intra(dest_y, block_offset,
  1713. h->mb + (p * 256 << pixel_shift),
  1714. linesize,
  1715. h->non_zero_count_cache + p * 5 * 8);
  1716. }
  1717. } else if (h->cbp & 15) {
  1718. if (transform_bypass) {
  1719. const int di = IS_8x8DCT(mb_type) ? 4 : 1;
  1720. idct_add = IS_8x8DCT(mb_type) ? s->dsp.add_pixels8
  1721. : s->dsp.add_pixels4;
  1722. for (i = 0; i < 16; i += di)
  1723. if (h->non_zero_count_cache[scan8[i + p * 16]])
  1724. idct_add(dest_y + block_offset[i],
  1725. h->mb + (i * 16 + p * 256 << pixel_shift),
  1726. linesize);
  1727. } else {
  1728. if (IS_8x8DCT(mb_type))
  1729. h->h264dsp.h264_idct8_add4(dest_y, block_offset,
  1730. h->mb + (p * 256 << pixel_shift),
  1731. linesize,
  1732. h->non_zero_count_cache + p * 5 * 8);
  1733. else
  1734. h->h264dsp.h264_idct_add16(dest_y, block_offset,
  1735. h->mb + (p * 256 << pixel_shift),
  1736. linesize,
  1737. h->non_zero_count_cache + p * 5 * 8);
  1738. }
  1739. }
  1740. } else if (CONFIG_SVQ3_DECODER) {
  1741. for (i = 0; i < 16; i++)
  1742. if (h->non_zero_count_cache[scan8[i + p * 16]] || h->mb[i * 16 + p * 256]) {
  1743. // FIXME benchmark weird rule, & below
  1744. uint8_t *const ptr = dest_y + block_offset[i];
  1745. ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize,
  1746. s->qscale, IS_INTRA(mb_type) ? 1 : 0);
  1747. }
  1748. }
  1749. }
  1750. }
  1751. #define BITS 8
  1752. #define SIMPLE 1
  1753. #include "h264_mb_template.c"
  1754. #undef BITS
  1755. #define BITS 16
  1756. #include "h264_mb_template.c"
  1757. #undef SIMPLE
  1758. #define SIMPLE 0
  1759. #include "h264_mb_template.c"
  1760. void ff_h264_hl_decode_mb(H264Context *h)
  1761. {
  1762. MpegEncContext *const s = &h->s;
  1763. const int mb_xy = h->mb_xy;
  1764. const int mb_type = s->current_picture.f.mb_type[mb_xy];
  1765. int is_complex = CONFIG_SMALL || h->is_complex || IS_INTRA_PCM(mb_type) || s->qscale == 0;
  1766. if (CHROMA444) {
  1767. if (is_complex || h->pixel_shift)
  1768. hl_decode_mb_444_complex(h);
  1769. else
  1770. hl_decode_mb_444_simple_8(h);
  1771. } else if (is_complex) {
  1772. hl_decode_mb_complex(h);
  1773. } else if (h->pixel_shift) {
  1774. hl_decode_mb_simple_16(h);
  1775. } else
  1776. hl_decode_mb_simple_8(h);
  1777. }
  1778. static int pred_weight_table(H264Context *h)
  1779. {
  1780. MpegEncContext *const s = &h->s;
  1781. int list, i;
  1782. int luma_def, chroma_def;
  1783. h->use_weight = 0;
  1784. h->use_weight_chroma = 0;
  1785. h->luma_log2_weight_denom = get_ue_golomb(&s->gb);
  1786. if (h->sps.chroma_format_idc)
  1787. h->chroma_log2_weight_denom = get_ue_golomb(&s->gb);
  1788. luma_def = 1 << h->luma_log2_weight_denom;
  1789. chroma_def = 1 << h->chroma_log2_weight_denom;
  1790. for (list = 0; list < 2; list++) {
  1791. h->luma_weight_flag[list] = 0;
  1792. h->chroma_weight_flag[list] = 0;
  1793. for (i = 0; i < h->ref_count[list]; i++) {
  1794. int luma_weight_flag, chroma_weight_flag;
  1795. luma_weight_flag = get_bits1(&s->gb);
  1796. if (luma_weight_flag) {
  1797. h->luma_weight[i][list][0] = get_se_golomb(&s->gb);
  1798. h->luma_weight[i][list][1] = get_se_golomb(&s->gb);
  1799. if (h->luma_weight[i][list][0] != luma_def ||
  1800. h->luma_weight[i][list][1] != 0) {
  1801. h->use_weight = 1;
  1802. h->luma_weight_flag[list] = 1;
  1803. }
  1804. } else {
  1805. h->luma_weight[i][list][0] = luma_def;
  1806. h->luma_weight[i][list][1] = 0;
  1807. }
  1808. if (h->sps.chroma_format_idc) {
  1809. chroma_weight_flag = get_bits1(&s->gb);
  1810. if (chroma_weight_flag) {
  1811. int j;
  1812. for (j = 0; j < 2; j++) {
  1813. h->chroma_weight[i][list][j][0] = get_se_golomb(&s->gb);
  1814. h->chroma_weight[i][list][j][1] = get_se_golomb(&s->gb);
  1815. if (h->chroma_weight[i][list][j][0] != chroma_def ||
  1816. h->chroma_weight[i][list][j][1] != 0) {
  1817. h->use_weight_chroma = 1;
  1818. h->chroma_weight_flag[list] = 1;
  1819. }
  1820. }
  1821. } else {
  1822. int j;
  1823. for (j = 0; j < 2; j++) {
  1824. h->chroma_weight[i][list][j][0] = chroma_def;
  1825. h->chroma_weight[i][list][j][1] = 0;
  1826. }
  1827. }
  1828. }
  1829. }
  1830. if (h->slice_type_nos != AV_PICTURE_TYPE_B)
  1831. break;
  1832. }
  1833. h->use_weight = h->use_weight || h->use_weight_chroma;
  1834. return 0;
  1835. }
  1836. /**
  1837. * Initialize implicit_weight table.
  1838. * @param field 0/1 initialize the weight for interlaced MBAFF
  1839. * -1 initializes the rest
  1840. */
  1841. static void implicit_weight_table(H264Context *h, int field)
  1842. {
  1843. MpegEncContext *const s = &h->s;
  1844. int ref0, ref1, i, cur_poc, ref_start, ref_count0, ref_count1;
  1845. for (i = 0; i < 2; i++) {
  1846. h->luma_weight_flag[i] = 0;
  1847. h->chroma_weight_flag[i] = 0;
  1848. }
  1849. if (field < 0) {
  1850. if (s->picture_structure == PICT_FRAME) {
  1851. cur_poc = s->current_picture_ptr->poc;
  1852. } else {
  1853. cur_poc = s->current_picture_ptr->field_poc[s->picture_structure - 1];
  1854. }
  1855. if (h->ref_count[0] == 1 && h->ref_count[1] == 1 && !FRAME_MBAFF &&
  1856. h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2 * cur_poc) {
  1857. h->use_weight = 0;
  1858. h->use_weight_chroma = 0;
  1859. return;
  1860. }
  1861. ref_start = 0;
  1862. ref_count0 = h->ref_count[0];
  1863. ref_count1 = h->ref_count[1];
  1864. } else {
  1865. cur_poc = s->current_picture_ptr->field_poc[field];
  1866. ref_start = 16;
  1867. ref_count0 = 16 + 2 * h->ref_count[0];
  1868. ref_count1 = 16 + 2 * h->ref_count[1];
  1869. }
  1870. h->use_weight = 2;
  1871. h->use_weight_chroma = 2;
  1872. h->luma_log2_weight_denom = 5;
  1873. h->chroma_log2_weight_denom = 5;
  1874. for (ref0 = ref_start; ref0 < ref_count0; ref0++) {
  1875. int poc0 = h->ref_list[0][ref0].poc;
  1876. for (ref1 = ref_start; ref1 < ref_count1; ref1++) {
  1877. int w = 32;
  1878. if (!h->ref_list[0][ref0].long_ref && !h->ref_list[1][ref1].long_ref) {
  1879. int poc1 = h->ref_list[1][ref1].poc;
  1880. int td = av_clip(poc1 - poc0, -128, 127);
  1881. if (td) {
  1882. int tb = av_clip(cur_poc - poc0, -128, 127);
  1883. int tx = (16384 + (FFABS(td) >> 1)) / td;
  1884. int dist_scale_factor = (tb * tx + 32) >> 8;
  1885. if (dist_scale_factor >= -64 && dist_scale_factor <= 128)
  1886. w = 64 - dist_scale_factor;
  1887. }
  1888. }
  1889. if (field < 0) {
  1890. h->implicit_weight[ref0][ref1][0] =
  1891. h->implicit_weight[ref0][ref1][1] = w;
  1892. } else {
  1893. h->implicit_weight[ref0][ref1][field] = w;
  1894. }
  1895. }
  1896. }
  1897. }
  1898. /**
  1899. * instantaneous decoder refresh.
  1900. */
  1901. static void idr(H264Context *h)
  1902. {
  1903. int i;
  1904. ff_h264_remove_all_refs(h);
  1905. h->prev_frame_num = 0;
  1906. h->prev_frame_num_offset = 0;
  1907. h->prev_poc_msb = 1<<16;
  1908. h->prev_poc_lsb = 0;
  1909. for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
  1910. h->last_pocs[i] = INT_MIN;
  1911. }
  1912. /* forget old pics after a seek */
  1913. static void flush_change(H264Context *h)
  1914. {
  1915. h->outputed_poc = h->next_outputed_poc = INT_MIN;
  1916. h->prev_interlaced_frame = 1;
  1917. idr(h);
  1918. h->prev_frame_num = -1;
  1919. if (h->s.current_picture_ptr)
  1920. h->s.current_picture_ptr->f.reference = 0;
  1921. h->s.first_field = 0;
  1922. memset(h->ref_list[0], 0, sizeof(h->ref_list[0]));
  1923. memset(h->ref_list[1], 0, sizeof(h->ref_list[1]));
  1924. memset(h->default_ref_list[0], 0, sizeof(h->default_ref_list[0]));
  1925. memset(h->default_ref_list[1], 0, sizeof(h->default_ref_list[1]));
  1926. ff_h264_reset_sei(h);
  1927. h->recovery_frame= -1;
  1928. h->sync= 0;
  1929. h->list_count = 0;
  1930. h->current_slice = 0;
  1931. }
  1932. /* forget old pics after a seek */
  1933. static void flush_dpb(AVCodecContext *avctx)
  1934. {
  1935. H264Context *h = avctx->priv_data;
  1936. int i;
  1937. for (i = 0; i <= MAX_DELAYED_PIC_COUNT; i++) {
  1938. if (h->delayed_pic[i])
  1939. h->delayed_pic[i]->f.reference = 0;
  1940. h->delayed_pic[i] = NULL;
  1941. }
  1942. flush_change(h);
  1943. ff_mpeg_flush(avctx);
  1944. }
  1945. static int init_poc(H264Context *h)
  1946. {
  1947. MpegEncContext *const s = &h->s;
  1948. const int max_frame_num = 1 << h->sps.log2_max_frame_num;
  1949. int field_poc[2];
  1950. Picture *cur = s->current_picture_ptr;
  1951. h->frame_num_offset = h->prev_frame_num_offset;
  1952. if (h->frame_num < h->prev_frame_num)
  1953. h->frame_num_offset += max_frame_num;
  1954. if (h->sps.poc_type == 0) {
  1955. const int max_poc_lsb = 1 << h->sps.log2_max_poc_lsb;
  1956. if (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb / 2)
  1957. h->poc_msb = h->prev_poc_msb + max_poc_lsb;
  1958. else if (h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb / 2)
  1959. h->poc_msb = h->prev_poc_msb - max_poc_lsb;
  1960. else
  1961. h->poc_msb = h->prev_poc_msb;
  1962. field_poc[0] =
  1963. field_poc[1] = h->poc_msb + h->poc_lsb;
  1964. if (s->picture_structure == PICT_FRAME)
  1965. field_poc[1] += h->delta_poc_bottom;
  1966. } else if (h->sps.poc_type == 1) {
  1967. int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;
  1968. int i;
  1969. if (h->sps.poc_cycle_length != 0)
  1970. abs_frame_num = h->frame_num_offset + h->frame_num;
  1971. else
  1972. abs_frame_num = 0;
  1973. if (h->nal_ref_idc == 0 && abs_frame_num > 0)
  1974. abs_frame_num--;
  1975. expected_delta_per_poc_cycle = 0;
  1976. for (i = 0; i < h->sps.poc_cycle_length; i++)
  1977. // FIXME integrate during sps parse
  1978. expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[i];
  1979. if (abs_frame_num > 0) {
  1980. int poc_cycle_cnt = (abs_frame_num - 1) / h->sps.poc_cycle_length;
  1981. int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;
  1982. expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;
  1983. for (i = 0; i <= frame_num_in_poc_cycle; i++)
  1984. expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[i];
  1985. } else
  1986. expectedpoc = 0;
  1987. if (h->nal_ref_idc == 0)
  1988. expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;
  1989. field_poc[0] = expectedpoc + h->delta_poc[0];
  1990. field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;
  1991. if (s->picture_structure == PICT_FRAME)
  1992. field_poc[1] += h->delta_poc[1];
  1993. } else {
  1994. int poc = 2 * (h->frame_num_offset + h->frame_num);
  1995. if (!h->nal_ref_idc)
  1996. poc--;
  1997. field_poc[0] = poc;
  1998. field_poc[1] = poc;
  1999. }
  2000. if (s->picture_structure != PICT_BOTTOM_FIELD)
  2001. s->current_picture_ptr->field_poc[0] = field_poc[0];
  2002. if (s->picture_structure != PICT_TOP_FIELD)
  2003. s->current_picture_ptr->field_poc[1] = field_poc[1];
  2004. cur->poc = FFMIN(cur->field_poc[0], cur->field_poc[1]);
  2005. return 0;
  2006. }
  2007. /**
  2008. * initialize scan tables
  2009. */
  2010. static void init_scan_tables(H264Context *h)
  2011. {
  2012. int i;
  2013. for (i = 0; i < 16; i++) {
  2014. #define T(x) (x >> 2) | ((x << 2) & 0xF)
  2015. h->zigzag_scan[i] = T(zigzag_scan[i]);
  2016. h->field_scan[i] = T(field_scan[i]);
  2017. #undef T
  2018. }
  2019. for (i = 0; i < 64; i++) {
  2020. #define T(x) (x >> 3) | ((x & 7) << 3)
  2021. h->zigzag_scan8x8[i] = T(ff_zigzag_direct[i]);
  2022. h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);
  2023. h->field_scan8x8[i] = T(field_scan8x8[i]);
  2024. h->field_scan8x8_cavlc[i] = T(field_scan8x8_cavlc[i]);
  2025. #undef T
  2026. }
  2027. if (h->sps.transform_bypass) { // FIXME same ugly
  2028. memcpy(h->zigzag_scan_q0 , zigzag_scan , sizeof(h->zigzag_scan_q0 ));
  2029. memcpy(h->zigzag_scan8x8_q0 , ff_zigzag_direct , sizeof(h->zigzag_scan8x8_q0 ));
  2030. memcpy(h->zigzag_scan8x8_cavlc_q0 , zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
  2031. memcpy(h->field_scan_q0 , field_scan , sizeof(h->field_scan_q0 ));
  2032. memcpy(h->field_scan8x8_q0 , field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
  2033. memcpy(h->field_scan8x8_cavlc_q0 , field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
  2034. } else {
  2035. memcpy(h->zigzag_scan_q0 , h->zigzag_scan , sizeof(h->zigzag_scan_q0 ));
  2036. memcpy(h->zigzag_scan8x8_q0 , h->zigzag_scan8x8 , sizeof(h->zigzag_scan8x8_q0 ));
  2037. memcpy(h->zigzag_scan8x8_cavlc_q0 , h->zigzag_scan8x8_cavlc , sizeof(h->zigzag_scan8x8_cavlc_q0));
  2038. memcpy(h->field_scan_q0 , h->field_scan , sizeof(h->field_scan_q0 ));
  2039. memcpy(h->field_scan8x8_q0 , h->field_scan8x8 , sizeof(h->field_scan8x8_q0 ));
  2040. memcpy(h->field_scan8x8_cavlc_q0 , h->field_scan8x8_cavlc , sizeof(h->field_scan8x8_cavlc_q0 ));
  2041. }
  2042. }
  2043. static int field_end(H264Context *h, int in_setup)
  2044. {
  2045. MpegEncContext *const s = &h->s;
  2046. AVCodecContext *const avctx = s->avctx;
  2047. int err = 0;
  2048. s->mb_y = 0;
  2049. if (!in_setup && !s->droppable)
  2050. ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX,
  2051. s->picture_structure == PICT_BOTTOM_FIELD);
  2052. if (CONFIG_H264_VDPAU_DECODER &&
  2053. s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  2054. ff_vdpau_h264_set_reference_frames(s);
  2055. if (in_setup || !(avctx->active_thread_type & FF_THREAD_FRAME)) {
  2056. if (!s->droppable) {
  2057. err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);
  2058. h->prev_poc_msb = h->poc_msb;
  2059. h->prev_poc_lsb = h->poc_lsb;
  2060. }
  2061. h->prev_frame_num_offset = h->frame_num_offset;
  2062. h->prev_frame_num = h->frame_num;
  2063. h->outputed_poc = h->next_outputed_poc;
  2064. }
  2065. if (avctx->hwaccel) {
  2066. if (avctx->hwaccel->end_frame(avctx) < 0)
  2067. av_log(avctx, AV_LOG_ERROR,
  2068. "hardware accelerator failed to decode picture\n");
  2069. }
  2070. if (CONFIG_H264_VDPAU_DECODER &&
  2071. s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  2072. ff_vdpau_h264_picture_complete(s);
  2073. /*
  2074. * FIXME: Error handling code does not seem to support interlaced
  2075. * when slices span multiple rows
  2076. * The ff_er_add_slice calls don't work right for bottom
  2077. * fields; they cause massive erroneous error concealing
  2078. * Error marking covers both fields (top and bottom).
  2079. * This causes a mismatched s->error_count
  2080. * and a bad error table. Further, the error count goes to
  2081. * INT_MAX when called for bottom field, because mb_y is
  2082. * past end by one (callers fault) and resync_mb_y != 0
  2083. * causes problems for the first MB line, too.
  2084. */
  2085. if (!FIELD_PICTURE)
  2086. ff_er_frame_end(s);
  2087. ff_MPV_frame_end(s);
  2088. h->current_slice = 0;
  2089. return err;
  2090. }
  2091. /**
  2092. * Replicate H264 "master" context to thread contexts.
  2093. */
  2094. static int clone_slice(H264Context *dst, H264Context *src)
  2095. {
  2096. int ret;
  2097. memcpy(dst->block_offset, src->block_offset, sizeof(dst->block_offset));
  2098. dst->s.current_picture_ptr = src->s.current_picture_ptr;
  2099. dst->s.current_picture = src->s.current_picture;
  2100. dst->s.linesize = src->s.linesize;
  2101. dst->s.uvlinesize = src->s.uvlinesize;
  2102. dst->s.first_field = src->s.first_field;
  2103. if (!dst->s.edge_emu_buffer &&
  2104. (ret = ff_mpv_frame_size_alloc(&dst->s, dst->s.linesize))) {
  2105. av_log(dst->s.avctx, AV_LOG_ERROR,
  2106. "Failed to allocate scratch buffers\n");
  2107. return ret;
  2108. }
  2109. dst->prev_poc_msb = src->prev_poc_msb;
  2110. dst->prev_poc_lsb = src->prev_poc_lsb;
  2111. dst->prev_frame_num_offset = src->prev_frame_num_offset;
  2112. dst->prev_frame_num = src->prev_frame_num;
  2113. dst->short_ref_count = src->short_ref_count;
  2114. memcpy(dst->short_ref, src->short_ref, sizeof(dst->short_ref));
  2115. memcpy(dst->long_ref, src->long_ref, sizeof(dst->long_ref));
  2116. memcpy(dst->default_ref_list, src->default_ref_list, sizeof(dst->default_ref_list));
  2117. memcpy(dst->ref_list, src->ref_list, sizeof(dst->ref_list));
  2118. memcpy(dst->dequant4_coeff, src->dequant4_coeff, sizeof(src->dequant4_coeff));
  2119. memcpy(dst->dequant8_coeff, src->dequant8_coeff, sizeof(src->dequant8_coeff));
  2120. return 0;
  2121. }
  2122. /**
  2123. * Compute profile from profile_idc and constraint_set?_flags.
  2124. *
  2125. * @param sps SPS
  2126. *
  2127. * @return profile as defined by FF_PROFILE_H264_*
  2128. */
  2129. int ff_h264_get_profile(SPS *sps)
  2130. {
  2131. int profile = sps->profile_idc;
  2132. switch (sps->profile_idc) {
  2133. case FF_PROFILE_H264_BASELINE:
  2134. // constraint_set1_flag set to 1
  2135. profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;
  2136. break;
  2137. case FF_PROFILE_H264_HIGH_10:
  2138. case FF_PROFILE_H264_HIGH_422:
  2139. case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
  2140. // constraint_set3_flag set to 1
  2141. profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;
  2142. break;
  2143. }
  2144. return profile;
  2145. }
  2146. static int h264_set_parameter_from_sps(H264Context *h)
  2147. {
  2148. MpegEncContext *s = &h->s;
  2149. if (s->flags & CODEC_FLAG_LOW_DELAY ||
  2150. (h->sps.bitstream_restriction_flag &&
  2151. !h->sps.num_reorder_frames)) {
  2152. if (s->avctx->has_b_frames > 1 || h->delayed_pic[0])
  2153. av_log(h->s.avctx, AV_LOG_WARNING, "Delayed frames seen. "
  2154. "Reenabling low delay requires a codec flush.\n");
  2155. else
  2156. s->low_delay = 1;
  2157. }
  2158. if (s->avctx->has_b_frames < 2)
  2159. s->avctx->has_b_frames = !s->low_delay;
  2160. if (s->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
  2161. h->cur_chroma_format_idc != h->sps.chroma_format_idc) {
  2162. if (s->avctx->codec &&
  2163. s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU &&
  2164. (h->sps.bit_depth_luma != 8 || h->sps.chroma_format_idc > 1)) {
  2165. av_log(s->avctx, AV_LOG_ERROR,
  2166. "VDPAU decoding does not support video colorspace.\n");
  2167. return AVERROR_INVALIDDATA;
  2168. }
  2169. if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 14 &&
  2170. h->sps.bit_depth_luma != 11 && h->sps.bit_depth_luma != 13 &&
  2171. (h->sps.bit_depth_luma != 9 || !CHROMA422)) {
  2172. s->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
  2173. h->cur_chroma_format_idc = h->sps.chroma_format_idc;
  2174. h->pixel_shift = h->sps.bit_depth_luma > 8;
  2175. ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
  2176. h->sps.chroma_format_idc);
  2177. ff_h264_pred_init(&h->hpc, s->codec_id, h->sps.bit_depth_luma,
  2178. h->sps.chroma_format_idc);
  2179. s->dsp.dct_bits = h->sps.bit_depth_luma > 8 ? 32 : 16;
  2180. ff_dsputil_init(&s->dsp, s->avctx);
  2181. } else {
  2182. av_log(s->avctx, AV_LOG_ERROR, "Unsupported bit depth: %d\n",
  2183. h->sps.bit_depth_luma);
  2184. return AVERROR_INVALIDDATA;
  2185. }
  2186. }
  2187. return 0;
  2188. }
  2189. static enum PixelFormat get_pixel_format(H264Context *h)
  2190. {
  2191. MpegEncContext *const s = &h->s;
  2192. switch (h->sps.bit_depth_luma) {
  2193. case 9:
  2194. if (CHROMA444) {
  2195. if (s->avctx->colorspace == AVCOL_SPC_RGB) {
  2196. return AV_PIX_FMT_GBRP9;
  2197. } else
  2198. return AV_PIX_FMT_YUV444P9;
  2199. } else if (CHROMA422)
  2200. return AV_PIX_FMT_YUV422P9;
  2201. else
  2202. return AV_PIX_FMT_YUV420P9;
  2203. break;
  2204. case 10:
  2205. if (CHROMA444) {
  2206. if (s->avctx->colorspace == AVCOL_SPC_RGB) {
  2207. return AV_PIX_FMT_GBRP10;
  2208. } else
  2209. return AV_PIX_FMT_YUV444P10;
  2210. } else if (CHROMA422)
  2211. return AV_PIX_FMT_YUV422P10;
  2212. else
  2213. return AV_PIX_FMT_YUV420P10;
  2214. break;
  2215. case 12:
  2216. if (CHROMA444) {
  2217. if (s->avctx->colorspace == AVCOL_SPC_RGB) {
  2218. return AV_PIX_FMT_GBRP12;
  2219. } else
  2220. return AV_PIX_FMT_YUV444P12;
  2221. } else if (CHROMA422)
  2222. return AV_PIX_FMT_YUV422P12;
  2223. else
  2224. return AV_PIX_FMT_YUV420P12;
  2225. break;
  2226. case 14:
  2227. if (CHROMA444) {
  2228. if (s->avctx->colorspace == AVCOL_SPC_RGB) {
  2229. return AV_PIX_FMT_GBRP14;
  2230. } else
  2231. return AV_PIX_FMT_YUV444P14;
  2232. } else if (CHROMA422)
  2233. return AV_PIX_FMT_YUV422P14;
  2234. else
  2235. return AV_PIX_FMT_YUV420P14;
  2236. break;
  2237. case 8:
  2238. if (CHROMA444) {
  2239. if (s->avctx->colorspace == AVCOL_SPC_RGB) {
  2240. av_log(h->s.avctx, AV_LOG_DEBUG, "Detected GBR colorspace.\n");
  2241. return AV_PIX_FMT_GBR24P;
  2242. } else if (s->avctx->colorspace == AVCOL_SPC_YCGCO) {
  2243. av_log(h->s.avctx, AV_LOG_WARNING, "Detected unsupported YCgCo colorspace.\n");
  2244. }
  2245. return s->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ444P
  2246. : AV_PIX_FMT_YUV444P;
  2247. } else if (CHROMA422) {
  2248. return s->avctx->color_range == AVCOL_RANGE_JPEG ? AV_PIX_FMT_YUVJ422P
  2249. : AV_PIX_FMT_YUV422P;
  2250. } else {
  2251. return s->avctx->get_format(s->avctx, s->avctx->codec->pix_fmts ?
  2252. s->avctx->codec->pix_fmts :
  2253. s->avctx->color_range == AVCOL_RANGE_JPEG ?
  2254. hwaccel_pixfmt_list_h264_jpeg_420 :
  2255. ff_hwaccel_pixfmt_list_420);
  2256. }
  2257. break;
  2258. default:
  2259. av_log(s->avctx, AV_LOG_ERROR,
  2260. "Unsupported bit depth: %d\n", h->sps.bit_depth_luma);
  2261. return AVERROR_INVALIDDATA;
  2262. }
  2263. }
  2264. static int h264_slice_header_init(H264Context *h, int reinit)
  2265. {
  2266. MpegEncContext *const s = &h->s;
  2267. int i, ret;
  2268. if( FFALIGN(s->avctx->width , 16 ) == s->width
  2269. && FFALIGN(s->avctx->height, 16*(2 - h->sps.frame_mbs_only_flag)) == s->height
  2270. && !h->sps.crop_right && !h->sps.crop_bottom
  2271. && (s->avctx->width != s->width || s->avctx->height && s->height)
  2272. ) {
  2273. av_log(h->s.avctx, AV_LOG_DEBUG, "Using externally provided dimensions\n");
  2274. s->avctx->coded_width = s->width;
  2275. s->avctx->coded_height = s->height;
  2276. } else{
  2277. avcodec_set_dimensions(s->avctx, s->width, s->height);
  2278. s->avctx->width -= (2>>CHROMA444)*FFMIN(h->sps.crop_right, (8<<CHROMA444)-1);
  2279. 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);
  2280. }
  2281. s->avctx->sample_aspect_ratio = h->sps.sar;
  2282. av_assert0(s->avctx->sample_aspect_ratio.den);
  2283. if (h->sps.timing_info_present_flag) {
  2284. int64_t den = h->sps.time_scale;
  2285. if (h->x264_build < 44U)
  2286. den *= 2;
  2287. av_reduce(&s->avctx->time_base.num, &s->avctx->time_base.den,
  2288. h->sps.num_units_in_tick, den, 1 << 30);
  2289. }
  2290. s->avctx->hwaccel = ff_find_hwaccel(s->avctx->codec->id, s->avctx->pix_fmt);
  2291. if (reinit) {
  2292. free_tables(h, 0);
  2293. if ((ret = ff_MPV_common_frame_size_change(s)) < 0) {
  2294. av_log(h->s.avctx, AV_LOG_ERROR, "ff_MPV_common_frame_size_change() failed.\n");
  2295. return ret;
  2296. }
  2297. } else {
  2298. if ((ret = ff_MPV_common_init(s) < 0)) {
  2299. av_log(h->s.avctx, AV_LOG_ERROR, "ff_MPV_common_init() failed.\n");
  2300. return ret;
  2301. }
  2302. }
  2303. s->first_field = 0;
  2304. h->prev_interlaced_frame = 1;
  2305. init_scan_tables(h);
  2306. if (ff_h264_alloc_tables(h) < 0) {
  2307. av_log(h->s.avctx, AV_LOG_ERROR,
  2308. "Could not allocate memory for h264\n");
  2309. return AVERROR(ENOMEM);
  2310. }
  2311. if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_SLICE)) {
  2312. if (context_init(h) < 0) {
  2313. av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed.\n");
  2314. return -1;
  2315. }
  2316. } else {
  2317. for (i = 1; i < s->slice_context_count; i++) {
  2318. H264Context *c;
  2319. c = h->thread_context[i] = av_malloc(sizeof(H264Context));
  2320. memcpy(c, h->s.thread_context[i], sizeof(MpegEncContext));
  2321. memset(&c->s + 1, 0, sizeof(H264Context) - sizeof(MpegEncContext));
  2322. c->h264dsp = h->h264dsp;
  2323. c->sps = h->sps;
  2324. c->pps = h->pps;
  2325. c->pixel_shift = h->pixel_shift;
  2326. c->cur_chroma_format_idc = h->cur_chroma_format_idc;
  2327. init_scan_tables(c);
  2328. clone_tables(c, h, i);
  2329. }
  2330. for (i = 0; i < s->slice_context_count; i++)
  2331. if (context_init(h->thread_context[i]) < 0) {
  2332. av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed.\n");
  2333. return -1;
  2334. }
  2335. }
  2336. return 0;
  2337. }
  2338. /**
  2339. * Decode a slice header.
  2340. * This will also call ff_MPV_common_init() and frame_start() as needed.
  2341. *
  2342. * @param h h264context
  2343. * @param h0 h264 master context (differs from 'h' when doing sliced based
  2344. * parallel decoding)
  2345. *
  2346. * @return 0 if okay, <0 if an error occurred, 1 if decoding must not be multithreaded
  2347. */
  2348. static int decode_slice_header(H264Context *h, H264Context *h0)
  2349. {
  2350. MpegEncContext *const s = &h->s;
  2351. MpegEncContext *const s0 = &h0->s;
  2352. unsigned int first_mb_in_slice;
  2353. unsigned int pps_id;
  2354. int num_ref_idx_active_override_flag, ret;
  2355. unsigned int slice_type, tmp, i, j;
  2356. int default_ref_list_done = 0;
  2357. int last_pic_structure, last_pic_droppable;
  2358. int must_reinit;
  2359. int needs_reinit = 0;
  2360. enum AVPixelFormat pix_fmt;
  2361. /* FIXME: 2tap qpel isn't implemented for high bit depth. */
  2362. if ((s->avctx->flags2 & CODEC_FLAG2_FAST) &&
  2363. !h->nal_ref_idc && !h->pixel_shift) {
  2364. s->me.qpel_put = s->dsp.put_2tap_qpel_pixels_tab;
  2365. s->me.qpel_avg = s->dsp.avg_2tap_qpel_pixels_tab;
  2366. } else {
  2367. s->me.qpel_put = s->dsp.put_h264_qpel_pixels_tab;
  2368. s->me.qpel_avg = s->dsp.avg_h264_qpel_pixels_tab;
  2369. }
  2370. first_mb_in_slice = get_ue_golomb_long(&s->gb);
  2371. if (first_mb_in_slice == 0) { // FIXME better field boundary detection
  2372. if (h0->current_slice && FIELD_PICTURE) {
  2373. field_end(h, 1);
  2374. }
  2375. h0->current_slice = 0;
  2376. if (!s0->first_field) {
  2377. if (s->current_picture_ptr && !s->droppable &&
  2378. s->current_picture_ptr->owner2 == s) {
  2379. ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX,
  2380. s->picture_structure == PICT_BOTTOM_FIELD);
  2381. }
  2382. s->current_picture_ptr = NULL;
  2383. }
  2384. }
  2385. slice_type = get_ue_golomb_31(&s->gb);
  2386. if (slice_type > 9) {
  2387. av_log(h->s.avctx, AV_LOG_ERROR,
  2388. "slice type too large (%d) at %d %d\n",
  2389. slice_type, s->mb_x, s->mb_y);
  2390. return -1;
  2391. }
  2392. if (slice_type > 4) {
  2393. slice_type -= 5;
  2394. h->slice_type_fixed = 1;
  2395. } else
  2396. h->slice_type_fixed = 0;
  2397. slice_type = golomb_to_pict_type[slice_type];
  2398. if (slice_type == AV_PICTURE_TYPE_I ||
  2399. (h0->current_slice != 0 && slice_type == h0->last_slice_type)) {
  2400. default_ref_list_done = 1;
  2401. }
  2402. h->slice_type = slice_type;
  2403. h->slice_type_nos = slice_type & 3;
  2404. // to make a few old functions happy, it's wrong though
  2405. s->pict_type = h->slice_type;
  2406. pps_id = get_ue_golomb(&s->gb);
  2407. if (pps_id >= MAX_PPS_COUNT) {
  2408. av_log(h->s.avctx, AV_LOG_ERROR, "pps_id %d out of range\n", pps_id);
  2409. return -1;
  2410. }
  2411. if (!h0->pps_buffers[pps_id]) {
  2412. av_log(h->s.avctx, AV_LOG_ERROR,
  2413. "non-existing PPS %u referenced\n",
  2414. pps_id);
  2415. return -1;
  2416. }
  2417. h->pps = *h0->pps_buffers[pps_id];
  2418. if (!h0->sps_buffers[h->pps.sps_id]) {
  2419. av_log(h->s.avctx, AV_LOG_ERROR,
  2420. "non-existing SPS %u referenced\n",
  2421. h->pps.sps_id);
  2422. return -1;
  2423. }
  2424. if (h->pps.sps_id != h->current_sps_id ||
  2425. h->context_reinitialized ||
  2426. h0->sps_buffers[h->pps.sps_id]->new) {
  2427. h0->sps_buffers[h->pps.sps_id]->new = 0;
  2428. h->current_sps_id = h->pps.sps_id;
  2429. h->sps = *h0->sps_buffers[h->pps.sps_id];
  2430. if ((ret = h264_set_parameter_from_sps(h)) < 0)
  2431. return ret;
  2432. }
  2433. s->avctx->profile = ff_h264_get_profile(&h->sps);
  2434. s->avctx->level = h->sps.level_idc;
  2435. s->avctx->refs = h->sps.ref_frame_count;
  2436. if (s->mb_width != h->sps.mb_width ||
  2437. s->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag))
  2438. needs_reinit = 1;
  2439. must_reinit = (s->context_initialized &&
  2440. ( 16*h->sps.mb_width != s->avctx->coded_width
  2441. || 16*h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) != s->avctx->coded_height
  2442. || s->avctx->bits_per_raw_sample != h->sps.bit_depth_luma
  2443. || h->cur_chroma_format_idc != h->sps.chroma_format_idc
  2444. || av_cmp_q(h->sps.sar, s->avctx->sample_aspect_ratio)));
  2445. s->mb_width = h->sps.mb_width;
  2446. s->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);
  2447. h->b_stride = s->mb_width * 4;
  2448. s->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p
  2449. s->width = 16 * s->mb_width;
  2450. s->height = 16 * s->mb_height;
  2451. if (h->sps.video_signal_type_present_flag) {
  2452. s->avctx->color_range = h->sps.full_range>0 ? AVCOL_RANGE_JPEG
  2453. : AVCOL_RANGE_MPEG;
  2454. if (h->sps.colour_description_present_flag) {
  2455. s->avctx->color_primaries = h->sps.color_primaries;
  2456. s->avctx->color_trc = h->sps.color_trc;
  2457. s->avctx->colorspace = h->sps.colorspace;
  2458. }
  2459. }
  2460. ret = get_pixel_format(h);
  2461. if (ret < 0)
  2462. return ret;
  2463. else
  2464. pix_fmt = ret;
  2465. if (s->avctx->pix_fmt == PIX_FMT_NONE)
  2466. s->avctx->pix_fmt = pix_fmt;
  2467. if (s->context_initialized &&
  2468. (
  2469. needs_reinit ||
  2470. must_reinit)) {
  2471. if (h != h0) {
  2472. av_log(s->avctx, AV_LOG_ERROR, "changing width/height on "
  2473. "slice %d\n", h0->current_slice + 1);
  2474. return AVERROR_INVALIDDATA;
  2475. }
  2476. av_log(h->s.avctx, AV_LOG_INFO, "Reinit context to %dx%d, "
  2477. "pix_fmt: %d\n", s->width, s->height, pix_fmt);
  2478. flush_change(h);
  2479. s->avctx->pix_fmt = pix_fmt;
  2480. if ((ret = h264_slice_header_init(h, 1)) < 0) {
  2481. av_log(h->s.avctx, AV_LOG_ERROR,
  2482. "h264_slice_header_init() failed\n");
  2483. return ret;
  2484. }
  2485. h->context_reinitialized = 1;
  2486. }
  2487. if (!s->context_initialized) {
  2488. if (h != h0) {
  2489. av_log(h->s.avctx, AV_LOG_ERROR,
  2490. "Cannot (re-)initialize context during parallel decoding.\n");
  2491. return -1;
  2492. }
  2493. if ((ret = h264_slice_header_init(h, 0)) < 0) {
  2494. av_log(h->s.avctx, AV_LOG_ERROR,
  2495. "h264_slice_header_init() failed\n");
  2496. return ret;
  2497. }
  2498. }
  2499. if (h == h0 && h->dequant_coeff_pps != pps_id) {
  2500. h->dequant_coeff_pps = pps_id;
  2501. init_dequant_tables(h);
  2502. }
  2503. h->frame_num = get_bits(&s->gb, h->sps.log2_max_frame_num);
  2504. h->mb_mbaff = 0;
  2505. h->mb_aff_frame = 0;
  2506. last_pic_structure = s0->picture_structure;
  2507. last_pic_droppable = s0->droppable;
  2508. s->droppable = h->nal_ref_idc == 0;
  2509. if (h->sps.frame_mbs_only_flag) {
  2510. s->picture_structure = PICT_FRAME;
  2511. } else {
  2512. if (!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B) {
  2513. av_log(h->s.avctx, AV_LOG_ERROR, "This stream was generated by a broken encoder, invalid 8x8 inference\n");
  2514. return -1;
  2515. }
  2516. if (get_bits1(&s->gb)) { // field_pic_flag
  2517. s->picture_structure = PICT_TOP_FIELD + get_bits1(&s->gb); // bottom_field_flag
  2518. } else {
  2519. s->picture_structure = PICT_FRAME;
  2520. h->mb_aff_frame = h->sps.mb_aff;
  2521. }
  2522. }
  2523. h->mb_field_decoding_flag = s->picture_structure != PICT_FRAME;
  2524. if (h0->current_slice != 0) {
  2525. if (last_pic_structure != s->picture_structure ||
  2526. last_pic_droppable != s->droppable) {
  2527. av_log(h->s.avctx, AV_LOG_ERROR,
  2528. "Changing field mode (%d -> %d) between slices is not allowed\n",
  2529. last_pic_structure, s->picture_structure);
  2530. s->picture_structure = last_pic_structure;
  2531. s->droppable = last_pic_droppable;
  2532. return AVERROR_INVALIDDATA;
  2533. } else if (!s0->current_picture_ptr) {
  2534. av_log(s->avctx, AV_LOG_ERROR,
  2535. "unset current_picture_ptr on %d. slice\n",
  2536. h0->current_slice + 1);
  2537. return AVERROR_INVALIDDATA;
  2538. }
  2539. } else {
  2540. /* Shorten frame num gaps so we don't have to allocate reference
  2541. * frames just to throw them away */
  2542. if (h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0) {
  2543. int unwrap_prev_frame_num = h->prev_frame_num;
  2544. int max_frame_num = 1 << h->sps.log2_max_frame_num;
  2545. if (unwrap_prev_frame_num > h->frame_num)
  2546. unwrap_prev_frame_num -= max_frame_num;
  2547. if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {
  2548. unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;
  2549. if (unwrap_prev_frame_num < 0)
  2550. unwrap_prev_frame_num += max_frame_num;
  2551. h->prev_frame_num = unwrap_prev_frame_num;
  2552. }
  2553. }
  2554. /* See if we have a decoded first field looking for a pair...
  2555. * Here, we're using that to see if we should mark previously
  2556. * decode frames as "finished".
  2557. * We have to do that before the "dummy" in-between frame allocation,
  2558. * since that can modify s->current_picture_ptr. */
  2559. if (s0->first_field) {
  2560. assert(s0->current_picture_ptr);
  2561. assert(s0->current_picture_ptr->f.data[0]);
  2562. assert(s0->current_picture_ptr->f.reference != DELAYED_PIC_REF);
  2563. /* Mark old field/frame as completed */
  2564. if (!last_pic_droppable && s0->current_picture_ptr->owner2 == s0) {
  2565. ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
  2566. last_pic_structure == PICT_BOTTOM_FIELD);
  2567. }
  2568. /* figure out if we have a complementary field pair */
  2569. if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
  2570. /* Previous field is unmatched. Don't display it, but let it
  2571. * remain for reference if marked as such. */
  2572. if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
  2573. ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
  2574. last_pic_structure == PICT_TOP_FIELD);
  2575. }
  2576. } else {
  2577. if (s0->current_picture_ptr->frame_num != h->frame_num) {
  2578. /* This and previous field were reference, but had
  2579. * different frame_nums. Consider this field first in
  2580. * pair. Throw away previous field except for reference
  2581. * purposes. */
  2582. if (!last_pic_droppable && last_pic_structure != PICT_FRAME) {
  2583. ff_thread_report_progress(&s0->current_picture_ptr->f, INT_MAX,
  2584. last_pic_structure == PICT_TOP_FIELD);
  2585. }
  2586. } else {
  2587. /* Second field in complementary pair */
  2588. if (!((last_pic_structure == PICT_TOP_FIELD &&
  2589. s->picture_structure == PICT_BOTTOM_FIELD) ||
  2590. (last_pic_structure == PICT_BOTTOM_FIELD &&
  2591. s->picture_structure == PICT_TOP_FIELD))) {
  2592. av_log(s->avctx, AV_LOG_ERROR,
  2593. "Invalid field mode combination %d/%d\n",
  2594. last_pic_structure, s->picture_structure);
  2595. s->picture_structure = last_pic_structure;
  2596. s->droppable = last_pic_droppable;
  2597. return AVERROR_INVALIDDATA;
  2598. } else if (last_pic_droppable != s->droppable) {
  2599. av_log(s->avctx, AV_LOG_ERROR,
  2600. "Cannot combine reference and non-reference fields in the same frame\n");
  2601. av_log_ask_for_sample(s->avctx, NULL);
  2602. s->picture_structure = last_pic_structure;
  2603. s->droppable = last_pic_droppable;
  2604. return AVERROR_INVALIDDATA;
  2605. }
  2606. /* Take ownership of this buffer. Note that if another thread owned
  2607. * the first field of this buffer, we're not operating on that pointer,
  2608. * so the original thread is still responsible for reporting progress
  2609. * on that first field (or if that was us, we just did that above).
  2610. * By taking ownership, we assign responsibility to ourselves to
  2611. * report progress on the second field. */
  2612. s0->current_picture_ptr->owner2 = s0;
  2613. }
  2614. }
  2615. }
  2616. while (h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0 && !s0->first_field &&
  2617. h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {
  2618. Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;
  2619. av_log(h->s.avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",
  2620. h->frame_num, h->prev_frame_num);
  2621. if (ff_h264_frame_start(h) < 0)
  2622. return -1;
  2623. h->prev_frame_num++;
  2624. h->prev_frame_num %= 1 << h->sps.log2_max_frame_num;
  2625. s->current_picture_ptr->frame_num = h->prev_frame_num;
  2626. ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX, 0);
  2627. ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX, 1);
  2628. ff_generate_sliding_window_mmcos(h);
  2629. if (ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index) < 0 &&
  2630. (s->avctx->err_recognition & AV_EF_EXPLODE))
  2631. return AVERROR_INVALIDDATA;
  2632. /* Error concealment: if a ref is missing, copy the previous ref in its place.
  2633. * FIXME: avoiding a memcpy would be nice, but ref handling makes many assumptions
  2634. * about there being no actual duplicates.
  2635. * FIXME: this doesn't copy padding for out-of-frame motion vectors. Given we're
  2636. * concealing a lost frame, this probably isn't noticeable by comparison, but it should
  2637. * be fixed. */
  2638. if (h->short_ref_count) {
  2639. if (prev) {
  2640. av_image_copy(h->short_ref[0]->f.data, h->short_ref[0]->f.linesize,
  2641. (const uint8_t **)prev->f.data, prev->f.linesize,
  2642. s->avctx->pix_fmt, s->mb_width * 16, s->mb_height * 16);
  2643. h->short_ref[0]->poc = prev->poc + 2;
  2644. }
  2645. h->short_ref[0]->frame_num = h->prev_frame_num;
  2646. }
  2647. }
  2648. /* See if we have a decoded first field looking for a pair...
  2649. * We're using that to see whether to continue decoding in that
  2650. * frame, or to allocate a new one. */
  2651. if (s0->first_field) {
  2652. assert(s0->current_picture_ptr);
  2653. assert(s0->current_picture_ptr->f.data[0]);
  2654. assert(s0->current_picture_ptr->f.reference != DELAYED_PIC_REF);
  2655. /* figure out if we have a complementary field pair */
  2656. if (!FIELD_PICTURE || s->picture_structure == last_pic_structure) {
  2657. /* Previous field is unmatched. Don't display it, but let it
  2658. * remain for reference if marked as such. */
  2659. s0->current_picture_ptr = NULL;
  2660. s0->first_field = FIELD_PICTURE;
  2661. } else {
  2662. if (s0->current_picture_ptr->frame_num != h->frame_num) {
  2663. ff_thread_report_progress((AVFrame*)s0->current_picture_ptr, INT_MAX,
  2664. s0->picture_structure==PICT_BOTTOM_FIELD);
  2665. /* This and the previous field had different frame_nums.
  2666. * Consider this field first in pair. Throw away previous
  2667. * one except for reference purposes. */
  2668. s0->first_field = 1;
  2669. s0->current_picture_ptr = NULL;
  2670. } else {
  2671. /* Second field in complementary pair */
  2672. s0->first_field = 0;
  2673. }
  2674. }
  2675. } else {
  2676. /* Frame or first field in a potentially complementary pair */
  2677. s0->first_field = FIELD_PICTURE;
  2678. }
  2679. if (!FIELD_PICTURE || s0->first_field) {
  2680. if (ff_h264_frame_start(h) < 0) {
  2681. s0->first_field = 0;
  2682. return -1;
  2683. }
  2684. } else {
  2685. ff_release_unused_pictures(s, 0);
  2686. }
  2687. }
  2688. if (h != h0 && (ret = clone_slice(h, h0)) < 0)
  2689. return ret;
  2690. s->current_picture_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup
  2691. av_assert1(s->mb_num == s->mb_width * s->mb_height);
  2692. if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE >= s->mb_num ||
  2693. first_mb_in_slice >= s->mb_num) {
  2694. av_log(h->s.avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");
  2695. return -1;
  2696. }
  2697. s->resync_mb_x = s->mb_x = first_mb_in_slice % s->mb_width;
  2698. s->resync_mb_y = s->mb_y = (first_mb_in_slice / s->mb_width) << FIELD_OR_MBAFF_PICTURE;
  2699. if (s->picture_structure == PICT_BOTTOM_FIELD)
  2700. s->resync_mb_y = s->mb_y = s->mb_y + 1;
  2701. av_assert1(s->mb_y < s->mb_height);
  2702. if (s->picture_structure == PICT_FRAME) {
  2703. h->curr_pic_num = h->frame_num;
  2704. h->max_pic_num = 1 << h->sps.log2_max_frame_num;
  2705. } else {
  2706. h->curr_pic_num = 2 * h->frame_num + 1;
  2707. h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1);
  2708. }
  2709. if (h->nal_unit_type == NAL_IDR_SLICE)
  2710. get_ue_golomb(&s->gb); /* idr_pic_id */
  2711. if (h->sps.poc_type == 0) {
  2712. h->poc_lsb = get_bits(&s->gb, h->sps.log2_max_poc_lsb);
  2713. if (h->pps.pic_order_present == 1 && s->picture_structure == PICT_FRAME)
  2714. h->delta_poc_bottom = get_se_golomb(&s->gb);
  2715. }
  2716. if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {
  2717. h->delta_poc[0] = get_se_golomb(&s->gb);
  2718. if (h->pps.pic_order_present == 1 && s->picture_structure == PICT_FRAME)
  2719. h->delta_poc[1] = get_se_golomb(&s->gb);
  2720. }
  2721. init_poc(h);
  2722. if (h->pps.redundant_pic_cnt_present)
  2723. h->redundant_pic_count = get_ue_golomb(&s->gb);
  2724. // set defaults, might be overridden a few lines later
  2725. h->ref_count[0] = h->pps.ref_count[0];
  2726. h->ref_count[1] = h->pps.ref_count[1];
  2727. if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
  2728. unsigned max[2];
  2729. max[0] = max[1] = s->picture_structure == PICT_FRAME ? 15 : 31;
  2730. if (h->slice_type_nos == AV_PICTURE_TYPE_B)
  2731. h->direct_spatial_mv_pred = get_bits1(&s->gb);
  2732. num_ref_idx_active_override_flag = get_bits1(&s->gb);
  2733. if (num_ref_idx_active_override_flag) {
  2734. h->ref_count[0] = get_ue_golomb(&s->gb) + 1;
  2735. if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
  2736. h->ref_count[1] = get_ue_golomb(&s->gb) + 1;
  2737. } else
  2738. // full range is spec-ok in this case, even for frames
  2739. h->ref_count[1] = 1;
  2740. }
  2741. if (h->ref_count[0]-1 > max[0] || h->ref_count[1]-1 > max[1]){
  2742. 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]);
  2743. h->ref_count[0] = h->ref_count[1] = 1;
  2744. return AVERROR_INVALIDDATA;
  2745. }
  2746. if (h->slice_type_nos == AV_PICTURE_TYPE_B)
  2747. h->list_count = 2;
  2748. else
  2749. h->list_count = 1;
  2750. } else
  2751. h->ref_count[1]= h->ref_count[0]= h->list_count= 0;
  2752. if (!default_ref_list_done)
  2753. ff_h264_fill_default_ref_list(h);
  2754. if (h->slice_type_nos != AV_PICTURE_TYPE_I &&
  2755. ff_h264_decode_ref_pic_list_reordering(h) < 0) {
  2756. h->ref_count[1] = h->ref_count[0] = 0;
  2757. return -1;
  2758. }
  2759. if (h->slice_type_nos != AV_PICTURE_TYPE_I) {
  2760. s->last_picture_ptr = &h->ref_list[0][0];
  2761. s->last_picture_ptr->owner2 = s;
  2762. ff_copy_picture(&s->last_picture, s->last_picture_ptr);
  2763. }
  2764. if (h->slice_type_nos == AV_PICTURE_TYPE_B) {
  2765. s->next_picture_ptr = &h->ref_list[1][0];
  2766. s->next_picture_ptr->owner2 = s;
  2767. ff_copy_picture(&s->next_picture, s->next_picture_ptr);
  2768. }
  2769. if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) ||
  2770. (h->pps.weighted_bipred_idc == 1 &&
  2771. h->slice_type_nos == AV_PICTURE_TYPE_B))
  2772. pred_weight_table(h);
  2773. else if (h->pps.weighted_bipred_idc == 2 &&
  2774. h->slice_type_nos == AV_PICTURE_TYPE_B) {
  2775. implicit_weight_table(h, -1);
  2776. } else {
  2777. h->use_weight = 0;
  2778. for (i = 0; i < 2; i++) {
  2779. h->luma_weight_flag[i] = 0;
  2780. h->chroma_weight_flag[i] = 0;
  2781. }
  2782. }
  2783. if (h->nal_ref_idc && ff_h264_decode_ref_pic_marking(h0, &s->gb) < 0 &&
  2784. (s->avctx->err_recognition & AV_EF_EXPLODE))
  2785. return AVERROR_INVALIDDATA;
  2786. if (FRAME_MBAFF) {
  2787. ff_h264_fill_mbaff_ref_list(h);
  2788. if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) {
  2789. implicit_weight_table(h, 0);
  2790. implicit_weight_table(h, 1);
  2791. }
  2792. }
  2793. if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred)
  2794. ff_h264_direct_dist_scale_factor(h);
  2795. ff_h264_direct_ref_list_init(h);
  2796. if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {
  2797. tmp = get_ue_golomb_31(&s->gb);
  2798. if (tmp > 2) {
  2799. av_log(s->avctx, AV_LOG_ERROR, "cabac_init_idc overflow\n");
  2800. return -1;
  2801. }
  2802. h->cabac_init_idc = tmp;
  2803. }
  2804. h->last_qscale_diff = 0;
  2805. tmp = h->pps.init_qp + get_se_golomb(&s->gb);
  2806. if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {
  2807. av_log(s->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);
  2808. return -1;
  2809. }
  2810. s->qscale = tmp;
  2811. h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
  2812. h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
  2813. // FIXME qscale / qp ... stuff
  2814. if (h->slice_type == AV_PICTURE_TYPE_SP)
  2815. get_bits1(&s->gb); /* sp_for_switch_flag */
  2816. if (h->slice_type == AV_PICTURE_TYPE_SP ||
  2817. h->slice_type == AV_PICTURE_TYPE_SI)
  2818. get_se_golomb(&s->gb); /* slice_qs_delta */
  2819. h->deblocking_filter = 1;
  2820. h->slice_alpha_c0_offset = 52;
  2821. h->slice_beta_offset = 52;
  2822. if (h->pps.deblocking_filter_parameters_present) {
  2823. tmp = get_ue_golomb_31(&s->gb);
  2824. if (tmp > 2) {
  2825. av_log(s->avctx, AV_LOG_ERROR,
  2826. "deblocking_filter_idc %u out of range\n", tmp);
  2827. return -1;
  2828. }
  2829. h->deblocking_filter = tmp;
  2830. if (h->deblocking_filter < 2)
  2831. h->deblocking_filter ^= 1; // 1<->0
  2832. if (h->deblocking_filter) {
  2833. h->slice_alpha_c0_offset += get_se_golomb(&s->gb) << 1;
  2834. h->slice_beta_offset += get_se_golomb(&s->gb) << 1;
  2835. if (h->slice_alpha_c0_offset > 104U ||
  2836. h->slice_beta_offset > 104U) {
  2837. av_log(s->avctx, AV_LOG_ERROR,
  2838. "deblocking filter parameters %d %d out of range\n",
  2839. h->slice_alpha_c0_offset, h->slice_beta_offset);
  2840. return -1;
  2841. }
  2842. }
  2843. }
  2844. if (s->avctx->skip_loop_filter >= AVDISCARD_ALL ||
  2845. (s->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&
  2846. h->slice_type_nos != AV_PICTURE_TYPE_I) ||
  2847. (s->avctx->skip_loop_filter >= AVDISCARD_BIDIR &&
  2848. h->slice_type_nos == AV_PICTURE_TYPE_B) ||
  2849. (s->avctx->skip_loop_filter >= AVDISCARD_NONREF &&
  2850. h->nal_ref_idc == 0))
  2851. h->deblocking_filter = 0;
  2852. if (h->deblocking_filter == 1 && h0->max_contexts > 1) {
  2853. if (s->avctx->flags2 & CODEC_FLAG2_FAST) {
  2854. /* Cheat slightly for speed:
  2855. * Do not bother to deblock across slices. */
  2856. h->deblocking_filter = 2;
  2857. } else {
  2858. h0->max_contexts = 1;
  2859. if (!h0->single_decode_warning) {
  2860. av_log(s->avctx, AV_LOG_INFO,
  2861. "Cannot parallelize deblocking type 1, decoding such frames in sequential order\n");
  2862. h0->single_decode_warning = 1;
  2863. }
  2864. if (h != h0) {
  2865. av_log(h->s.avctx, AV_LOG_ERROR,
  2866. "Deblocking switched inside frame.\n");
  2867. return 1;
  2868. }
  2869. }
  2870. }
  2871. h->qp_thresh = 15 + 52 -
  2872. FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) -
  2873. FFMAX3(0,
  2874. h->pps.chroma_qp_index_offset[0],
  2875. h->pps.chroma_qp_index_offset[1]) +
  2876. 6 * (h->sps.bit_depth_luma - 8);
  2877. h0->last_slice_type = slice_type;
  2878. h->slice_num = ++h0->current_slice;
  2879. if (h->slice_num)
  2880. h0->slice_row[(h->slice_num-1)&(MAX_SLICES-1)]= s->resync_mb_y;
  2881. if ( h0->slice_row[h->slice_num&(MAX_SLICES-1)] + 3 >= s->resync_mb_y
  2882. && h0->slice_row[h->slice_num&(MAX_SLICES-1)] <= s->resync_mb_y
  2883. && h->slice_num >= MAX_SLICES) {
  2884. //in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case
  2885. 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);
  2886. }
  2887. for (j = 0; j < 2; j++) {
  2888. int id_list[16];
  2889. int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j];
  2890. for (i = 0; i < 16; i++) {
  2891. id_list[i] = 60;
  2892. if (h->ref_list[j][i].f.data[0]) {
  2893. int k;
  2894. uint8_t *base = h->ref_list[j][i].f.base[0];
  2895. for (k = 0; k < h->short_ref_count; k++)
  2896. if (h->short_ref[k]->f.base[0] == base) {
  2897. id_list[i] = k;
  2898. break;
  2899. }
  2900. for (k = 0; k < h->long_ref_count; k++)
  2901. if (h->long_ref[k] && h->long_ref[k]->f.base[0] == base) {
  2902. id_list[i] = h->short_ref_count + k;
  2903. break;
  2904. }
  2905. }
  2906. }
  2907. ref2frm[0] =
  2908. ref2frm[1] = -1;
  2909. for (i = 0; i < 16; i++)
  2910. ref2frm[i + 2] = 4 * id_list[i] +
  2911. (h->ref_list[j][i].f.reference & 3);
  2912. ref2frm[18 + 0] =
  2913. ref2frm[18 + 1] = -1;
  2914. for (i = 16; i < 48; i++)
  2915. ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +
  2916. (h->ref_list[j][i].f.reference & 3);
  2917. }
  2918. // FIXME: fix draw_edges + PAFF + frame threads
  2919. h->emu_edge_width = (s->flags & CODEC_FLAG_EMU_EDGE ||
  2920. (!h->sps.frame_mbs_only_flag &&
  2921. s->avctx->active_thread_type))
  2922. ? 0 : 16;
  2923. h->emu_edge_height = (FRAME_MBAFF || FIELD_PICTURE) ? 0 : h->emu_edge_width;
  2924. if (s->avctx->debug & FF_DEBUG_PICT_INFO) {
  2925. av_log(h->s.avctx, AV_LOG_DEBUG,
  2926. "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",
  2927. h->slice_num,
  2928. (s->picture_structure == PICT_FRAME ? "F" : s->picture_structure == PICT_TOP_FIELD ? "T" : "B"),
  2929. first_mb_in_slice,
  2930. av_get_picture_type_char(h->slice_type),
  2931. h->slice_type_fixed ? " fix" : "",
  2932. h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",
  2933. pps_id, h->frame_num,
  2934. s->current_picture_ptr->field_poc[0],
  2935. s->current_picture_ptr->field_poc[1],
  2936. h->ref_count[0], h->ref_count[1],
  2937. s->qscale,
  2938. h->deblocking_filter,
  2939. h->slice_alpha_c0_offset / 2 - 26, h->slice_beta_offset / 2 - 26,
  2940. h->use_weight,
  2941. h->use_weight == 1 && h->use_weight_chroma ? "c" : "",
  2942. h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");
  2943. }
  2944. return 0;
  2945. }
  2946. int ff_h264_get_slice_type(const H264Context *h)
  2947. {
  2948. switch (h->slice_type) {
  2949. case AV_PICTURE_TYPE_P:
  2950. return 0;
  2951. case AV_PICTURE_TYPE_B:
  2952. return 1;
  2953. case AV_PICTURE_TYPE_I:
  2954. return 2;
  2955. case AV_PICTURE_TYPE_SP:
  2956. return 3;
  2957. case AV_PICTURE_TYPE_SI:
  2958. return 4;
  2959. default:
  2960. return -1;
  2961. }
  2962. }
  2963. static av_always_inline void fill_filter_caches_inter(H264Context *h,
  2964. MpegEncContext *const s,
  2965. int mb_type, int top_xy,
  2966. int left_xy[LEFT_MBS],
  2967. int top_type,
  2968. int left_type[LEFT_MBS],
  2969. int mb_xy, int list)
  2970. {
  2971. int b_stride = h->b_stride;
  2972. int16_t(*mv_dst)[2] = &h->mv_cache[list][scan8[0]];
  2973. int8_t *ref_cache = &h->ref_cache[list][scan8[0]];
  2974. if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {
  2975. if (USES_LIST(top_type, list)) {
  2976. const int b_xy = h->mb2b_xy[top_xy] + 3 * b_stride;
  2977. const int b8_xy = 4 * top_xy + 2;
  2978. int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2));
  2979. AV_COPY128(mv_dst - 1 * 8, s->current_picture.f.motion_val[list][b_xy + 0]);
  2980. ref_cache[0 - 1 * 8] =
  2981. ref_cache[1 - 1 * 8] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 0]];
  2982. ref_cache[2 - 1 * 8] =
  2983. ref_cache[3 - 1 * 8] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 1]];
  2984. } else {
  2985. AV_ZERO128(mv_dst - 1 * 8);
  2986. AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  2987. }
  2988. if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {
  2989. if (USES_LIST(left_type[LTOP], list)) {
  2990. const int b_xy = h->mb2b_xy[left_xy[LTOP]] + 3;
  2991. const int b8_xy = 4 * left_xy[LTOP] + 1;
  2992. int (*ref2frm)[64] =(void*)( h->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2));
  2993. AV_COPY32(mv_dst - 1 + 0, s->current_picture.f.motion_val[list][b_xy + b_stride * 0]);
  2994. AV_COPY32(mv_dst - 1 + 8, s->current_picture.f.motion_val[list][b_xy + b_stride * 1]);
  2995. AV_COPY32(mv_dst - 1 + 16, s->current_picture.f.motion_val[list][b_xy + b_stride * 2]);
  2996. AV_COPY32(mv_dst - 1 + 24, s->current_picture.f.motion_val[list][b_xy + b_stride * 3]);
  2997. ref_cache[-1 + 0] =
  2998. ref_cache[-1 + 8] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 2 * 0]];
  2999. ref_cache[-1 + 16] =
  3000. ref_cache[-1 + 24] = ref2frm[list][s->current_picture.f.ref_index[list][b8_xy + 2 * 1]];
  3001. } else {
  3002. AV_ZERO32(mv_dst - 1 + 0);
  3003. AV_ZERO32(mv_dst - 1 + 8);
  3004. AV_ZERO32(mv_dst - 1 + 16);
  3005. AV_ZERO32(mv_dst - 1 + 24);
  3006. ref_cache[-1 + 0] =
  3007. ref_cache[-1 + 8] =
  3008. ref_cache[-1 + 16] =
  3009. ref_cache[-1 + 24] = LIST_NOT_USED;
  3010. }
  3011. }
  3012. }
  3013. if (!USES_LIST(mb_type, list)) {
  3014. fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);
  3015. AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  3016. AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  3017. AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  3018. AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);
  3019. return;
  3020. }
  3021. {
  3022. int8_t *ref = &s->current_picture.f.ref_index[list][4 * mb_xy];
  3023. int (*ref2frm)[64] = (void*)(h->ref2frm[h->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF ? 20 : 2));
  3024. uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]], ref2frm[list][ref[1]]) & 0x00FF00FF) * 0x0101;
  3025. uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]], ref2frm[list][ref[3]]) & 0x00FF00FF) * 0x0101;
  3026. AV_WN32A(&ref_cache[0 * 8], ref01);
  3027. AV_WN32A(&ref_cache[1 * 8], ref01);
  3028. AV_WN32A(&ref_cache[2 * 8], ref23);
  3029. AV_WN32A(&ref_cache[3 * 8], ref23);
  3030. }
  3031. {
  3032. int16_t(*mv_src)[2] = &s->current_picture.f.motion_val[list][4 * s->mb_x + 4 * s->mb_y * b_stride];
  3033. AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);
  3034. AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);
  3035. AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);
  3036. AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);
  3037. }
  3038. }
  3039. /**
  3040. *
  3041. * @return non zero if the loop filter can be skipped
  3042. */
  3043. static int fill_filter_caches(H264Context *h, int mb_type)
  3044. {
  3045. MpegEncContext *const s = &h->s;
  3046. const int mb_xy = h->mb_xy;
  3047. int top_xy, left_xy[LEFT_MBS];
  3048. int top_type, left_type[LEFT_MBS];
  3049. uint8_t *nnz;
  3050. uint8_t *nnz_cache;
  3051. top_xy = mb_xy - (s->mb_stride << MB_FIELD);
  3052. /* Wow, what a mess, why didn't they simplify the interlacing & intra
  3053. * stuff, I can't imagine that these complex rules are worth it. */
  3054. left_xy[LBOT] = left_xy[LTOP] = mb_xy - 1;
  3055. if (FRAME_MBAFF) {
  3056. const int left_mb_field_flag = IS_INTERLACED(s->current_picture.f.mb_type[mb_xy - 1]);
  3057. const int curr_mb_field_flag = IS_INTERLACED(mb_type);
  3058. if (s->mb_y & 1) {
  3059. if (left_mb_field_flag != curr_mb_field_flag)
  3060. left_xy[LTOP] -= s->mb_stride;
  3061. } else {
  3062. if (curr_mb_field_flag)
  3063. top_xy += s->mb_stride &
  3064. (((s->current_picture.f.mb_type[top_xy] >> 7) & 1) - 1);
  3065. if (left_mb_field_flag != curr_mb_field_flag)
  3066. left_xy[LBOT] += s->mb_stride;
  3067. }
  3068. }
  3069. h->top_mb_xy = top_xy;
  3070. h->left_mb_xy[LTOP] = left_xy[LTOP];
  3071. h->left_mb_xy[LBOT] = left_xy[LBOT];
  3072. {
  3073. /* For sufficiently low qp, filtering wouldn't do anything.
  3074. * This is a conservative estimate: could also check beta_offset
  3075. * and more accurate chroma_qp. */
  3076. int qp_thresh = h->qp_thresh; // FIXME strictly we should store qp_thresh for each mb of a slice
  3077. int qp = s->current_picture.f.qscale_table[mb_xy];
  3078. if (qp <= qp_thresh &&
  3079. (left_xy[LTOP] < 0 ||
  3080. ((qp + s->current_picture.f.qscale_table[left_xy[LTOP]] + 1) >> 1) <= qp_thresh) &&
  3081. (top_xy < 0 ||
  3082. ((qp + s->current_picture.f.qscale_table[top_xy] + 1) >> 1) <= qp_thresh)) {
  3083. if (!FRAME_MBAFF)
  3084. return 1;
  3085. if ((left_xy[LTOP] < 0 ||
  3086. ((qp + s->current_picture.f.qscale_table[left_xy[LBOT]] + 1) >> 1) <= qp_thresh) &&
  3087. (top_xy < s->mb_stride ||
  3088. ((qp + s->current_picture.f.qscale_table[top_xy - s->mb_stride] + 1) >> 1) <= qp_thresh))
  3089. return 1;
  3090. }
  3091. }
  3092. top_type = s->current_picture.f.mb_type[top_xy];
  3093. left_type[LTOP] = s->current_picture.f.mb_type[left_xy[LTOP]];
  3094. left_type[LBOT] = s->current_picture.f.mb_type[left_xy[LBOT]];
  3095. if (h->deblocking_filter == 2) {
  3096. if (h->slice_table[top_xy] != h->slice_num)
  3097. top_type = 0;
  3098. if (h->slice_table[left_xy[LBOT]] != h->slice_num)
  3099. left_type[LTOP] = left_type[LBOT] = 0;
  3100. } else {
  3101. if (h->slice_table[top_xy] == 0xFFFF)
  3102. top_type = 0;
  3103. if (h->slice_table[left_xy[LBOT]] == 0xFFFF)
  3104. left_type[LTOP] = left_type[LBOT] = 0;
  3105. }
  3106. h->top_type = top_type;
  3107. h->left_type[LTOP] = left_type[LTOP];
  3108. h->left_type[LBOT] = left_type[LBOT];
  3109. if (IS_INTRA(mb_type))
  3110. return 0;
  3111. fill_filter_caches_inter(h, s, mb_type, top_xy, left_xy,
  3112. top_type, left_type, mb_xy, 0);
  3113. if (h->list_count == 2)
  3114. fill_filter_caches_inter(h, s, mb_type, top_xy, left_xy,
  3115. top_type, left_type, mb_xy, 1);
  3116. nnz = h->non_zero_count[mb_xy];
  3117. nnz_cache = h->non_zero_count_cache;
  3118. AV_COPY32(&nnz_cache[4 + 8 * 1], &nnz[0]);
  3119. AV_COPY32(&nnz_cache[4 + 8 * 2], &nnz[4]);
  3120. AV_COPY32(&nnz_cache[4 + 8 * 3], &nnz[8]);
  3121. AV_COPY32(&nnz_cache[4 + 8 * 4], &nnz[12]);
  3122. h->cbp = h->cbp_table[mb_xy];
  3123. if (top_type) {
  3124. nnz = h->non_zero_count[top_xy];
  3125. AV_COPY32(&nnz_cache[4 + 8 * 0], &nnz[3 * 4]);
  3126. }
  3127. if (left_type[LTOP]) {
  3128. nnz = h->non_zero_count[left_xy[LTOP]];
  3129. nnz_cache[3 + 8 * 1] = nnz[3 + 0 * 4];
  3130. nnz_cache[3 + 8 * 2] = nnz[3 + 1 * 4];
  3131. nnz_cache[3 + 8 * 3] = nnz[3 + 2 * 4];
  3132. nnz_cache[3 + 8 * 4] = nnz[3 + 3 * 4];
  3133. }
  3134. /* CAVLC 8x8dct requires NNZ values for residual decoding that differ
  3135. * from what the loop filter needs */
  3136. if (!CABAC && h->pps.transform_8x8_mode) {
  3137. if (IS_8x8DCT(top_type)) {
  3138. nnz_cache[4 + 8 * 0] =
  3139. nnz_cache[5 + 8 * 0] = (h->cbp_table[top_xy] & 0x4000) >> 12;
  3140. nnz_cache[6 + 8 * 0] =
  3141. nnz_cache[7 + 8 * 0] = (h->cbp_table[top_xy] & 0x8000) >> 12;
  3142. }
  3143. if (IS_8x8DCT(left_type[LTOP])) {
  3144. nnz_cache[3 + 8 * 1] =
  3145. nnz_cache[3 + 8 * 2] = (h->cbp_table[left_xy[LTOP]] & 0x2000) >> 12; // FIXME check MBAFF
  3146. }
  3147. if (IS_8x8DCT(left_type[LBOT])) {
  3148. nnz_cache[3 + 8 * 3] =
  3149. nnz_cache[3 + 8 * 4] = (h->cbp_table[left_xy[LBOT]] & 0x8000) >> 12; // FIXME check MBAFF
  3150. }
  3151. if (IS_8x8DCT(mb_type)) {
  3152. nnz_cache[scan8[0]] =
  3153. nnz_cache[scan8[1]] =
  3154. nnz_cache[scan8[2]] =
  3155. nnz_cache[scan8[3]] = (h->cbp & 0x1000) >> 12;
  3156. nnz_cache[scan8[0 + 4]] =
  3157. nnz_cache[scan8[1 + 4]] =
  3158. nnz_cache[scan8[2 + 4]] =
  3159. nnz_cache[scan8[3 + 4]] = (h->cbp & 0x2000) >> 12;
  3160. nnz_cache[scan8[0 + 8]] =
  3161. nnz_cache[scan8[1 + 8]] =
  3162. nnz_cache[scan8[2 + 8]] =
  3163. nnz_cache[scan8[3 + 8]] = (h->cbp & 0x4000) >> 12;
  3164. nnz_cache[scan8[0 + 12]] =
  3165. nnz_cache[scan8[1 + 12]] =
  3166. nnz_cache[scan8[2 + 12]] =
  3167. nnz_cache[scan8[3 + 12]] = (h->cbp & 0x8000) >> 12;
  3168. }
  3169. }
  3170. return 0;
  3171. }
  3172. static void loop_filter(H264Context *h, int start_x, int end_x)
  3173. {
  3174. MpegEncContext *const s = &h->s;
  3175. uint8_t *dest_y, *dest_cb, *dest_cr;
  3176. int linesize, uvlinesize, mb_x, mb_y;
  3177. const int end_mb_y = s->mb_y + FRAME_MBAFF;
  3178. const int old_slice_type = h->slice_type;
  3179. const int pixel_shift = h->pixel_shift;
  3180. const int block_h = 16 >> s->chroma_y_shift;
  3181. if (h->deblocking_filter) {
  3182. for (mb_x = start_x; mb_x < end_x; mb_x++)
  3183. for (mb_y = end_mb_y - FRAME_MBAFF; mb_y <= end_mb_y; mb_y++) {
  3184. int mb_xy, mb_type;
  3185. mb_xy = h->mb_xy = mb_x + mb_y * s->mb_stride;
  3186. h->slice_num = h->slice_table[mb_xy];
  3187. mb_type = s->current_picture.f.mb_type[mb_xy];
  3188. h->list_count = h->list_counts[mb_xy];
  3189. if (FRAME_MBAFF)
  3190. h->mb_mbaff =
  3191. h->mb_field_decoding_flag = !!IS_INTERLACED(mb_type);
  3192. s->mb_x = mb_x;
  3193. s->mb_y = mb_y;
  3194. dest_y = s->current_picture.f.data[0] +
  3195. ((mb_x << pixel_shift) + mb_y * s->linesize) * 16;
  3196. dest_cb = s->current_picture.f.data[1] +
  3197. (mb_x << pixel_shift) * (8 << CHROMA444) +
  3198. mb_y * s->uvlinesize * block_h;
  3199. dest_cr = s->current_picture.f.data[2] +
  3200. (mb_x << pixel_shift) * (8 << CHROMA444) +
  3201. mb_y * s->uvlinesize * block_h;
  3202. // FIXME simplify above
  3203. if (MB_FIELD) {
  3204. linesize = h->mb_linesize = s->linesize * 2;
  3205. uvlinesize = h->mb_uvlinesize = s->uvlinesize * 2;
  3206. if (mb_y & 1) { // FIXME move out of this function?
  3207. dest_y -= s->linesize * 15;
  3208. dest_cb -= s->uvlinesize * (block_h - 1);
  3209. dest_cr -= s->uvlinesize * (block_h - 1);
  3210. }
  3211. } else {
  3212. linesize = h->mb_linesize = s->linesize;
  3213. uvlinesize = h->mb_uvlinesize = s->uvlinesize;
  3214. }
  3215. backup_mb_border(h, dest_y, dest_cb, dest_cr, linesize,
  3216. uvlinesize, 0);
  3217. if (fill_filter_caches(h, mb_type))
  3218. continue;
  3219. h->chroma_qp[0] = get_chroma_qp(h, 0, s->current_picture.f.qscale_table[mb_xy]);
  3220. h->chroma_qp[1] = get_chroma_qp(h, 1, s->current_picture.f.qscale_table[mb_xy]);
  3221. if (FRAME_MBAFF) {
  3222. ff_h264_filter_mb(h, mb_x, mb_y, dest_y, dest_cb, dest_cr,
  3223. linesize, uvlinesize);
  3224. } else {
  3225. ff_h264_filter_mb_fast(h, mb_x, mb_y, dest_y, dest_cb,
  3226. dest_cr, linesize, uvlinesize);
  3227. }
  3228. }
  3229. }
  3230. h->slice_type = old_slice_type;
  3231. s->mb_x = end_x;
  3232. s->mb_y = end_mb_y - FRAME_MBAFF;
  3233. h->chroma_qp[0] = get_chroma_qp(h, 0, s->qscale);
  3234. h->chroma_qp[1] = get_chroma_qp(h, 1, s->qscale);
  3235. }
  3236. static void predict_field_decoding_flag(H264Context *h)
  3237. {
  3238. MpegEncContext *const s = &h->s;
  3239. const int mb_xy = s->mb_x + s->mb_y * s->mb_stride;
  3240. int mb_type = (h->slice_table[mb_xy - 1] == h->slice_num) ?
  3241. s->current_picture.f.mb_type[mb_xy - 1] :
  3242. (h->slice_table[mb_xy - s->mb_stride] == h->slice_num) ?
  3243. s->current_picture.f.mb_type[mb_xy - s->mb_stride] : 0;
  3244. h->mb_mbaff = h->mb_field_decoding_flag = IS_INTERLACED(mb_type) ? 1 : 0;
  3245. }
  3246. /**
  3247. * Draw edges and report progress for the last MB row.
  3248. */
  3249. static void decode_finish_row(H264Context *h)
  3250. {
  3251. MpegEncContext *const s = &h->s;
  3252. int top = 16 * (s->mb_y >> FIELD_PICTURE);
  3253. int pic_height = 16 * s->mb_height >> FIELD_PICTURE;
  3254. int height = 16 << FRAME_MBAFF;
  3255. int deblock_border = (16 + 4) << FRAME_MBAFF;
  3256. if (h->deblocking_filter) {
  3257. if ((top + height) >= pic_height)
  3258. height += deblock_border;
  3259. top -= deblock_border;
  3260. }
  3261. if (top >= pic_height || (top + height) < h->emu_edge_height)
  3262. return;
  3263. height = FFMIN(height, pic_height - top);
  3264. if (top < h->emu_edge_height) {
  3265. height = top + height;
  3266. top = 0;
  3267. }
  3268. ff_draw_horiz_band(s, top, height);
  3269. if (s->droppable)
  3270. return;
  3271. ff_thread_report_progress(&s->current_picture_ptr->f, top + height - 1,
  3272. s->picture_structure == PICT_BOTTOM_FIELD);
  3273. }
  3274. static int decode_slice(struct AVCodecContext *avctx, void *arg)
  3275. {
  3276. H264Context *h = *(void **)arg;
  3277. MpegEncContext *const s = &h->s;
  3278. const int part_mask = s->partitioned_frame ? (ER_AC_END | ER_AC_ERROR)
  3279. : 0x7F;
  3280. int lf_x_start = s->mb_x;
  3281. s->mb_skip_run = -1;
  3282. h->is_complex = FRAME_MBAFF || s->picture_structure != PICT_FRAME ||
  3283. s->codec_id != AV_CODEC_ID_H264 ||
  3284. (CONFIG_GRAY && (s->flags & CODEC_FLAG_GRAY));
  3285. if (h->pps.cabac) {
  3286. /* realign */
  3287. align_get_bits(&s->gb);
  3288. /* init cabac */
  3289. ff_init_cabac_decoder(&h->cabac,
  3290. s->gb.buffer + get_bits_count(&s->gb) / 8,
  3291. (get_bits_left(&s->gb) + 7) / 8);
  3292. ff_h264_init_cabac_states(h);
  3293. for (;;) {
  3294. // START_TIMER
  3295. int ret = ff_h264_decode_mb_cabac(h);
  3296. int eos;
  3297. // STOP_TIMER("decode_mb_cabac")
  3298. if (ret >= 0)
  3299. ff_h264_hl_decode_mb(h);
  3300. // FIXME optimal? or let mb_decode decode 16x32 ?
  3301. if (ret >= 0 && FRAME_MBAFF) {
  3302. s->mb_y++;
  3303. ret = ff_h264_decode_mb_cabac(h);
  3304. if (ret >= 0)
  3305. ff_h264_hl_decode_mb(h);
  3306. s->mb_y--;
  3307. }
  3308. eos = get_cabac_terminate(&h->cabac);
  3309. if ((s->workaround_bugs & FF_BUG_TRUNCATED) &&
  3310. h->cabac.bytestream > h->cabac.bytestream_end + 2) {
  3311. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x - 1,
  3312. s->mb_y, ER_MB_END & part_mask);
  3313. if (s->mb_x >= lf_x_start)
  3314. loop_filter(h, lf_x_start, s->mb_x + 1);
  3315. return 0;
  3316. }
  3317. if (h->cabac.bytestream > h->cabac.bytestream_end + 2 )
  3318. av_log(h->s.avctx, AV_LOG_DEBUG, "bytestream overread %td\n", h->cabac.bytestream_end - h->cabac.bytestream);
  3319. if (ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 4) {
  3320. av_log(h->s.avctx, AV_LOG_ERROR,
  3321. "error while decoding MB %d %d, bytestream (%td)\n",
  3322. s->mb_x, s->mb_y,
  3323. h->cabac.bytestream_end - h->cabac.bytestream);
  3324. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x,
  3325. s->mb_y, ER_MB_ERROR & part_mask);
  3326. return -1;
  3327. }
  3328. if (++s->mb_x >= s->mb_width) {
  3329. loop_filter(h, lf_x_start, s->mb_x);
  3330. s->mb_x = lf_x_start = 0;
  3331. decode_finish_row(h);
  3332. ++s->mb_y;
  3333. if (FIELD_OR_MBAFF_PICTURE) {
  3334. ++s->mb_y;
  3335. if (FRAME_MBAFF && s->mb_y < s->mb_height)
  3336. predict_field_decoding_flag(h);
  3337. }
  3338. }
  3339. if (eos || s->mb_y >= s->mb_height) {
  3340. tprintf(s->avctx, "slice end %d %d\n",
  3341. get_bits_count(&s->gb), s->gb.size_in_bits);
  3342. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x - 1,
  3343. s->mb_y, ER_MB_END & part_mask);
  3344. if (s->mb_x > lf_x_start)
  3345. loop_filter(h, lf_x_start, s->mb_x);
  3346. return 0;
  3347. }
  3348. }
  3349. } else {
  3350. for (;;) {
  3351. int ret = ff_h264_decode_mb_cavlc(h);
  3352. if (ret >= 0)
  3353. ff_h264_hl_decode_mb(h);
  3354. // FIXME optimal? or let mb_decode decode 16x32 ?
  3355. if (ret >= 0 && FRAME_MBAFF) {
  3356. s->mb_y++;
  3357. ret = ff_h264_decode_mb_cavlc(h);
  3358. if (ret >= 0)
  3359. ff_h264_hl_decode_mb(h);
  3360. s->mb_y--;
  3361. }
  3362. if (ret < 0) {
  3363. av_log(h->s.avctx, AV_LOG_ERROR,
  3364. "error while decoding MB %d %d\n", s->mb_x, s->mb_y);
  3365. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x,
  3366. s->mb_y, ER_MB_ERROR & part_mask);
  3367. return -1;
  3368. }
  3369. if (++s->mb_x >= s->mb_width) {
  3370. loop_filter(h, lf_x_start, s->mb_x);
  3371. s->mb_x = lf_x_start = 0;
  3372. decode_finish_row(h);
  3373. ++s->mb_y;
  3374. if (FIELD_OR_MBAFF_PICTURE) {
  3375. ++s->mb_y;
  3376. if (FRAME_MBAFF && s->mb_y < s->mb_height)
  3377. predict_field_decoding_flag(h);
  3378. }
  3379. if (s->mb_y >= s->mb_height) {
  3380. tprintf(s->avctx, "slice end %d %d\n",
  3381. get_bits_count(&s->gb), s->gb.size_in_bits);
  3382. if ( get_bits_left(&s->gb) == 0
  3383. || get_bits_left(&s->gb) > 0 && !(s->avctx->err_recognition & AV_EF_AGGRESSIVE)) {
  3384. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y,
  3385. s->mb_x - 1, s->mb_y,
  3386. ER_MB_END & part_mask);
  3387. return 0;
  3388. } else {
  3389. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y,
  3390. s->mb_x, s->mb_y,
  3391. ER_MB_END & part_mask);
  3392. return -1;
  3393. }
  3394. }
  3395. }
  3396. if (get_bits_left(&s->gb) <= 0 && s->mb_skip_run <= 0) {
  3397. tprintf(s->avctx, "slice end %d %d\n",
  3398. get_bits_count(&s->gb), s->gb.size_in_bits);
  3399. if (get_bits_left(&s->gb) == 0) {
  3400. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y,
  3401. s->mb_x - 1, s->mb_y,
  3402. ER_MB_END & part_mask);
  3403. if (s->mb_x > lf_x_start)
  3404. loop_filter(h, lf_x_start, s->mb_x);
  3405. return 0;
  3406. } else {
  3407. ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x,
  3408. s->mb_y, ER_MB_ERROR & part_mask);
  3409. return -1;
  3410. }
  3411. }
  3412. }
  3413. }
  3414. }
  3415. /**
  3416. * Call decode_slice() for each context.
  3417. *
  3418. * @param h h264 master context
  3419. * @param context_count number of contexts to execute
  3420. */
  3421. static int execute_decode_slices(H264Context *h, int context_count)
  3422. {
  3423. MpegEncContext *const s = &h->s;
  3424. AVCodecContext *const avctx = s->avctx;
  3425. H264Context *hx;
  3426. int i;
  3427. if (s->avctx->hwaccel ||
  3428. s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  3429. return 0;
  3430. if (context_count == 1) {
  3431. return decode_slice(avctx, &h);
  3432. } else {
  3433. for (i = 1; i < context_count; i++) {
  3434. hx = h->thread_context[i];
  3435. hx->s.err_recognition = avctx->err_recognition;
  3436. hx->s.error_count = 0;
  3437. hx->x264_build = h->x264_build;
  3438. }
  3439. avctx->execute(avctx, decode_slice, h->thread_context,
  3440. NULL, context_count, sizeof(void *));
  3441. /* pull back stuff from slices to master context */
  3442. hx = h->thread_context[context_count - 1];
  3443. s->mb_x = hx->s.mb_x;
  3444. s->mb_y = hx->s.mb_y;
  3445. s->droppable = hx->s.droppable;
  3446. s->picture_structure = hx->s.picture_structure;
  3447. for (i = 1; i < context_count; i++)
  3448. h->s.error_count += h->thread_context[i]->s.error_count;
  3449. }
  3450. return 0;
  3451. }
  3452. static int decode_nal_units(H264Context *h, const uint8_t *buf, int buf_size,
  3453. int parse_extradata)
  3454. {
  3455. MpegEncContext *const s = &h->s;
  3456. AVCodecContext *const avctx = s->avctx;
  3457. H264Context *hx; ///< thread context
  3458. int buf_index;
  3459. int context_count;
  3460. int next_avc;
  3461. int pass = !(avctx->active_thread_type & FF_THREAD_FRAME);
  3462. int nals_needed = 0; ///< number of NALs that need decoding before the next frame thread starts
  3463. int nal_index;
  3464. int idr_cleared=0;
  3465. int first_slice = 0;
  3466. h->nal_unit_type= 0;
  3467. if(!s->slice_context_count)
  3468. s->slice_context_count= 1;
  3469. h->max_contexts = s->slice_context_count;
  3470. if (!(s->flags2 & CODEC_FLAG2_CHUNKS)) {
  3471. h->current_slice = 0;
  3472. if (!s->first_field)
  3473. s->current_picture_ptr = NULL;
  3474. ff_h264_reset_sei(h);
  3475. }
  3476. if (h->nal_length_size == 4) {
  3477. if (buf_size > 8 && AV_RB32(buf) == 1 && AV_RB32(buf+5) > (unsigned)buf_size) {
  3478. h->is_avc = 0;
  3479. }else if(buf_size > 3 && AV_RB32(buf) > 1 && AV_RB32(buf) <= (unsigned)buf_size)
  3480. h->is_avc = 1;
  3481. }
  3482. for (; pass <= 1; pass++) {
  3483. buf_index = 0;
  3484. context_count = 0;
  3485. next_avc = h->is_avc ? 0 : buf_size;
  3486. nal_index = 0;
  3487. for (;;) {
  3488. int consumed;
  3489. int dst_length;
  3490. int bit_length;
  3491. const uint8_t *ptr;
  3492. int i, nalsize = 0;
  3493. int err;
  3494. if (buf_index >= next_avc) {
  3495. if (buf_index >= buf_size - h->nal_length_size)
  3496. break;
  3497. nalsize = 0;
  3498. for (i = 0; i < h->nal_length_size; i++)
  3499. nalsize = (nalsize << 8) | buf[buf_index++];
  3500. if (nalsize <= 0 || nalsize > buf_size - buf_index) {
  3501. av_log(h->s.avctx, AV_LOG_ERROR,
  3502. "AVC: nal size %d\n", nalsize);
  3503. break;
  3504. }
  3505. next_avc = buf_index + nalsize;
  3506. } else {
  3507. // start code prefix search
  3508. for (; buf_index + 3 < next_avc; buf_index++)
  3509. // This should always succeed in the first iteration.
  3510. if (buf[buf_index] == 0 &&
  3511. buf[buf_index + 1] == 0 &&
  3512. buf[buf_index + 2] == 1)
  3513. break;
  3514. if (buf_index + 3 >= buf_size) {
  3515. buf_index = buf_size;
  3516. break;
  3517. }
  3518. buf_index += 3;
  3519. if (buf_index >= next_avc)
  3520. continue;
  3521. }
  3522. hx = h->thread_context[context_count];
  3523. ptr = ff_h264_decode_nal(hx, buf + buf_index, &dst_length,
  3524. &consumed, next_avc - buf_index);
  3525. if (ptr == NULL || dst_length < 0) {
  3526. buf_index = -1;
  3527. goto end;
  3528. }
  3529. i = buf_index + consumed;
  3530. if ((s->workaround_bugs & FF_BUG_AUTODETECT) && i + 3 < next_avc &&
  3531. buf[i] == 0x00 && buf[i + 1] == 0x00 &&
  3532. buf[i + 2] == 0x01 && buf[i + 3] == 0xE0)
  3533. s->workaround_bugs |= FF_BUG_TRUNCATED;
  3534. if (!(s->workaround_bugs & FF_BUG_TRUNCATED))
  3535. while(dst_length > 0 && ptr[dst_length - 1] == 0)
  3536. dst_length--;
  3537. bit_length = !dst_length ? 0
  3538. : (8 * dst_length -
  3539. decode_rbsp_trailing(h, ptr + dst_length - 1));
  3540. if (s->avctx->debug & FF_DEBUG_STARTCODE)
  3541. 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);
  3542. if (h->is_avc && (nalsize != consumed) && nalsize)
  3543. av_log(h->s.avctx, AV_LOG_DEBUG,
  3544. "AVC: Consumed only %d bytes instead of %d\n",
  3545. consumed, nalsize);
  3546. buf_index += consumed;
  3547. nal_index++;
  3548. if (pass == 0) {
  3549. /* packets can sometimes contain multiple PPS/SPS,
  3550. * e.g. two PAFF field pictures in one packet, or a demuxer
  3551. * which splits NALs strangely if so, when frame threading we
  3552. * can't start the next thread until we've read all of them */
  3553. switch (hx->nal_unit_type) {
  3554. case NAL_SPS:
  3555. case NAL_PPS:
  3556. nals_needed = nal_index;
  3557. break;
  3558. case NAL_DPA:
  3559. case NAL_IDR_SLICE:
  3560. case NAL_SLICE:
  3561. init_get_bits(&hx->s.gb, ptr, bit_length);
  3562. if (!get_ue_golomb(&hx->s.gb) || !first_slice)
  3563. nals_needed = nal_index;
  3564. if (!first_slice)
  3565. first_slice = hx->nal_unit_type;
  3566. }
  3567. continue;
  3568. }
  3569. if (!first_slice)
  3570. switch (hx->nal_unit_type) {
  3571. case NAL_DPA:
  3572. case NAL_IDR_SLICE:
  3573. case NAL_SLICE:
  3574. first_slice = hx->nal_unit_type;
  3575. }
  3576. // FIXME do not discard SEI id
  3577. if (avctx->skip_frame >= AVDISCARD_NONREF && h->nal_ref_idc == 0)
  3578. continue;
  3579. again:
  3580. /* Ignore per frame NAL unit type during extradata
  3581. * parsing. Decoding slices is not possible in codec init
  3582. * with frame-mt */
  3583. if (parse_extradata) {
  3584. switch (hx->nal_unit_type) {
  3585. case NAL_IDR_SLICE:
  3586. case NAL_SLICE:
  3587. case NAL_DPA:
  3588. case NAL_DPB:
  3589. case NAL_DPC:
  3590. case NAL_AUXILIARY_SLICE:
  3591. av_log(h->s.avctx, AV_LOG_WARNING, "Ignoring NAL %d in global header/extradata\n", hx->nal_unit_type);
  3592. hx->nal_unit_type = NAL_FF_IGNORE;
  3593. }
  3594. }
  3595. err = 0;
  3596. switch (hx->nal_unit_type) {
  3597. case NAL_IDR_SLICE:
  3598. if (first_slice != NAL_IDR_SLICE) {
  3599. av_log(h->s.avctx, AV_LOG_ERROR,
  3600. "Invalid mix of idr and non-idr slices\n");
  3601. buf_index = -1;
  3602. goto end;
  3603. }
  3604. if(!idr_cleared)
  3605. idr(h); // FIXME ensure we don't lose some frames if there is reordering
  3606. idr_cleared = 1;
  3607. case NAL_SLICE:
  3608. init_get_bits(&hx->s.gb, ptr, bit_length);
  3609. hx->intra_gb_ptr =
  3610. hx->inter_gb_ptr = &hx->s.gb;
  3611. hx->s.data_partitioning = 0;
  3612. if ((err = decode_slice_header(hx, h)))
  3613. break;
  3614. if (h->sei_recovery_frame_cnt >= 0 && (h->frame_num != h->sei_recovery_frame_cnt || hx->slice_type_nos != AV_PICTURE_TYPE_I))
  3615. h->valid_recovery_point = 1;
  3616. if ( h->sei_recovery_frame_cnt >= 0
  3617. && ( h->recovery_frame<0
  3618. || ((h->recovery_frame - h->frame_num) & ((1 << h->sps.log2_max_frame_num)-1)) > h->sei_recovery_frame_cnt)) {
  3619. h->recovery_frame = (h->frame_num + h->sei_recovery_frame_cnt) %
  3620. (1 << h->sps.log2_max_frame_num);
  3621. if (!h->valid_recovery_point)
  3622. h->recovery_frame = h->frame_num;
  3623. }
  3624. s->current_picture_ptr->f.key_frame |=
  3625. (hx->nal_unit_type == NAL_IDR_SLICE);
  3626. if (h->recovery_frame == h->frame_num) {
  3627. s->current_picture_ptr->sync |= 1;
  3628. h->recovery_frame = -1;
  3629. }
  3630. h->sync |= !!s->current_picture_ptr->f.key_frame;
  3631. h->sync |= 3*!!(s->flags2 & CODEC_FLAG2_SHOW_ALL);
  3632. s->current_picture_ptr->sync |= h->sync;
  3633. if (h->current_slice == 1) {
  3634. if (!(s->flags2 & CODEC_FLAG2_CHUNKS))
  3635. decode_postinit(h, nal_index >= nals_needed);
  3636. if (s->avctx->hwaccel &&
  3637. s->avctx->hwaccel->start_frame(s->avctx, NULL, 0) < 0)
  3638. return -1;
  3639. if (CONFIG_H264_VDPAU_DECODER &&
  3640. s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)
  3641. ff_vdpau_h264_picture_start(s);
  3642. }
  3643. if (hx->redundant_pic_count == 0 &&
  3644. (avctx->skip_frame < AVDISCARD_NONREF ||
  3645. hx->nal_ref_idc) &&
  3646. (avctx->skip_frame < AVDISCARD_BIDIR ||
  3647. hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
  3648. (avctx->skip_frame < AVDISCARD_NONKEY ||
  3649. hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
  3650. avctx->skip_frame < AVDISCARD_ALL) {
  3651. if (avctx->hwaccel) {
  3652. if (avctx->hwaccel->decode_slice(avctx,
  3653. &buf[buf_index - consumed],
  3654. consumed) < 0)
  3655. return -1;
  3656. } else if (CONFIG_H264_VDPAU_DECODER &&
  3657. s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {
  3658. static const uint8_t start_code[] = {
  3659. 0x00, 0x00, 0x01 };
  3660. ff_vdpau_add_data_chunk(s, start_code,
  3661. sizeof(start_code));
  3662. ff_vdpau_add_data_chunk(s, &buf[buf_index - consumed],
  3663. consumed);
  3664. } else
  3665. context_count++;
  3666. }
  3667. break;
  3668. case NAL_DPA:
  3669. init_get_bits(&hx->s.gb, ptr, bit_length);
  3670. hx->intra_gb_ptr =
  3671. hx->inter_gb_ptr = NULL;
  3672. if ((err = decode_slice_header(hx, h)) < 0)
  3673. break;
  3674. hx->s.data_partitioning = 1;
  3675. break;
  3676. case NAL_DPB:
  3677. init_get_bits(&hx->intra_gb, ptr, bit_length);
  3678. hx->intra_gb_ptr = &hx->intra_gb;
  3679. break;
  3680. case NAL_DPC:
  3681. init_get_bits(&hx->inter_gb, ptr, bit_length);
  3682. hx->inter_gb_ptr = &hx->inter_gb;
  3683. av_log(h->s.avctx, AV_LOG_ERROR, "Partitioned H.264 support is incomplete\n");
  3684. break;
  3685. if (hx->redundant_pic_count == 0 &&
  3686. hx->intra_gb_ptr &&
  3687. hx->s.data_partitioning &&
  3688. s->current_picture_ptr &&
  3689. s->context_initialized &&
  3690. (avctx->skip_frame < AVDISCARD_NONREF || hx->nal_ref_idc) &&
  3691. (avctx->skip_frame < AVDISCARD_BIDIR ||
  3692. hx->slice_type_nos != AV_PICTURE_TYPE_B) &&
  3693. (avctx->skip_frame < AVDISCARD_NONKEY ||
  3694. hx->slice_type_nos == AV_PICTURE_TYPE_I) &&
  3695. avctx->skip_frame < AVDISCARD_ALL)
  3696. context_count++;
  3697. break;
  3698. case NAL_SEI:
  3699. init_get_bits(&s->gb, ptr, bit_length);
  3700. ff_h264_decode_sei(h);
  3701. break;
  3702. case NAL_SPS:
  3703. init_get_bits(&s->gb, ptr, bit_length);
  3704. if (ff_h264_decode_seq_parameter_set(h) < 0 && (h->is_avc ? (nalsize != consumed) && nalsize : 1)) {
  3705. av_log(h->s.avctx, AV_LOG_DEBUG,
  3706. "SPS decoding failure, trying again with the complete NAL\n");
  3707. if (h->is_avc)
  3708. av_assert0(next_avc - buf_index + consumed == nalsize);
  3709. if ((next_avc - buf_index + consumed - 1) >= INT_MAX/8)
  3710. break;
  3711. init_get_bits(&s->gb, &buf[buf_index + 1 - consumed],
  3712. 8*(next_avc - buf_index + consumed - 1));
  3713. ff_h264_decode_seq_parameter_set(h);
  3714. }
  3715. break;
  3716. case NAL_PPS:
  3717. init_get_bits(&s->gb, ptr, bit_length);
  3718. ff_h264_decode_picture_parameter_set(h, bit_length);
  3719. break;
  3720. case NAL_AUD:
  3721. case NAL_END_SEQUENCE:
  3722. case NAL_END_STREAM:
  3723. case NAL_FILLER_DATA:
  3724. case NAL_SPS_EXT:
  3725. case NAL_AUXILIARY_SLICE:
  3726. break;
  3727. case NAL_FF_IGNORE:
  3728. break;
  3729. default:
  3730. av_log(avctx, AV_LOG_DEBUG, "Unknown NAL code: %d (%d bits)\n",
  3731. hx->nal_unit_type, bit_length);
  3732. }
  3733. if (context_count == h->max_contexts) {
  3734. execute_decode_slices(h, context_count);
  3735. context_count = 0;
  3736. }
  3737. if (err < 0)
  3738. av_log(h->s.avctx, AV_LOG_ERROR, "decode_slice_header error\n");
  3739. else if (err == 1) {
  3740. /* Slice could not be decoded in parallel mode, copy down
  3741. * NAL unit stuff to context 0 and restart. Note that
  3742. * rbsp_buffer is not transferred, but since we no longer
  3743. * run in parallel mode this should not be an issue. */
  3744. h->nal_unit_type = hx->nal_unit_type;
  3745. h->nal_ref_idc = hx->nal_ref_idc;
  3746. hx = h;
  3747. goto again;
  3748. }
  3749. }
  3750. }
  3751. if (context_count)
  3752. execute_decode_slices(h, context_count);
  3753. end:
  3754. /* clean up */
  3755. if (s->current_picture_ptr && s->current_picture_ptr->owner2 == s &&
  3756. !s->droppable) {
  3757. ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX,
  3758. s->picture_structure == PICT_BOTTOM_FIELD);
  3759. }
  3760. return buf_index;
  3761. }
  3762. /**
  3763. * Return the number of bytes consumed for building the current frame.
  3764. */
  3765. static int get_consumed_bytes(MpegEncContext *s, int pos, int buf_size)
  3766. {
  3767. if (pos == 0)
  3768. pos = 1; // avoid infinite loops (i doubt that is needed but ...)
  3769. if (pos + 10 > buf_size)
  3770. pos = buf_size; // oops ;)
  3771. return pos;
  3772. }
  3773. static int decode_frame(AVCodecContext *avctx, void *data,
  3774. int *got_frame, AVPacket *avpkt)
  3775. {
  3776. const uint8_t *buf = avpkt->data;
  3777. int buf_size = avpkt->size;
  3778. H264Context *h = avctx->priv_data;
  3779. MpegEncContext *s = &h->s;
  3780. AVFrame *pict = data;
  3781. int buf_index = 0;
  3782. Picture *out;
  3783. int i, out_idx;
  3784. s->flags = avctx->flags;
  3785. s->flags2 = avctx->flags2;
  3786. /* end of stream, output what is still in the buffers */
  3787. if (buf_size == 0) {
  3788. out:
  3789. s->current_picture_ptr = NULL;
  3790. // FIXME factorize this with the output code below
  3791. out = h->delayed_pic[0];
  3792. out_idx = 0;
  3793. for (i = 1;
  3794. h->delayed_pic[i] &&
  3795. !h->delayed_pic[i]->f.key_frame &&
  3796. !h->delayed_pic[i]->mmco_reset;
  3797. i++)
  3798. if (h->delayed_pic[i]->poc < out->poc) {
  3799. out = h->delayed_pic[i];
  3800. out_idx = i;
  3801. }
  3802. for (i = out_idx; h->delayed_pic[i]; i++)
  3803. h->delayed_pic[i] = h->delayed_pic[i + 1];
  3804. if (out) {
  3805. *got_frame = 1;
  3806. *pict = out->f;
  3807. }
  3808. return buf_index;
  3809. }
  3810. if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){
  3811. int cnt= buf[5]&0x1f;
  3812. const uint8_t *p= buf+6;
  3813. while(cnt--){
  3814. int nalsize= AV_RB16(p) + 2;
  3815. if(nalsize > buf_size - (p-buf) || p[2]!=0x67)
  3816. goto not_extra;
  3817. p += nalsize;
  3818. }
  3819. cnt = *(p++);
  3820. if(!cnt)
  3821. goto not_extra;
  3822. while(cnt--){
  3823. int nalsize= AV_RB16(p) + 2;
  3824. if(nalsize > buf_size - (p-buf) || p[2]!=0x68)
  3825. goto not_extra;
  3826. p += nalsize;
  3827. }
  3828. return ff_h264_decode_extradata(h, buf, buf_size);
  3829. }
  3830. not_extra:
  3831. buf_index = decode_nal_units(h, buf, buf_size, 0);
  3832. if (buf_index < 0)
  3833. return -1;
  3834. if (!s->current_picture_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {
  3835. av_assert0(buf_index <= buf_size);
  3836. goto out;
  3837. }
  3838. if (!(s->flags2 & CODEC_FLAG2_CHUNKS) && !s->current_picture_ptr) {
  3839. if (avctx->skip_frame >= AVDISCARD_NONREF ||
  3840. buf_size >= 4 && !memcmp("Q264", buf, 4))
  3841. return buf_size;
  3842. av_log(avctx, AV_LOG_ERROR, "no frame!\n");
  3843. return -1;
  3844. }
  3845. if (!(s->flags2 & CODEC_FLAG2_CHUNKS) ||
  3846. (s->mb_y >= s->mb_height && s->mb_height)) {
  3847. if (s->flags2 & CODEC_FLAG2_CHUNKS)
  3848. decode_postinit(h, 1);
  3849. field_end(h, 0);
  3850. h->context_reinitialized = 0;
  3851. /* Wait for second field. */
  3852. *got_frame = 0;
  3853. if (h->next_output_pic && (h->next_output_pic->sync || h->sync>1)) {
  3854. *got_frame = 1;
  3855. *pict = h->next_output_pic->f;
  3856. }
  3857. }
  3858. assert(pict->data[0] || !*got_frame);
  3859. ff_print_debug_info(s, pict);
  3860. return get_consumed_bytes(s, buf_index, buf_size);
  3861. }
  3862. av_cold void ff_h264_free_context(H264Context *h)
  3863. {
  3864. int i;
  3865. free_tables(h, 1); // FIXME cleanup init stuff perhaps
  3866. for (i = 0; i < MAX_SPS_COUNT; i++)
  3867. av_freep(h->sps_buffers + i);
  3868. for (i = 0; i < MAX_PPS_COUNT; i++)
  3869. av_freep(h->pps_buffers + i);
  3870. }
  3871. static av_cold int h264_decode_end(AVCodecContext *avctx)
  3872. {
  3873. H264Context *h = avctx->priv_data;
  3874. MpegEncContext *s = &h->s;
  3875. ff_h264_remove_all_refs(h);
  3876. ff_h264_free_context(h);
  3877. ff_MPV_common_end(s);
  3878. // memset(h, 0, sizeof(H264Context));
  3879. return 0;
  3880. }
  3881. static const AVProfile profiles[] = {
  3882. { FF_PROFILE_H264_BASELINE, "Baseline" },
  3883. { FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
  3884. { FF_PROFILE_H264_MAIN, "Main" },
  3885. { FF_PROFILE_H264_EXTENDED, "Extended" },
  3886. { FF_PROFILE_H264_HIGH, "High" },
  3887. { FF_PROFILE_H264_HIGH_10, "High 10" },
  3888. { FF_PROFILE_H264_HIGH_10_INTRA, "High 10 Intra" },
  3889. { FF_PROFILE_H264_HIGH_422, "High 4:2:2" },
  3890. { FF_PROFILE_H264_HIGH_422_INTRA, "High 4:2:2 Intra" },
  3891. { FF_PROFILE_H264_HIGH_444, "High 4:4:4" },
  3892. { FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
  3893. { FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
  3894. { FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
  3895. { FF_PROFILE_UNKNOWN },
  3896. };
  3897. static const AVOption h264_options[] = {
  3898. {"is_avc", "is avc", offsetof(H264Context, is_avc), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0},
  3899. {"nal_length_size", "nal_length_size", offsetof(H264Context, nal_length_size), FF_OPT_TYPE_INT, {.i64 = 0}, 0, 4, 0},
  3900. {NULL}
  3901. };
  3902. static const AVClass h264_class = {
  3903. .class_name = "H264 Decoder",
  3904. .item_name = av_default_item_name,
  3905. .option = h264_options,
  3906. .version = LIBAVUTIL_VERSION_INT,
  3907. };
  3908. static const AVClass h264_vdpau_class = {
  3909. .class_name = "H264 VDPAU Decoder",
  3910. .item_name = av_default_item_name,
  3911. .option = h264_options,
  3912. .version = LIBAVUTIL_VERSION_INT,
  3913. };
  3914. AVCodec ff_h264_decoder = {
  3915. .name = "h264",
  3916. .type = AVMEDIA_TYPE_VIDEO,
  3917. .id = AV_CODEC_ID_H264,
  3918. .priv_data_size = sizeof(H264Context),
  3919. .init = ff_h264_decode_init,
  3920. .close = h264_decode_end,
  3921. .decode = decode_frame,
  3922. .capabilities = /*CODEC_CAP_DRAW_HORIZ_BAND |*/ CODEC_CAP_DR1 |
  3923. CODEC_CAP_DELAY | CODEC_CAP_SLICE_THREADS |
  3924. CODEC_CAP_FRAME_THREADS,
  3925. .flush = flush_dpb,
  3926. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
  3927. .init_thread_copy = ONLY_IF_THREADS_ENABLED(decode_init_thread_copy),
  3928. .update_thread_context = ONLY_IF_THREADS_ENABLED(decode_update_thread_context),
  3929. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  3930. .priv_class = &h264_class,
  3931. };
  3932. #if CONFIG_H264_VDPAU_DECODER
  3933. AVCodec ff_h264_vdpau_decoder = {
  3934. .name = "h264_vdpau",
  3935. .type = AVMEDIA_TYPE_VIDEO,
  3936. .id = AV_CODEC_ID_H264,
  3937. .priv_data_size = sizeof(H264Context),
  3938. .init = ff_h264_decode_init,
  3939. .close = h264_decode_end,
  3940. .decode = decode_frame,
  3941. .capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_HWACCEL_VDPAU,
  3942. .flush = flush_dpb,
  3943. .long_name = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)"),
  3944. .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_H264,
  3945. AV_PIX_FMT_NONE},
  3946. .profiles = NULL_IF_CONFIG_SMALL(profiles),
  3947. .priv_class = &h264_vdpau_class,
  3948. };
  3949. #endif