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.

1747 lines
60KB

  1. /*
  2. * MJPEG decoder
  3. * Copyright (c) 2000, 2001 Fabrice Bellard
  4. * Copyright (c) 2003 Alex Beregszaszi
  5. * Copyright (c) 2003-2004 Michael Niedermayer
  6. *
  7. * Support for external huffman table, various fixes (AVID workaround),
  8. * aspecting, new decode_frame mechanism and apple mjpeg-b support
  9. * by Alex Beregszaszi
  10. *
  11. * This file is part of Libav.
  12. *
  13. * Libav is free software; you can redistribute it and/or
  14. * modify it under the terms of the GNU Lesser General Public
  15. * License as published by the Free Software Foundation; either
  16. * version 2.1 of the License, or (at your option) any later version.
  17. *
  18. * Libav is distributed in the hope that it will be useful,
  19. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  21. * Lesser General Public License for more details.
  22. *
  23. * You should have received a copy of the GNU Lesser General Public
  24. * License along with Libav; if not, write to the Free Software
  25. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  26. */
  27. /**
  28. * @file
  29. * MJPEG decoder.
  30. */
  31. #include <assert.h>
  32. #include "libavutil/imgutils.h"
  33. #include "libavutil/opt.h"
  34. #include "avcodec.h"
  35. #include "blockdsp.h"
  36. #include "idctdsp.h"
  37. #include "internal.h"
  38. #include "jpegtables.h"
  39. #include "mjpeg.h"
  40. #include "mjpegdec.h"
  41. #include "jpeglsdec.h"
  42. #include "put_bits.h"
  43. static int build_vlc(VLC *vlc, const uint8_t *bits_table,
  44. const uint8_t *val_table, int nb_codes,
  45. int use_static, int is_ac)
  46. {
  47. uint8_t huff_size[256] = { 0 };
  48. uint16_t huff_code[256];
  49. uint16_t huff_sym[256];
  50. int i;
  51. assert(nb_codes <= 256);
  52. ff_mjpeg_build_huffman_codes(huff_size, huff_code, bits_table, val_table);
  53. for (i = 0; i < 256; i++)
  54. huff_sym[i] = i + 16 * is_ac;
  55. if (is_ac)
  56. huff_sym[0] = 16 * 256;
  57. return ff_init_vlc_sparse(vlc, 9, nb_codes, huff_size, 1, 1,
  58. huff_code, 2, 2, huff_sym, 2, 2, use_static);
  59. }
  60. static void build_basic_mjpeg_vlc(MJpegDecodeContext *s)
  61. {
  62. build_vlc(&s->vlcs[0][0], avpriv_mjpeg_bits_dc_luminance,
  63. avpriv_mjpeg_val_dc, 12, 0, 0);
  64. build_vlc(&s->vlcs[0][1], avpriv_mjpeg_bits_dc_chrominance,
  65. avpriv_mjpeg_val_dc, 12, 0, 0);
  66. build_vlc(&s->vlcs[1][0], avpriv_mjpeg_bits_ac_luminance,
  67. avpriv_mjpeg_val_ac_luminance, 251, 0, 1);
  68. build_vlc(&s->vlcs[1][1], avpriv_mjpeg_bits_ac_chrominance,
  69. avpriv_mjpeg_val_ac_chrominance, 251, 0, 1);
  70. build_vlc(&s->vlcs[2][0], avpriv_mjpeg_bits_ac_luminance,
  71. avpriv_mjpeg_val_ac_luminance, 251, 0, 0);
  72. build_vlc(&s->vlcs[2][1], avpriv_mjpeg_bits_ac_chrominance,
  73. avpriv_mjpeg_val_ac_chrominance, 251, 0, 0);
  74. }
  75. av_cold int ff_mjpeg_decode_init(AVCodecContext *avctx)
  76. {
  77. MJpegDecodeContext *s = avctx->priv_data;
  78. if (!s->picture_ptr) {
  79. s->picture = av_frame_alloc();
  80. if (!s->picture)
  81. return AVERROR(ENOMEM);
  82. s->picture_ptr = s->picture;
  83. }
  84. s->avctx = avctx;
  85. ff_blockdsp_init(&s->bdsp, avctx);
  86. ff_hpeldsp_init(&s->hdsp, avctx->flags);
  87. ff_idctdsp_init(&s->idsp, avctx);
  88. ff_init_scantable(s->idsp.idct_permutation, &s->scantable,
  89. ff_zigzag_direct);
  90. s->buffer_size = 0;
  91. s->buffer = NULL;
  92. s->start_code = -1;
  93. s->first_picture = 1;
  94. s->org_height = avctx->coded_height;
  95. avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
  96. avctx->colorspace = AVCOL_SPC_BT470BG;
  97. build_basic_mjpeg_vlc(s);
  98. if (s->extern_huff) {
  99. int ret;
  100. av_log(avctx, AV_LOG_INFO, "mjpeg: using external huffman table\n");
  101. init_get_bits(&s->gb, avctx->extradata, avctx->extradata_size * 8);
  102. if ((ret = ff_mjpeg_decode_dht(s))) {
  103. av_log(avctx, AV_LOG_ERROR,
  104. "mjpeg: error using external huffman table\n");
  105. return ret;
  106. }
  107. }
  108. if (avctx->field_order == AV_FIELD_BB) { /* quicktime icefloe 019 */
  109. s->interlace_polarity = 1; /* bottom field first */
  110. av_log(avctx, AV_LOG_DEBUG, "mjpeg bottom field first\n");
  111. }
  112. if (avctx->codec->id == AV_CODEC_ID_AMV)
  113. s->flipped = 1;
  114. return 0;
  115. }
  116. /* quantize tables */
  117. int ff_mjpeg_decode_dqt(MJpegDecodeContext *s)
  118. {
  119. int len, index, i, j;
  120. len = get_bits(&s->gb, 16) - 2;
  121. while (len >= 65) {
  122. /* only 8-bit precision handled */
  123. if (get_bits(&s->gb, 4) != 0) {
  124. av_log(s->avctx, AV_LOG_ERROR, "dqt: 16-bit precision\n");
  125. return -1;
  126. }
  127. index = get_bits(&s->gb, 4);
  128. if (index >= 4)
  129. return -1;
  130. av_log(s->avctx, AV_LOG_DEBUG, "index=%d\n", index);
  131. /* read quant table */
  132. for (i = 0; i < 64; i++) {
  133. j = s->scantable.permutated[i];
  134. s->quant_matrixes[index][j] = get_bits(&s->gb, 8);
  135. }
  136. // XXX FIXME fine-tune, and perhaps add dc too
  137. s->qscale[index] = FFMAX(s->quant_matrixes[index][s->scantable.permutated[1]],
  138. s->quant_matrixes[index][s->scantable.permutated[8]]) >> 1;
  139. av_log(s->avctx, AV_LOG_DEBUG, "qscale[%d]: %d\n",
  140. index, s->qscale[index]);
  141. len -= 65;
  142. }
  143. return 0;
  144. }
  145. /* decode huffman tables and build VLC decoders */
  146. int ff_mjpeg_decode_dht(MJpegDecodeContext *s)
  147. {
  148. int len, index, i, class, n, v, code_max;
  149. uint8_t bits_table[17];
  150. uint8_t val_table[256];
  151. int ret = 0;
  152. len = get_bits(&s->gb, 16) - 2;
  153. while (len > 0) {
  154. if (len < 17)
  155. return AVERROR_INVALIDDATA;
  156. class = get_bits(&s->gb, 4);
  157. if (class >= 2)
  158. return AVERROR_INVALIDDATA;
  159. index = get_bits(&s->gb, 4);
  160. if (index >= 4)
  161. return AVERROR_INVALIDDATA;
  162. n = 0;
  163. for (i = 1; i <= 16; i++) {
  164. bits_table[i] = get_bits(&s->gb, 8);
  165. n += bits_table[i];
  166. }
  167. len -= 17;
  168. if (len < n || n > 256)
  169. return AVERROR_INVALIDDATA;
  170. code_max = 0;
  171. for (i = 0; i < n; i++) {
  172. v = get_bits(&s->gb, 8);
  173. if (v > code_max)
  174. code_max = v;
  175. val_table[i] = v;
  176. }
  177. len -= n;
  178. /* build VLC and flush previous vlc if present */
  179. ff_free_vlc(&s->vlcs[class][index]);
  180. av_log(s->avctx, AV_LOG_DEBUG, "class=%d index=%d nb_codes=%d\n",
  181. class, index, code_max + 1);
  182. if ((ret = build_vlc(&s->vlcs[class][index], bits_table, val_table,
  183. code_max + 1, 0, class > 0)) < 0)
  184. return ret;
  185. if (class > 0) {
  186. ff_free_vlc(&s->vlcs[2][index]);
  187. if ((ret = build_vlc(&s->vlcs[2][index], bits_table, val_table,
  188. code_max + 1, 0, 0)) < 0)
  189. return ret;
  190. }
  191. }
  192. return 0;
  193. }
  194. int ff_mjpeg_decode_sof(MJpegDecodeContext *s)
  195. {
  196. int h_count[MAX_COMPONENTS] = { 0 };
  197. int v_count[MAX_COMPONENTS] = { 0 };
  198. int len, nb_components, i, width, height, bits, pix_fmt_id, ret;
  199. /* XXX: verify len field validity */
  200. len = get_bits(&s->gb, 16);
  201. bits = get_bits(&s->gb, 8);
  202. if (s->pegasus_rct)
  203. bits = 9;
  204. if (bits == 9 && !s->pegasus_rct)
  205. s->rct = 1; // FIXME ugly
  206. if (bits != 8 && !s->lossless) {
  207. av_log(s->avctx, AV_LOG_ERROR, "only 8 bits/component accepted\n");
  208. return -1;
  209. }
  210. height = get_bits(&s->gb, 16);
  211. width = get_bits(&s->gb, 16);
  212. // HACK for odd_height.mov
  213. if (s->interlaced && s->width == width && s->height == height + 1)
  214. height= s->height;
  215. av_log(s->avctx, AV_LOG_DEBUG, "sof0: picture: %dx%d\n", width, height);
  216. if (av_image_check_size(width, height, 0, s->avctx))
  217. return AVERROR_INVALIDDATA;
  218. nb_components = get_bits(&s->gb, 8);
  219. if (nb_components <= 0 ||
  220. nb_components > MAX_COMPONENTS)
  221. return -1;
  222. if (s->interlaced && (s->bottom_field == !s->interlace_polarity)) {
  223. if (nb_components != s->nb_components) {
  224. av_log(s->avctx, AV_LOG_ERROR,
  225. "nb_components changing in interlaced picture\n");
  226. return AVERROR_INVALIDDATA;
  227. }
  228. }
  229. if (s->ls && !(bits <= 8 || nb_components == 1)) {
  230. avpriv_report_missing_feature(s->avctx,
  231. "JPEG-LS that is not <= 8 "
  232. "bits/component or 16-bit gray");
  233. return AVERROR_PATCHWELCOME;
  234. }
  235. s->nb_components = nb_components;
  236. s->h_max = 1;
  237. s->v_max = 1;
  238. for (i = 0; i < nb_components; i++) {
  239. /* component id */
  240. s->component_id[i] = get_bits(&s->gb, 8) - 1;
  241. h_count[i] = get_bits(&s->gb, 4);
  242. v_count[i] = get_bits(&s->gb, 4);
  243. /* compute hmax and vmax (only used in interleaved case) */
  244. if (h_count[i] > s->h_max)
  245. s->h_max = h_count[i];
  246. if (v_count[i] > s->v_max)
  247. s->v_max = v_count[i];
  248. s->quant_index[i] = get_bits(&s->gb, 8);
  249. if (s->quant_index[i] >= 4)
  250. return AVERROR_INVALIDDATA;
  251. if (!h_count[i] || !v_count[i]) {
  252. av_log(s->avctx, AV_LOG_ERROR,
  253. "Invalid sampling factor in component %d %d:%d\n",
  254. i, h_count[i], v_count[i]);
  255. return AVERROR_INVALIDDATA;
  256. }
  257. av_log(s->avctx, AV_LOG_DEBUG, "component %d %d:%d id: %d quant:%d\n",
  258. i, h_count[i], v_count[i],
  259. s->component_id[i], s->quant_index[i]);
  260. }
  261. if (s->ls && (s->h_max > 1 || s->v_max > 1)) {
  262. avpriv_report_missing_feature(s->avctx, "Subsampling in JPEG-LS");
  263. return AVERROR_PATCHWELCOME;
  264. }
  265. if (s->v_max == 1 && s->h_max == 1 && s->lossless == 1)
  266. s->rgb = 1;
  267. /* if different size, realloc/alloc picture */
  268. if (width != s->width || height != s->height || bits != s->bits ||
  269. memcmp(s->h_count, h_count, sizeof(h_count)) ||
  270. memcmp(s->v_count, v_count, sizeof(v_count))) {
  271. s->width = width;
  272. s->height = height;
  273. s->bits = bits;
  274. memcpy(s->h_count, h_count, sizeof(h_count));
  275. memcpy(s->v_count, v_count, sizeof(v_count));
  276. s->interlaced = 0;
  277. /* test interlaced mode */
  278. if (s->first_picture &&
  279. s->org_height != 0 &&
  280. s->height < ((s->org_height * 3) / 4)) {
  281. s->interlaced = 1;
  282. s->bottom_field = s->interlace_polarity;
  283. s->picture_ptr->interlaced_frame = 1;
  284. s->picture_ptr->top_field_first = !s->interlace_polarity;
  285. height *= 2;
  286. }
  287. ret = ff_set_dimensions(s->avctx, width, height);
  288. if (ret < 0)
  289. return ret;
  290. s->first_picture = 0;
  291. }
  292. if (!(s->interlaced && (s->bottom_field == !s->interlace_polarity))) {
  293. /* XXX: not complete test ! */
  294. pix_fmt_id = (s->h_count[0] << 28) | (s->v_count[0] << 24) |
  295. (s->h_count[1] << 20) | (s->v_count[1] << 16) |
  296. (s->h_count[2] << 12) | (s->v_count[2] << 8) |
  297. (s->h_count[3] << 4) | s->v_count[3];
  298. av_log(s->avctx, AV_LOG_DEBUG, "pix fmt id %x\n", pix_fmt_id);
  299. /* NOTE we do not allocate pictures large enough for the possible
  300. * padding of h/v_count being 4 */
  301. if (!(pix_fmt_id & 0xD0D0D0D0))
  302. pix_fmt_id -= (pix_fmt_id & 0xF0F0F0F0) >> 1;
  303. if (!(pix_fmt_id & 0x0D0D0D0D))
  304. pix_fmt_id -= (pix_fmt_id & 0x0F0F0F0F) >> 1;
  305. switch (pix_fmt_id) {
  306. case 0x11111100:
  307. if (s->rgb)
  308. s->avctx->pix_fmt = AV_PIX_FMT_BGRA;
  309. else {
  310. s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;
  311. s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
  312. }
  313. assert(s->nb_components == 3);
  314. break;
  315. case 0x11000000:
  316. s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
  317. break;
  318. case 0x12111100:
  319. s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV440P : AV_PIX_FMT_YUVJ440P;
  320. s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
  321. break;
  322. case 0x21111100:
  323. s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV422P : AV_PIX_FMT_YUVJ422P;
  324. s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
  325. break;
  326. case 0x22111100:
  327. s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV420P : AV_PIX_FMT_YUVJ420P;
  328. s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;
  329. break;
  330. default:
  331. av_log(s->avctx, AV_LOG_ERROR, "Unhandled pixel format 0x%x\n", pix_fmt_id);
  332. return AVERROR_PATCHWELCOME;
  333. }
  334. if (s->ls) {
  335. if (s->nb_components > 1)
  336. s->avctx->pix_fmt = AV_PIX_FMT_RGB24;
  337. else if (s->bits <= 8)
  338. s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;
  339. else
  340. s->avctx->pix_fmt = AV_PIX_FMT_GRAY16;
  341. }
  342. s->pix_desc = av_pix_fmt_desc_get(s->avctx->pix_fmt);
  343. if (!s->pix_desc) {
  344. av_log(s->avctx, AV_LOG_ERROR, "Could not get a pixel format descriptor.\n");
  345. return AVERROR_BUG;
  346. }
  347. av_frame_unref(s->picture_ptr);
  348. if (ff_get_buffer(s->avctx, s->picture_ptr, AV_GET_BUFFER_FLAG_REF) < 0) {
  349. av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
  350. return -1;
  351. }
  352. s->picture_ptr->pict_type = AV_PICTURE_TYPE_I;
  353. s->picture_ptr->key_frame = 1;
  354. s->got_picture = 1;
  355. for (i = 0; i < 3; i++)
  356. s->linesize[i] = s->picture_ptr->linesize[i] << s->interlaced;
  357. ff_dlog(s->avctx, "%d %d %d %d %d %d\n",
  358. s->width, s->height, s->linesize[0], s->linesize[1],
  359. s->interlaced, s->avctx->height);
  360. if (len != (8 + (3 * nb_components)))
  361. av_log(s->avctx, AV_LOG_DEBUG, "decode_sof0: error, len(%d) mismatch\n", len);
  362. }
  363. /* totally blank picture as progressive JPEG will only add details to it */
  364. if (s->progressive) {
  365. int bw = (width + s->h_max * 8 - 1) / (s->h_max * 8);
  366. int bh = (height + s->v_max * 8 - 1) / (s->v_max * 8);
  367. for (i = 0; i < s->nb_components; i++) {
  368. int size = bw * bh * s->h_count[i] * s->v_count[i];
  369. av_freep(&s->blocks[i]);
  370. av_freep(&s->last_nnz[i]);
  371. s->blocks[i] = av_malloc(size * sizeof(**s->blocks));
  372. s->last_nnz[i] = av_mallocz(size * sizeof(**s->last_nnz));
  373. s->block_stride[i] = bw * s->h_count[i];
  374. }
  375. memset(s->coefs_finished, 0, sizeof(s->coefs_finished));
  376. }
  377. return 0;
  378. }
  379. static inline int mjpeg_decode_dc(MJpegDecodeContext *s, int dc_index)
  380. {
  381. int code;
  382. code = get_vlc2(&s->gb, s->vlcs[0][dc_index].table, 9, 2);
  383. if (code < 0) {
  384. av_log(s->avctx, AV_LOG_WARNING,
  385. "mjpeg_decode_dc: bad vlc: %d:%d (%p)\n",
  386. 0, dc_index, &s->vlcs[0][dc_index]);
  387. return 0xffff;
  388. }
  389. if (code)
  390. return get_xbits(&s->gb, code);
  391. else
  392. return 0;
  393. }
  394. /* decode block and dequantize */
  395. static int decode_block(MJpegDecodeContext *s, int16_t *block, int component,
  396. int dc_index, int ac_index, int16_t *quant_matrix)
  397. {
  398. int code, i, j, level, val;
  399. /* DC coef */
  400. val = mjpeg_decode_dc(s, dc_index);
  401. if (val == 0xffff) {
  402. av_log(s->avctx, AV_LOG_ERROR, "error dc\n");
  403. return AVERROR_INVALIDDATA;
  404. }
  405. val = val * quant_matrix[0] + s->last_dc[component];
  406. s->last_dc[component] = val;
  407. block[0] = val;
  408. /* AC coefs */
  409. i = 0;
  410. {OPEN_READER(re, &s->gb);
  411. do {
  412. UPDATE_CACHE(re, &s->gb);
  413. GET_VLC(code, re, &s->gb, s->vlcs[1][ac_index].table, 9, 2);
  414. i += ((unsigned)code) >> 4;
  415. code &= 0xf;
  416. if (code) {
  417. if (code > MIN_CACHE_BITS - 16)
  418. UPDATE_CACHE(re, &s->gb);
  419. {
  420. int cache = GET_CACHE(re, &s->gb);
  421. int sign = (~cache) >> 31;
  422. level = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
  423. }
  424. LAST_SKIP_BITS(re, &s->gb, code);
  425. if (i > 63) {
  426. av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
  427. return AVERROR_INVALIDDATA;
  428. }
  429. j = s->scantable.permutated[i];
  430. block[j] = level * quant_matrix[j];
  431. }
  432. } while (i < 63);
  433. CLOSE_READER(re, &s->gb);}
  434. return 0;
  435. }
  436. static int decode_dc_progressive(MJpegDecodeContext *s, int16_t *block,
  437. int component, int dc_index,
  438. int16_t *quant_matrix, int Al)
  439. {
  440. int val;
  441. s->bdsp.clear_block(block);
  442. val = mjpeg_decode_dc(s, dc_index);
  443. if (val == 0xffff) {
  444. av_log(s->avctx, AV_LOG_ERROR, "error dc\n");
  445. return AVERROR_INVALIDDATA;
  446. }
  447. val = (val * quant_matrix[0] << Al) + s->last_dc[component];
  448. s->last_dc[component] = val;
  449. block[0] = val;
  450. return 0;
  451. }
  452. /* decode block and dequantize - progressive JPEG version */
  453. static int decode_block_progressive(MJpegDecodeContext *s, int16_t *block,
  454. uint8_t *last_nnz, int ac_index,
  455. int16_t *quant_matrix,
  456. int ss, int se, int Al, int *EOBRUN)
  457. {
  458. int code, i, j, level, val, run;
  459. if (*EOBRUN) {
  460. (*EOBRUN)--;
  461. return 0;
  462. }
  463. {
  464. OPEN_READER(re, &s->gb);
  465. for (i = ss; ; i++) {
  466. UPDATE_CACHE(re, &s->gb);
  467. GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
  468. run = ((unsigned) code) >> 4;
  469. code &= 0xF;
  470. if (code) {
  471. i += run;
  472. if (code > MIN_CACHE_BITS - 16)
  473. UPDATE_CACHE(re, &s->gb);
  474. {
  475. int cache = GET_CACHE(re, &s->gb);
  476. int sign = (~cache) >> 31;
  477. level = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
  478. }
  479. LAST_SKIP_BITS(re, &s->gb, code);
  480. if (i >= se) {
  481. if (i == se) {
  482. j = s->scantable.permutated[se];
  483. block[j] = level * quant_matrix[j] << Al;
  484. break;
  485. }
  486. av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
  487. return AVERROR_INVALIDDATA;
  488. }
  489. j = s->scantable.permutated[i];
  490. block[j] = level * quant_matrix[j] << Al;
  491. } else {
  492. if (run == 0xF) {// ZRL - skip 15 coefficients
  493. i += 15;
  494. if (i >= se) {
  495. av_log(s->avctx, AV_LOG_ERROR, "ZRL overflow: %d\n", i);
  496. return AVERROR_INVALIDDATA;
  497. }
  498. } else {
  499. val = (1 << run);
  500. if (run) {
  501. UPDATE_CACHE(re, &s->gb);
  502. val += NEG_USR32(GET_CACHE(re, &s->gb), run);
  503. LAST_SKIP_BITS(re, &s->gb, run);
  504. }
  505. *EOBRUN = val - 1;
  506. break;
  507. }
  508. }
  509. }
  510. CLOSE_READER(re, &s->gb);
  511. }
  512. if (i > *last_nnz)
  513. *last_nnz = i;
  514. return 0;
  515. }
  516. #define REFINE_BIT(j) { \
  517. UPDATE_CACHE(re, &s->gb); \
  518. sign = block[j] >> 15; \
  519. block[j] += SHOW_UBITS(re, &s->gb, 1) * \
  520. ((quant_matrix[j] ^ sign) - sign) << Al; \
  521. LAST_SKIP_BITS(re, &s->gb, 1); \
  522. }
  523. #define ZERO_RUN \
  524. for (; ; i++) { \
  525. if (i > last) { \
  526. i += run; \
  527. if (i > se) { \
  528. av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i); \
  529. return -1; \
  530. } \
  531. break; \
  532. } \
  533. j = s->scantable.permutated[i]; \
  534. if (block[j]) \
  535. REFINE_BIT(j) \
  536. else if (run-- == 0) \
  537. break; \
  538. }
  539. /* decode block and dequantize - progressive JPEG refinement pass */
  540. static int decode_block_refinement(MJpegDecodeContext *s, int16_t *block,
  541. uint8_t *last_nnz,
  542. int ac_index, int16_t *quant_matrix,
  543. int ss, int se, int Al, int *EOBRUN)
  544. {
  545. int code, i = ss, j, sign, val, run;
  546. int last = FFMIN(se, *last_nnz);
  547. OPEN_READER(re, &s->gb);
  548. if (*EOBRUN) {
  549. (*EOBRUN)--;
  550. } else {
  551. for (; ; i++) {
  552. UPDATE_CACHE(re, &s->gb);
  553. GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
  554. if (code & 0xF) {
  555. run = ((unsigned) code) >> 4;
  556. UPDATE_CACHE(re, &s->gb);
  557. val = SHOW_UBITS(re, &s->gb, 1);
  558. LAST_SKIP_BITS(re, &s->gb, 1);
  559. ZERO_RUN;
  560. j = s->scantable.permutated[i];
  561. val--;
  562. block[j] = ((quant_matrix[j]^val) - val) << Al;
  563. if (i == se) {
  564. if (i > *last_nnz)
  565. *last_nnz = i;
  566. CLOSE_READER(re, &s->gb);
  567. return 0;
  568. }
  569. } else {
  570. run = ((unsigned) code) >> 4;
  571. if (run == 0xF) {
  572. ZERO_RUN;
  573. } else {
  574. val = run;
  575. run = (1 << run);
  576. if (val) {
  577. UPDATE_CACHE(re, &s->gb);
  578. run += SHOW_UBITS(re, &s->gb, val);
  579. LAST_SKIP_BITS(re, &s->gb, val);
  580. }
  581. *EOBRUN = run - 1;
  582. break;
  583. }
  584. }
  585. }
  586. if (i > *last_nnz)
  587. *last_nnz = i;
  588. }
  589. for (; i <= last; i++) {
  590. j = s->scantable.permutated[i];
  591. if (block[j])
  592. REFINE_BIT(j)
  593. }
  594. CLOSE_READER(re, &s->gb);
  595. return 0;
  596. }
  597. #undef REFINE_BIT
  598. #undef ZERO_RUN
  599. static int ljpeg_decode_rgb_scan(MJpegDecodeContext *s, int predictor,
  600. int point_transform)
  601. {
  602. int i, mb_x, mb_y;
  603. uint16_t (*buffer)[4];
  604. int left[3], top[3], topleft[3];
  605. const int linesize = s->linesize[0];
  606. const int mask = (1 << s->bits) - 1;
  607. av_fast_malloc(&s->ljpeg_buffer, &s->ljpeg_buffer_size,
  608. (unsigned)s->mb_width * 4 * sizeof(s->ljpeg_buffer[0][0]));
  609. buffer = s->ljpeg_buffer;
  610. for (i = 0; i < 3; i++)
  611. buffer[0][i] = 1 << (s->bits + point_transform - 1);
  612. for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
  613. const int modified_predictor = mb_y ? predictor : 1;
  614. uint8_t *ptr = s->picture_ptr->data[0] + (linesize * mb_y);
  615. if (s->interlaced && s->bottom_field)
  616. ptr += linesize >> 1;
  617. for (i = 0; i < 3; i++)
  618. top[i] = left[i] = topleft[i] = buffer[0][i];
  619. for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
  620. if (s->restart_interval && !s->restart_count)
  621. s->restart_count = s->restart_interval;
  622. for (i = 0; i < 3; i++) {
  623. int pred;
  624. topleft[i] = top[i];
  625. top[i] = buffer[mb_x][i];
  626. PREDICT(pred, topleft[i], top[i], left[i], modified_predictor);
  627. left[i] = buffer[mb_x][i] =
  628. mask & (pred + (mjpeg_decode_dc(s, s->dc_index[i]) << point_transform));
  629. }
  630. if (s->restart_interval && !--s->restart_count) {
  631. align_get_bits(&s->gb);
  632. skip_bits(&s->gb, 16); /* skip RSTn */
  633. }
  634. }
  635. if (s->rct) {
  636. for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
  637. ptr[4 * mb_x + 1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2] - 0x200) >> 2);
  638. ptr[4 * mb_x + 0] = buffer[mb_x][1] + ptr[4 * mb_x + 1];
  639. ptr[4 * mb_x + 2] = buffer[mb_x][2] + ptr[4 * mb_x + 1];
  640. }
  641. } else if (s->pegasus_rct) {
  642. for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
  643. ptr[4 * mb_x + 1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2]) >> 2);
  644. ptr[4 * mb_x + 0] = buffer[mb_x][1] + ptr[4 * mb_x + 1];
  645. ptr[4 * mb_x + 2] = buffer[mb_x][2] + ptr[4 * mb_x + 1];
  646. }
  647. } else {
  648. for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
  649. ptr[4 * mb_x + 0] = buffer[mb_x][2];
  650. ptr[4 * mb_x + 1] = buffer[mb_x][1];
  651. ptr[4 * mb_x + 2] = buffer[mb_x][0];
  652. }
  653. }
  654. }
  655. return 0;
  656. }
  657. static int ljpeg_decode_yuv_scan(MJpegDecodeContext *s, int predictor,
  658. int point_transform, int nb_components)
  659. {
  660. int i, mb_x, mb_y;
  661. for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
  662. for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
  663. if (s->restart_interval && !s->restart_count)
  664. s->restart_count = s->restart_interval;
  665. if (mb_x == 0 || mb_y == 0 || s->interlaced) {
  666. for (i = 0; i < nb_components; i++) {
  667. uint8_t *ptr;
  668. int n, h, v, x, y, c, j, linesize;
  669. n = s->nb_blocks[i];
  670. c = s->comp_index[i];
  671. h = s->h_scount[i];
  672. v = s->v_scount[i];
  673. x = 0;
  674. y = 0;
  675. linesize = s->linesize[c];
  676. for (j = 0; j < n; j++) {
  677. int pred;
  678. // FIXME optimize this crap
  679. ptr = s->picture_ptr->data[c] +
  680. (linesize * (v * mb_y + y)) +
  681. (h * mb_x + x);
  682. if (y == 0 && mb_y == 0) {
  683. if (x == 0 && mb_x == 0)
  684. pred = 128 << point_transform;
  685. else
  686. pred = ptr[-1];
  687. } else {
  688. if (x == 0 && mb_x == 0)
  689. pred = ptr[-linesize];
  690. else
  691. PREDICT(pred, ptr[-linesize - 1],
  692. ptr[-linesize], ptr[-1], predictor);
  693. }
  694. if (s->interlaced && s->bottom_field)
  695. ptr += linesize >> 1;
  696. *ptr = pred + (mjpeg_decode_dc(s, s->dc_index[i]) << point_transform);
  697. if (++x == h) {
  698. x = 0;
  699. y++;
  700. }
  701. }
  702. }
  703. } else {
  704. for (i = 0; i < nb_components; i++) {
  705. uint8_t *ptr;
  706. int n, h, v, x, y, c, j, linesize;
  707. n = s->nb_blocks[i];
  708. c = s->comp_index[i];
  709. h = s->h_scount[i];
  710. v = s->v_scount[i];
  711. x = 0;
  712. y = 0;
  713. linesize = s->linesize[c];
  714. for (j = 0; j < n; j++) {
  715. int pred;
  716. // FIXME optimize this crap
  717. ptr = s->picture_ptr->data[c] +
  718. (linesize * (v * mb_y + y)) +
  719. (h * mb_x + x);
  720. PREDICT(pred, ptr[-linesize - 1],
  721. ptr[-linesize], ptr[-1], predictor);
  722. *ptr = pred + (mjpeg_decode_dc(s, s->dc_index[i]) << point_transform);
  723. if (++x == h) {
  724. x = 0;
  725. y++;
  726. }
  727. }
  728. }
  729. }
  730. if (s->restart_interval && !--s->restart_count) {
  731. align_get_bits(&s->gb);
  732. skip_bits(&s->gb, 16); /* skip RSTn */
  733. }
  734. }
  735. }
  736. return 0;
  737. }
  738. static int mjpeg_decode_scan(MJpegDecodeContext *s, int nb_components, int Ah,
  739. int Al, const uint8_t *mb_bitmask,
  740. const AVFrame *reference)
  741. {
  742. int i, mb_x, mb_y;
  743. uint8_t *data[MAX_COMPONENTS];
  744. const uint8_t *reference_data[MAX_COMPONENTS];
  745. int linesize[MAX_COMPONENTS];
  746. GetBitContext mb_bitmask_gb;
  747. if (mb_bitmask)
  748. init_get_bits(&mb_bitmask_gb, mb_bitmask, s->mb_width * s->mb_height);
  749. for (i = 0; i < nb_components; i++) {
  750. int c = s->comp_index[i];
  751. data[c] = s->picture_ptr->data[c];
  752. reference_data[c] = reference ? reference->data[c] : NULL;
  753. linesize[c] = s->linesize[c];
  754. s->coefs_finished[c] |= 1;
  755. }
  756. for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
  757. for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
  758. const int copy_mb = mb_bitmask && !get_bits1(&mb_bitmask_gb);
  759. if (s->restart_interval && !s->restart_count)
  760. s->restart_count = s->restart_interval;
  761. if (get_bits_left(&s->gb) < 0) {
  762. av_log(s->avctx, AV_LOG_ERROR, "overread %d\n",
  763. -get_bits_left(&s->gb));
  764. return AVERROR_INVALIDDATA;
  765. }
  766. for (i = 0; i < nb_components; i++) {
  767. uint8_t *ptr;
  768. int n, h, v, x, y, c, j;
  769. int block_offset;
  770. n = s->nb_blocks[i];
  771. c = s->comp_index[i];
  772. h = s->h_scount[i];
  773. v = s->v_scount[i];
  774. x = 0;
  775. y = 0;
  776. for (j = 0; j < n; j++) {
  777. block_offset = ((linesize[c] * (v * mb_y + y) * 8) +
  778. (h * mb_x + x) * 8);
  779. if (s->interlaced && s->bottom_field)
  780. block_offset += linesize[c] >> 1;
  781. ptr = data[c] + block_offset;
  782. if (!s->progressive) {
  783. if (copy_mb)
  784. s->hdsp.put_pixels_tab[1][0](ptr,
  785. reference_data[c] + block_offset,
  786. linesize[c], 8);
  787. else {
  788. s->bdsp.clear_block(s->block);
  789. if (decode_block(s, s->block, i,
  790. s->dc_index[i], s->ac_index[i],
  791. s->quant_matrixes[s->quant_index[c]]) < 0) {
  792. av_log(s->avctx, AV_LOG_ERROR,
  793. "error y=%d x=%d\n", mb_y, mb_x);
  794. return AVERROR_INVALIDDATA;
  795. }
  796. s->idsp.idct_put(ptr, linesize[c], s->block);
  797. }
  798. } else {
  799. int block_idx = s->block_stride[c] * (v * mb_y + y) +
  800. (h * mb_x + x);
  801. int16_t *block = s->blocks[c][block_idx];
  802. if (Ah)
  803. block[0] += get_bits1(&s->gb) *
  804. s->quant_matrixes[s->quant_index[c]][0] << Al;
  805. else if (decode_dc_progressive(s, block, i, s->dc_index[i],
  806. s->quant_matrixes[s->quant_index[c]],
  807. Al) < 0) {
  808. av_log(s->avctx, AV_LOG_ERROR,
  809. "error y=%d x=%d\n", mb_y, mb_x);
  810. return AVERROR_INVALIDDATA;
  811. }
  812. }
  813. ff_dlog(s->avctx, "mb: %d %d processed\n", mb_y, mb_x);
  814. ff_dlog(s->avctx, "%d %d %d %d %d %d %d %d \n",
  815. mb_x, mb_y, x, y, c, s->bottom_field,
  816. (v * mb_y + y) * 8, (h * mb_x + x) * 8);
  817. if (++x == h) {
  818. x = 0;
  819. y++;
  820. }
  821. }
  822. }
  823. if (s->restart_interval) {
  824. s->restart_count--;
  825. i = 8 + ((-get_bits_count(&s->gb)) & 7);
  826. /* skip RSTn */
  827. if (show_bits(&s->gb, i) == (1 << i) - 1) {
  828. int pos = get_bits_count(&s->gb);
  829. align_get_bits(&s->gb);
  830. while (get_bits_left(&s->gb) >= 8 && show_bits(&s->gb, 8) == 0xFF)
  831. skip_bits(&s->gb, 8);
  832. if ((get_bits(&s->gb, 8) & 0xF8) == 0xD0) {
  833. for (i = 0; i < nb_components; i++) /* reset dc */
  834. s->last_dc[i] = 1024;
  835. } else
  836. skip_bits_long(&s->gb, pos - get_bits_count(&s->gb));
  837. }
  838. }
  839. }
  840. }
  841. return 0;
  842. }
  843. static int mjpeg_decode_scan_progressive_ac(MJpegDecodeContext *s, int ss,
  844. int se, int Ah, int Al,
  845. const uint8_t *mb_bitmask,
  846. const AVFrame *reference)
  847. {
  848. int mb_x, mb_y;
  849. int EOBRUN = 0;
  850. int c = s->comp_index[0];
  851. uint8_t *data = s->picture_ptr->data[c];
  852. const uint8_t *reference_data = reference ? reference->data[c] : NULL;
  853. int linesize = s->linesize[c];
  854. int last_scan = 0;
  855. int16_t *quant_matrix = s->quant_matrixes[s->quant_index[c]];
  856. GetBitContext mb_bitmask_gb;
  857. if (ss < 0 || ss >= 64 ||
  858. se < ss || se >= 64 ||
  859. Ah < 0 || Al < 0)
  860. return AVERROR_INVALIDDATA;
  861. if (mb_bitmask)
  862. init_get_bits(&mb_bitmask_gb, mb_bitmask, s->mb_width * s->mb_height);
  863. if (!Al) {
  864. // s->coefs_finished is a bitmask for coefficients coded
  865. // ss and se are parameters telling start and end coefficients
  866. s->coefs_finished[c] |= (~0ULL >> (63 - (se - ss))) << ss;
  867. last_scan = !~s->coefs_finished[c];
  868. }
  869. if (s->interlaced && s->bottom_field) {
  870. int offset = linesize >> 1;
  871. data += offset;
  872. reference_data += offset;
  873. }
  874. for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
  875. int block_offset = mb_y * linesize * 8;
  876. uint8_t *ptr = data + block_offset;
  877. int block_idx = mb_y * s->block_stride[c];
  878. int16_t (*block)[64] = &s->blocks[c][block_idx];
  879. uint8_t *last_nnz = &s->last_nnz[c][block_idx];
  880. for (mb_x = 0; mb_x < s->mb_width; mb_x++, block++, last_nnz++) {
  881. const int copy_mb = mb_bitmask && !get_bits1(&mb_bitmask_gb);
  882. if (!copy_mb) {
  883. int ret;
  884. if (Ah)
  885. ret = decode_block_refinement(s, *block, last_nnz, s->ac_index[0],
  886. quant_matrix, ss, se, Al, &EOBRUN);
  887. else
  888. ret = decode_block_progressive(s, *block, last_nnz, s->ac_index[0],
  889. quant_matrix, ss, se, Al, &EOBRUN);
  890. if (ret < 0) {
  891. av_log(s->avctx, AV_LOG_ERROR,
  892. "error y=%d x=%d\n", mb_y, mb_x);
  893. return AVERROR_INVALIDDATA;
  894. }
  895. }
  896. if (last_scan) {
  897. if (copy_mb) {
  898. s->hdsp.put_pixels_tab[1][0](ptr,
  899. reference_data + block_offset,
  900. linesize, 8);
  901. } else {
  902. s->idsp.idct_put(ptr, linesize, *block);
  903. ptr += 8;
  904. }
  905. }
  906. }
  907. }
  908. return 0;
  909. }
  910. int ff_mjpeg_decode_sos(MJpegDecodeContext *s, const uint8_t *mb_bitmask,
  911. const AVFrame *reference)
  912. {
  913. int len, nb_components, i, h, v, predictor, point_transform;
  914. int index, id, ret;
  915. const int block_size = s->lossless ? 1 : 8;
  916. int ilv, prev_shift;
  917. /* XXX: verify len field validity */
  918. len = get_bits(&s->gb, 16);
  919. nb_components = get_bits(&s->gb, 8);
  920. if (nb_components == 0 || nb_components > MAX_COMPONENTS) {
  921. av_log(s->avctx, AV_LOG_ERROR,
  922. "decode_sos: nb_components (%d) unsupported\n", nb_components);
  923. return AVERROR_PATCHWELCOME;
  924. }
  925. if (len != 6 + 2 * nb_components) {
  926. av_log(s->avctx, AV_LOG_ERROR, "decode_sos: invalid len (%d)\n", len);
  927. return AVERROR_INVALIDDATA;
  928. }
  929. for (i = 0; i < nb_components; i++) {
  930. id = get_bits(&s->gb, 8) - 1;
  931. av_log(s->avctx, AV_LOG_DEBUG, "component: %d\n", id);
  932. /* find component index */
  933. for (index = 0; index < s->nb_components; index++)
  934. if (id == s->component_id[index])
  935. break;
  936. if (index == s->nb_components) {
  937. av_log(s->avctx, AV_LOG_ERROR,
  938. "decode_sos: index(%d) out of components\n", index);
  939. return AVERROR_INVALIDDATA;
  940. }
  941. /* Metasoft MJPEG codec has Cb and Cr swapped */
  942. if (s->avctx->codec_tag == MKTAG('M', 'T', 'S', 'J')
  943. && nb_components == 3 && s->nb_components == 3 && i)
  944. index = 3 - i;
  945. s->comp_index[i] = index;
  946. s->nb_blocks[i] = s->h_count[index] * s->v_count[index];
  947. s->h_scount[i] = s->h_count[index];
  948. s->v_scount[i] = s->v_count[index];
  949. s->dc_index[i] = get_bits(&s->gb, 4);
  950. s->ac_index[i] = get_bits(&s->gb, 4);
  951. if (s->dc_index[i] < 0 || s->ac_index[i] < 0 ||
  952. s->dc_index[i] >= 4 || s->ac_index[i] >= 4)
  953. goto out_of_range;
  954. if (!s->vlcs[0][s->dc_index[i]].table ||
  955. !s->vlcs[1][s->ac_index[i]].table)
  956. goto out_of_range;
  957. }
  958. predictor = get_bits(&s->gb, 8); /* JPEG Ss / lossless JPEG predictor /JPEG-LS NEAR */
  959. ilv = get_bits(&s->gb, 8); /* JPEG Se / JPEG-LS ILV */
  960. prev_shift = get_bits(&s->gb, 4); /* Ah */
  961. point_transform = get_bits(&s->gb, 4); /* Al */
  962. if (nb_components > 1) {
  963. /* interleaved stream */
  964. s->mb_width = (s->width + s->h_max * block_size - 1) / (s->h_max * block_size);
  965. s->mb_height = (s->height + s->v_max * block_size - 1) / (s->v_max * block_size);
  966. } else if (!s->ls) { /* skip this for JPEG-LS */
  967. h = s->h_max / s->h_scount[0];
  968. v = s->v_max / s->v_scount[0];
  969. s->mb_width = (s->width + h * block_size - 1) / (h * block_size);
  970. s->mb_height = (s->height + v * block_size - 1) / (v * block_size);
  971. s->nb_blocks[0] = 1;
  972. s->h_scount[0] = 1;
  973. s->v_scount[0] = 1;
  974. }
  975. if (s->avctx->debug & FF_DEBUG_PICT_INFO)
  976. av_log(s->avctx, AV_LOG_DEBUG, "%s %s p:%d >>:%d ilv:%d bits:%d %s\n",
  977. s->lossless ? "lossless" : "sequential DCT", s->rgb ? "RGB" : "",
  978. predictor, point_transform, ilv, s->bits,
  979. s->pegasus_rct ? "PRCT" : (s->rct ? "RCT" : ""));
  980. /* mjpeg-b can have padding bytes between sos and image data, skip them */
  981. for (i = s->mjpb_skiptosod; i > 0; i--)
  982. skip_bits(&s->gb, 8);
  983. next_field:
  984. for (i = 0; i < nb_components; i++)
  985. s->last_dc[i] = 1024;
  986. if (s->lossless) {
  987. if (CONFIG_JPEGLS_DECODER && s->ls) {
  988. // for () {
  989. // reset_ls_coding_parameters(s, 0);
  990. if ((ret = ff_jpegls_decode_picture(s, predictor,
  991. point_transform, ilv)) < 0)
  992. return ret;
  993. } else {
  994. if (s->rgb) {
  995. if ((ret = ljpeg_decode_rgb_scan(s, predictor,
  996. point_transform)) < 0)
  997. return ret;
  998. } else {
  999. if ((ret = ljpeg_decode_yuv_scan(s, predictor,
  1000. point_transform,
  1001. nb_components)) < 0)
  1002. return ret;
  1003. }
  1004. }
  1005. } else {
  1006. if (s->progressive && predictor) {
  1007. if ((ret = mjpeg_decode_scan_progressive_ac(s, predictor,
  1008. ilv, prev_shift,
  1009. point_transform,
  1010. mb_bitmask,
  1011. reference)) < 0)
  1012. return ret;
  1013. } else {
  1014. if ((ret = mjpeg_decode_scan(s, nb_components,
  1015. prev_shift, point_transform,
  1016. mb_bitmask, reference)) < 0)
  1017. return ret;
  1018. }
  1019. }
  1020. if (s->interlaced &&
  1021. get_bits_left(&s->gb) > 32 &&
  1022. show_bits(&s->gb, 8) == 0xFF) {
  1023. GetBitContext bak = s->gb;
  1024. align_get_bits(&bak);
  1025. if (show_bits(&bak, 16) == 0xFFD1) {
  1026. ff_dlog(s->avctx, "AVRn interlaced picture marker found\n");
  1027. s->gb = bak;
  1028. skip_bits(&s->gb, 16);
  1029. s->bottom_field ^= 1;
  1030. goto next_field;
  1031. }
  1032. }
  1033. emms_c();
  1034. return 0;
  1035. out_of_range:
  1036. av_log(s->avctx, AV_LOG_ERROR, "decode_sos: ac/dc index out of range\n");
  1037. return AVERROR_INVALIDDATA;
  1038. }
  1039. static int mjpeg_decode_dri(MJpegDecodeContext *s)
  1040. {
  1041. if (get_bits(&s->gb, 16) != 4)
  1042. return AVERROR_INVALIDDATA;
  1043. s->restart_interval = get_bits(&s->gb, 16);
  1044. s->restart_count = 0;
  1045. av_log(s->avctx, AV_LOG_DEBUG, "restart interval: %d\n",
  1046. s->restart_interval);
  1047. return 0;
  1048. }
  1049. static int mjpeg_decode_app(MJpegDecodeContext *s)
  1050. {
  1051. int len, id, i;
  1052. len = get_bits(&s->gb, 16);
  1053. if (len < 5)
  1054. return AVERROR_INVALIDDATA;
  1055. if (8 * len > get_bits_left(&s->gb))
  1056. return AVERROR_INVALIDDATA;
  1057. id = get_bits_long(&s->gb, 32);
  1058. id = av_be2ne32(id);
  1059. len -= 6;
  1060. if (s->avctx->debug & FF_DEBUG_STARTCODE)
  1061. av_log(s->avctx, AV_LOG_DEBUG, "APPx %8X\n", id);
  1062. /* Buggy AVID, it puts EOI only at every 10th frame. */
  1063. /* Also, this fourcc is used by non-avid files too, it holds some
  1064. information, but it's always present in AVID-created files. */
  1065. if (id == AV_RL32("AVI1")) {
  1066. /* structure:
  1067. 4bytes AVI1
  1068. 1bytes polarity
  1069. 1bytes always zero
  1070. 4bytes field_size
  1071. 4bytes field_size_less_padding
  1072. */
  1073. s->buggy_avid = 1;
  1074. i = get_bits(&s->gb, 8);
  1075. if (i == 2)
  1076. s->bottom_field = 1;
  1077. else if (i == 1)
  1078. s->bottom_field = 0;
  1079. #if 0
  1080. skip_bits(&s->gb, 8);
  1081. skip_bits(&s->gb, 32);
  1082. skip_bits(&s->gb, 32);
  1083. len -= 10;
  1084. #endif
  1085. goto out;
  1086. }
  1087. // len -= 2;
  1088. if (id == AV_RL32("JFIF")) {
  1089. int t_w, t_h, v1, v2;
  1090. skip_bits(&s->gb, 8); /* the trailing zero-byte */
  1091. v1 = get_bits(&s->gb, 8);
  1092. v2 = get_bits(&s->gb, 8);
  1093. skip_bits(&s->gb, 8);
  1094. s->avctx->sample_aspect_ratio.num = get_bits(&s->gb, 16);
  1095. s->avctx->sample_aspect_ratio.den = get_bits(&s->gb, 16);
  1096. ff_set_sar(s->avctx, s->avctx->sample_aspect_ratio);
  1097. if (s->avctx->debug & FF_DEBUG_PICT_INFO)
  1098. av_log(s->avctx, AV_LOG_INFO,
  1099. "mjpeg: JFIF header found (version: %x.%x) SAR=%d/%d\n",
  1100. v1, v2,
  1101. s->avctx->sample_aspect_ratio.num,
  1102. s->avctx->sample_aspect_ratio.den);
  1103. t_w = get_bits(&s->gb, 8);
  1104. t_h = get_bits(&s->gb, 8);
  1105. if (t_w && t_h) {
  1106. /* skip thumbnail */
  1107. if (len -10 - (t_w * t_h * 3) > 0)
  1108. len -= t_w * t_h * 3;
  1109. }
  1110. len -= 10;
  1111. goto out;
  1112. }
  1113. if (id == AV_RL32("Adob") && (get_bits(&s->gb, 8) == 'e')) {
  1114. if (s->avctx->debug & FF_DEBUG_PICT_INFO)
  1115. av_log(s->avctx, AV_LOG_INFO, "mjpeg: Adobe header found\n");
  1116. skip_bits(&s->gb, 16); /* version */
  1117. skip_bits(&s->gb, 16); /* flags0 */
  1118. skip_bits(&s->gb, 16); /* flags1 */
  1119. skip_bits(&s->gb, 8); /* transform */
  1120. len -= 7;
  1121. goto out;
  1122. }
  1123. if (id == AV_RL32("LJIF")) {
  1124. if (s->avctx->debug & FF_DEBUG_PICT_INFO)
  1125. av_log(s->avctx, AV_LOG_INFO,
  1126. "Pegasus lossless jpeg header found\n");
  1127. skip_bits(&s->gb, 16); /* version ? */
  1128. skip_bits(&s->gb, 16); /* unknown always 0? */
  1129. skip_bits(&s->gb, 16); /* unknown always 0? */
  1130. skip_bits(&s->gb, 16); /* unknown always 0? */
  1131. switch (get_bits(&s->gb, 8)) {
  1132. case 1:
  1133. s->rgb = 1;
  1134. s->pegasus_rct = 0;
  1135. break;
  1136. case 2:
  1137. s->rgb = 1;
  1138. s->pegasus_rct = 1;
  1139. break;
  1140. default:
  1141. av_log(s->avctx, AV_LOG_ERROR, "unknown colorspace\n");
  1142. }
  1143. len -= 9;
  1144. goto out;
  1145. }
  1146. /* Apple MJPEG-A */
  1147. if ((s->start_code == APP1) && (len > (0x28 - 8))) {
  1148. id = get_bits_long(&s->gb, 32);
  1149. id = av_be2ne32(id);
  1150. len -= 4;
  1151. /* Apple MJPEG-A */
  1152. if (id == AV_RL32("mjpg")) {
  1153. #if 0
  1154. skip_bits(&s->gb, 32); /* field size */
  1155. skip_bits(&s->gb, 32); /* pad field size */
  1156. skip_bits(&s->gb, 32); /* next off */
  1157. skip_bits(&s->gb, 32); /* quant off */
  1158. skip_bits(&s->gb, 32); /* huff off */
  1159. skip_bits(&s->gb, 32); /* image off */
  1160. skip_bits(&s->gb, 32); /* scan off */
  1161. skip_bits(&s->gb, 32); /* data off */
  1162. #endif
  1163. if (s->avctx->debug & FF_DEBUG_PICT_INFO)
  1164. av_log(s->avctx, AV_LOG_INFO, "mjpeg: Apple MJPEG-A header found\n");
  1165. }
  1166. }
  1167. out:
  1168. /* slow but needed for extreme adobe jpegs */
  1169. if (len < 0)
  1170. av_log(s->avctx, AV_LOG_ERROR,
  1171. "mjpeg: error, decode_app parser read over the end\n");
  1172. while (--len > 0)
  1173. skip_bits(&s->gb, 8);
  1174. return 0;
  1175. }
  1176. static int mjpeg_decode_com(MJpegDecodeContext *s)
  1177. {
  1178. int len = get_bits(&s->gb, 16);
  1179. if (len >= 2 && 8 * len - 16 <= get_bits_left(&s->gb)) {
  1180. int i;
  1181. char *cbuf = av_malloc(len - 1);
  1182. if (!cbuf)
  1183. return AVERROR(ENOMEM);
  1184. for (i = 0; i < len - 2; i++)
  1185. cbuf[i] = get_bits(&s->gb, 8);
  1186. if (i > 0 && cbuf[i - 1] == '\n')
  1187. cbuf[i - 1] = 0;
  1188. else
  1189. cbuf[i] = 0;
  1190. if (s->avctx->debug & FF_DEBUG_PICT_INFO)
  1191. av_log(s->avctx, AV_LOG_INFO, "mjpeg comment: '%s'\n", cbuf);
  1192. /* buggy avid, it puts EOI only at every 10th frame */
  1193. if (!strcmp(cbuf, "AVID")) {
  1194. s->buggy_avid = 1;
  1195. } else if (!strcmp(cbuf, "CS=ITU601"))
  1196. s->cs_itu601 = 1;
  1197. else if ((len > 20 && !strncmp(cbuf, "Intel(R) JPEG Library", 21)) ||
  1198. (len > 19 && !strncmp(cbuf, "Metasoft MJPEG Codec", 20)))
  1199. s->flipped = 1;
  1200. av_free(cbuf);
  1201. }
  1202. return 0;
  1203. }
  1204. /* return the 8 bit start code value and update the search
  1205. state. Return -1 if no start code found */
  1206. static int find_marker(const uint8_t **pbuf_ptr, const uint8_t *buf_end)
  1207. {
  1208. const uint8_t *buf_ptr;
  1209. unsigned int v, v2;
  1210. int val;
  1211. #ifdef DEBUG
  1212. int skipped = 0;
  1213. #endif
  1214. buf_ptr = *pbuf_ptr;
  1215. while (buf_ptr < buf_end) {
  1216. v = *buf_ptr++;
  1217. v2 = *buf_ptr;
  1218. if ((v == 0xff) && (v2 >= 0xc0) && (v2 <= 0xfe) && buf_ptr < buf_end) {
  1219. val = *buf_ptr++;
  1220. goto found;
  1221. }
  1222. #ifdef DEBUG
  1223. skipped++;
  1224. #endif
  1225. }
  1226. val = -1;
  1227. found:
  1228. ff_dlog(NULL, "find_marker skipped %d bytes\n", skipped);
  1229. *pbuf_ptr = buf_ptr;
  1230. return val;
  1231. }
  1232. int ff_mjpeg_find_marker(MJpegDecodeContext *s,
  1233. const uint8_t **buf_ptr, const uint8_t *buf_end,
  1234. const uint8_t **unescaped_buf_ptr,
  1235. int *unescaped_buf_size)
  1236. {
  1237. int start_code;
  1238. start_code = find_marker(buf_ptr, buf_end);
  1239. av_fast_padded_malloc(&s->buffer, &s->buffer_size, buf_end - *buf_ptr);
  1240. if (!s->buffer)
  1241. return AVERROR(ENOMEM);
  1242. /* unescape buffer of SOS, use special treatment for JPEG-LS */
  1243. if (start_code == SOS && !s->ls) {
  1244. const uint8_t *src = *buf_ptr;
  1245. uint8_t *dst = s->buffer;
  1246. while (src < buf_end) {
  1247. uint8_t x = *(src++);
  1248. *(dst++) = x;
  1249. if (s->avctx->codec_id != AV_CODEC_ID_THP) {
  1250. if (x == 0xff) {
  1251. while (src < buf_end && x == 0xff)
  1252. x = *(src++);
  1253. if (x >= 0xd0 && x <= 0xd7)
  1254. *(dst++) = x;
  1255. else if (x)
  1256. break;
  1257. }
  1258. }
  1259. }
  1260. *unescaped_buf_ptr = s->buffer;
  1261. *unescaped_buf_size = dst - s->buffer;
  1262. memset(s->buffer + *unescaped_buf_size, 0,
  1263. AV_INPUT_BUFFER_PADDING_SIZE);
  1264. av_log(s->avctx, AV_LOG_DEBUG, "escaping removed %td bytes\n",
  1265. (buf_end - *buf_ptr) - (dst - s->buffer));
  1266. } else if (start_code == SOS && s->ls) {
  1267. const uint8_t *src = *buf_ptr;
  1268. uint8_t *dst = s->buffer;
  1269. int bit_count = 0;
  1270. int t = 0, b = 0;
  1271. PutBitContext pb;
  1272. s->cur_scan++;
  1273. /* find marker */
  1274. while (src + t < buf_end) {
  1275. uint8_t x = src[t++];
  1276. if (x == 0xff) {
  1277. while ((src + t < buf_end) && x == 0xff)
  1278. x = src[t++];
  1279. if (x & 0x80) {
  1280. t -= 2;
  1281. break;
  1282. }
  1283. }
  1284. }
  1285. bit_count = t * 8;
  1286. init_put_bits(&pb, dst, t);
  1287. /* unescape bitstream */
  1288. while (b < t) {
  1289. uint8_t x = src[b++];
  1290. put_bits(&pb, 8, x);
  1291. if (x == 0xFF) {
  1292. x = src[b++];
  1293. put_bits(&pb, 7, x);
  1294. bit_count--;
  1295. }
  1296. }
  1297. flush_put_bits(&pb);
  1298. *unescaped_buf_ptr = dst;
  1299. *unescaped_buf_size = (bit_count + 7) >> 3;
  1300. memset(s->buffer + *unescaped_buf_size, 0,
  1301. AV_INPUT_BUFFER_PADDING_SIZE);
  1302. } else {
  1303. *unescaped_buf_ptr = *buf_ptr;
  1304. *unescaped_buf_size = buf_end - *buf_ptr;
  1305. }
  1306. return start_code;
  1307. }
  1308. int ff_mjpeg_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,
  1309. AVPacket *avpkt)
  1310. {
  1311. AVFrame *frame = data;
  1312. const uint8_t *buf = avpkt->data;
  1313. int buf_size = avpkt->size;
  1314. MJpegDecodeContext *s = avctx->priv_data;
  1315. const uint8_t *buf_end, *buf_ptr;
  1316. const uint8_t *unescaped_buf_ptr;
  1317. int unescaped_buf_size;
  1318. int start_code;
  1319. int ret = 0;
  1320. s->got_picture = 0; // picture from previous image can not be reused
  1321. buf_ptr = buf;
  1322. buf_end = buf + buf_size;
  1323. while (buf_ptr < buf_end) {
  1324. /* find start next marker */
  1325. start_code = ff_mjpeg_find_marker(s, &buf_ptr, buf_end,
  1326. &unescaped_buf_ptr,
  1327. &unescaped_buf_size);
  1328. /* EOF */
  1329. if (start_code < 0) {
  1330. goto the_end;
  1331. } else if (unescaped_buf_size > INT_MAX / 8) {
  1332. av_log(avctx, AV_LOG_ERROR,
  1333. "MJPEG packet 0x%x too big (%d/%d), corrupt data?\n",
  1334. start_code, unescaped_buf_size, buf_size);
  1335. return AVERROR_INVALIDDATA;
  1336. }
  1337. av_log(avctx, AV_LOG_DEBUG, "marker=%x avail_size_in_buf=%td\n",
  1338. start_code, buf_end - buf_ptr);
  1339. ret = init_get_bits(&s->gb, unescaped_buf_ptr,
  1340. unescaped_buf_size * 8);
  1341. if (ret < 0)
  1342. return ret;
  1343. s->start_code = start_code;
  1344. if (s->avctx->debug & FF_DEBUG_STARTCODE)
  1345. av_log(avctx, AV_LOG_DEBUG, "startcode: %X\n", start_code);
  1346. /* process markers */
  1347. if (start_code >= 0xd0 && start_code <= 0xd7)
  1348. av_log(avctx, AV_LOG_DEBUG,
  1349. "restart marker: %d\n", start_code & 0x0f);
  1350. /* APP fields */
  1351. else if (start_code >= APP0 && start_code <= APP15)
  1352. mjpeg_decode_app(s);
  1353. /* Comment */
  1354. else if (start_code == COM) {
  1355. ret = mjpeg_decode_com(s);
  1356. if (ret < 0)
  1357. return ret;
  1358. }
  1359. if (!CONFIG_JPEGLS_DECODER &&
  1360. (start_code == SOF48 || start_code == LSE)) {
  1361. av_log(avctx, AV_LOG_ERROR, "JPEG-LS support not enabled.\n");
  1362. return AVERROR(ENOSYS);
  1363. }
  1364. switch (start_code) {
  1365. case SOI:
  1366. s->restart_interval = 0;
  1367. s->restart_count = 0;
  1368. /* nothing to do on SOI */
  1369. break;
  1370. case DQT:
  1371. ff_mjpeg_decode_dqt(s);
  1372. break;
  1373. case DHT:
  1374. if ((ret = ff_mjpeg_decode_dht(s)) < 0) {
  1375. av_log(avctx, AV_LOG_ERROR, "huffman table decode error\n");
  1376. return ret;
  1377. }
  1378. break;
  1379. case SOF0:
  1380. case SOF1:
  1381. s->lossless = 0;
  1382. s->ls = 0;
  1383. s->progressive = 0;
  1384. if ((ret = ff_mjpeg_decode_sof(s)) < 0)
  1385. return ret;
  1386. break;
  1387. case SOF2:
  1388. s->lossless = 0;
  1389. s->ls = 0;
  1390. s->progressive = 1;
  1391. if ((ret = ff_mjpeg_decode_sof(s)) < 0)
  1392. return ret;
  1393. break;
  1394. case SOF3:
  1395. s->lossless = 1;
  1396. s->ls = 0;
  1397. s->progressive = 0;
  1398. if ((ret = ff_mjpeg_decode_sof(s)) < 0)
  1399. return ret;
  1400. break;
  1401. case SOF48:
  1402. s->lossless = 1;
  1403. s->ls = 1;
  1404. s->progressive = 0;
  1405. if ((ret = ff_mjpeg_decode_sof(s)) < 0)
  1406. return ret;
  1407. break;
  1408. case LSE:
  1409. if (!CONFIG_JPEGLS_DECODER ||
  1410. (ret = ff_jpegls_decode_lse(s)) < 0)
  1411. return ret;
  1412. break;
  1413. case EOI:
  1414. s->cur_scan = 0;
  1415. if ((s->buggy_avid && !s->interlaced) || s->restart_interval)
  1416. break;
  1417. eoi_parser:
  1418. if (!s->got_picture) {
  1419. av_log(avctx, AV_LOG_WARNING,
  1420. "Found EOI before any SOF, ignoring\n");
  1421. break;
  1422. }
  1423. if (s->interlaced) {
  1424. s->bottom_field ^= 1;
  1425. /* if not bottom field, do not output image yet */
  1426. if (s->bottom_field == !s->interlace_polarity)
  1427. goto not_the_end;
  1428. }
  1429. if ((ret = av_frame_ref(frame, s->picture_ptr)) < 0)
  1430. return ret;
  1431. if (s->flipped) {
  1432. int i;
  1433. for (i = 0; frame->data[i]; i++) {
  1434. int h = frame->height >> ((i == 1 || i == 2) ?
  1435. s->pix_desc->log2_chroma_h : 0);
  1436. frame->data[i] += frame->linesize[i] * (h - 1);
  1437. frame->linesize[i] *= -1;
  1438. }
  1439. }
  1440. *got_frame = 1;
  1441. if (!s->lossless &&
  1442. avctx->debug & FF_DEBUG_QP) {
  1443. av_log(avctx, AV_LOG_DEBUG,
  1444. "QP: %d\n", FFMAX3(s->qscale[0],
  1445. s->qscale[1],
  1446. s->qscale[2]));
  1447. }
  1448. goto the_end;
  1449. case SOS:
  1450. if (!s->got_picture) {
  1451. av_log(avctx, AV_LOG_WARNING,
  1452. "Can not process SOS before SOF, skipping\n");
  1453. break;
  1454. }
  1455. if ((ret = ff_mjpeg_decode_sos(s, NULL, NULL)) < 0 &&
  1456. (avctx->err_recognition & AV_EF_EXPLODE))
  1457. return ret;
  1458. /* buggy avid puts EOI every 10-20th frame */
  1459. /* if restart period is over process EOI */
  1460. if ((s->buggy_avid && !s->interlaced) || s->restart_interval)
  1461. goto eoi_parser;
  1462. break;
  1463. case DRI:
  1464. mjpeg_decode_dri(s);
  1465. break;
  1466. case SOF5:
  1467. case SOF6:
  1468. case SOF7:
  1469. case SOF9:
  1470. case SOF10:
  1471. case SOF11:
  1472. case SOF13:
  1473. case SOF14:
  1474. case SOF15:
  1475. case JPG:
  1476. av_log(avctx, AV_LOG_ERROR,
  1477. "mjpeg: unsupported coding type (%x)\n", start_code);
  1478. break;
  1479. }
  1480. not_the_end:
  1481. /* eof process start code */
  1482. buf_ptr += (get_bits_count(&s->gb) + 7) / 8;
  1483. av_log(avctx, AV_LOG_DEBUG,
  1484. "marker parser used %d bytes (%d bits)\n",
  1485. (get_bits_count(&s->gb) + 7) / 8, get_bits_count(&s->gb));
  1486. }
  1487. if (s->got_picture) {
  1488. av_log(avctx, AV_LOG_WARNING, "EOI missing, emulating\n");
  1489. goto eoi_parser;
  1490. }
  1491. av_log(avctx, AV_LOG_FATAL, "No JPEG data found in image\n");
  1492. return AVERROR_INVALIDDATA;
  1493. the_end:
  1494. av_log(avctx, AV_LOG_DEBUG, "mjpeg decode frame unused %td bytes\n",
  1495. buf_end - buf_ptr);
  1496. // return buf_end - buf_ptr;
  1497. return buf_ptr - buf;
  1498. }
  1499. av_cold int ff_mjpeg_decode_end(AVCodecContext *avctx)
  1500. {
  1501. MJpegDecodeContext *s = avctx->priv_data;
  1502. int i, j;
  1503. if (s->picture) {
  1504. av_frame_free(&s->picture);
  1505. s->picture_ptr = NULL;
  1506. } else if (s->picture_ptr)
  1507. av_frame_unref(s->picture_ptr);
  1508. av_free(s->buffer);
  1509. av_freep(&s->ljpeg_buffer);
  1510. s->ljpeg_buffer_size = 0;
  1511. for (i = 0; i < 3; i++) {
  1512. for (j = 0; j < 4; j++)
  1513. ff_free_vlc(&s->vlcs[i][j]);
  1514. }
  1515. for (i = 0; i < MAX_COMPONENTS; i++) {
  1516. av_freep(&s->blocks[i]);
  1517. av_freep(&s->last_nnz[i]);
  1518. }
  1519. return 0;
  1520. }
  1521. #define OFFSET(x) offsetof(MJpegDecodeContext, x)
  1522. #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  1523. static const AVOption options[] = {
  1524. { "extern_huff", "Use external huffman table.",
  1525. OFFSET(extern_huff), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD },
  1526. { NULL },
  1527. };
  1528. static const AVClass mjpegdec_class = {
  1529. .class_name = "MJPEG decoder",
  1530. .item_name = av_default_item_name,
  1531. .option = options,
  1532. .version = LIBAVUTIL_VERSION_INT,
  1533. };
  1534. AVCodec ff_mjpeg_decoder = {
  1535. .name = "mjpeg",
  1536. .long_name = NULL_IF_CONFIG_SMALL("MJPEG (Motion JPEG)"),
  1537. .type = AVMEDIA_TYPE_VIDEO,
  1538. .id = AV_CODEC_ID_MJPEG,
  1539. .priv_data_size = sizeof(MJpegDecodeContext),
  1540. .init = ff_mjpeg_decode_init,
  1541. .close = ff_mjpeg_decode_end,
  1542. .decode = ff_mjpeg_decode_frame,
  1543. .capabilities = AV_CODEC_CAP_DR1,
  1544. .priv_class = &mjpegdec_class,
  1545. .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
  1546. };
  1547. AVCodec ff_thp_decoder = {
  1548. .name = "thp",
  1549. .long_name = NULL_IF_CONFIG_SMALL("Nintendo Gamecube THP video"),
  1550. .type = AVMEDIA_TYPE_VIDEO,
  1551. .id = AV_CODEC_ID_THP,
  1552. .priv_data_size = sizeof(MJpegDecodeContext),
  1553. .init = ff_mjpeg_decode_init,
  1554. .close = ff_mjpeg_decode_end,
  1555. .decode = ff_mjpeg_decode_frame,
  1556. .capabilities = AV_CODEC_CAP_DR1,
  1557. .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
  1558. };