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.

4499 lines
172KB

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