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