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