FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
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 FFmpeg.
12  *
13  * FFmpeg 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  * FFmpeg 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 FFmpeg; if not, write to the Free Software
25  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26  */
27 
28 /**
29  * @file
30  * MJPEG decoder.
31  */
32 
33 #include "libavutil/imgutils.h"
34 #include "libavutil/avassert.h"
35 #include "libavutil/opt.h"
36 #include "avcodec.h"
37 #include "blockdsp.h"
38 #include "copy_block.h"
39 #include "idctdsp.h"
40 #include "internal.h"
41 #include "mjpeg.h"
42 #include "mjpegdec.h"
43 #include "jpeglsdec.h"
44 #include "tiff.h"
45 #include "exif.h"
46 #include "bytestream.h"
47 
48 
49 static int build_vlc(VLC *vlc, const uint8_t *bits_table,
50  const uint8_t *val_table, int nb_codes,
51  int use_static, int is_ac)
52 {
53  uint8_t huff_size[256] = { 0 };
54  uint16_t huff_code[256];
55  uint16_t huff_sym[256];
56  int i;
57 
58  av_assert0(nb_codes <= 256);
59 
60  ff_mjpeg_build_huffman_codes(huff_size, huff_code, bits_table, val_table);
61 
62  for (i = 0; i < 256; i++)
63  huff_sym[i] = i + 16 * is_ac;
64 
65  if (is_ac)
66  huff_sym[0] = 16 * 256;
67 
68  return ff_init_vlc_sparse(vlc, 9, nb_codes, huff_size, 1, 1,
69  huff_code, 2, 2, huff_sym, 2, 2, use_static);
70 }
71 
73 {
75  avpriv_mjpeg_val_dc, 12, 0, 0);
77  avpriv_mjpeg_val_dc, 12, 0, 0);
86 }
87 
89 {
90  s->buggy_avid = 1;
91  if (len > 14 && buf[12] == 1) /* 1 - NTSC */
92  s->interlace_polarity = 1;
93  if (len > 14 && buf[12] == 2) /* 2 - PAL */
94  s->interlace_polarity = 0;
95  if (s->avctx->debug & FF_DEBUG_PICT_INFO)
96  av_log(s->avctx, AV_LOG_INFO, "AVID: len:%d %d\n", len, len > 14 ? buf[12] : -1);
97 }
98 
100 {
101  MJpegDecodeContext *s = avctx->priv_data;
102 
103  if (!s->picture_ptr) {
104  s->picture = av_frame_alloc();
105  if (!s->picture)
106  return AVERROR(ENOMEM);
107  s->picture_ptr = s->picture;
108  }
109 
110  s->avctx = avctx;
111  ff_blockdsp_init(&s->bdsp, avctx);
112  ff_hpeldsp_init(&s->hdsp, avctx->flags);
113  ff_idctdsp_init(&s->idsp, avctx);
116  s->buffer_size = 0;
117  s->buffer = NULL;
118  s->start_code = -1;
119  s->first_picture = 1;
120  s->got_picture = 0;
121  s->org_height = avctx->coded_height;
123  avctx->colorspace = AVCOL_SPC_BT470BG;
124 
126 
127  if (s->extern_huff) {
128  av_log(avctx, AV_LOG_INFO, "using external huffman table\n");
129  init_get_bits(&s->gb, avctx->extradata, avctx->extradata_size * 8);
130  if (ff_mjpeg_decode_dht(s)) {
131  av_log(avctx, AV_LOG_ERROR,
132  "error using external huffman table, switching back to internal\n");
134  }
135  }
136  if (avctx->field_order == AV_FIELD_BB) { /* quicktime icefloe 019 */
137  s->interlace_polarity = 1; /* bottom field first */
138  av_log(avctx, AV_LOG_DEBUG, "bottom field first\n");
139  } else if (avctx->field_order == AV_FIELD_UNKNOWN) {
140  if (avctx->codec_tag == AV_RL32("MJPG"))
141  s->interlace_polarity = 1;
142  }
143 
144  if ( avctx->extradata_size > 8
145  && AV_RL32(avctx->extradata) == 0x2C
146  && AV_RL32(avctx->extradata+4) == 0x18) {
147  parse_avid(s, avctx->extradata, avctx->extradata_size);
148  }
149 
150  if (avctx->codec->id == AV_CODEC_ID_AMV)
151  s->flipped = 1;
152 
153  return 0;
154 }
155 
156 
157 /* quantize tables */
159 {
160  int len, index, i, j;
161 
162  len = get_bits(&s->gb, 16) - 2;
163 
164  while (len >= 65) {
165  int pr = get_bits(&s->gb, 4);
166  if (pr > 1) {
167  av_log(s->avctx, AV_LOG_ERROR, "dqt: invalid precision\n");
168  return AVERROR_INVALIDDATA;
169  }
170  index = get_bits(&s->gb, 4);
171  if (index >= 4)
172  return -1;
173  av_log(s->avctx, AV_LOG_DEBUG, "index=%d\n", index);
174  /* read quant table */
175  for (i = 0; i < 64; i++) {
176  j = s->scantable.permutated[i];
177  s->quant_matrixes[index][j] = get_bits(&s->gb, pr ? 16 : 8);
178  }
179 
180  // XXX FIXME finetune, and perhaps add dc too
181  s->qscale[index] = FFMAX(s->quant_matrixes[index][s->scantable.permutated[1]],
182  s->quant_matrixes[index][s->scantable.permutated[8]]) >> 1;
183  av_log(s->avctx, AV_LOG_DEBUG, "qscale[%d]: %d\n",
184  index, s->qscale[index]);
185  len -= 65;
186  }
187  return 0;
188 }
189 
190 /* decode huffman tables and build VLC decoders */
192 {
193  int len, index, i, class, n, v, code_max;
194  uint8_t bits_table[17];
195  uint8_t val_table[256];
196  int ret = 0;
197 
198  len = get_bits(&s->gb, 16) - 2;
199 
200  while (len > 0) {
201  if (len < 17)
202  return AVERROR_INVALIDDATA;
203  class = get_bits(&s->gb, 4);
204  if (class >= 2)
205  return AVERROR_INVALIDDATA;
206  index = get_bits(&s->gb, 4);
207  if (index >= 4)
208  return AVERROR_INVALIDDATA;
209  n = 0;
210  for (i = 1; i <= 16; i++) {
211  bits_table[i] = get_bits(&s->gb, 8);
212  n += bits_table[i];
213  }
214  len -= 17;
215  if (len < n || n > 256)
216  return AVERROR_INVALIDDATA;
217 
218  code_max = 0;
219  for (i = 0; i < n; i++) {
220  v = get_bits(&s->gb, 8);
221  if (v > code_max)
222  code_max = v;
223  val_table[i] = v;
224  }
225  len -= n;
226 
227  /* build VLC and flush previous vlc if present */
228  ff_free_vlc(&s->vlcs[class][index]);
229  av_log(s->avctx, AV_LOG_DEBUG, "class=%d index=%d nb_codes=%d\n",
230  class, index, code_max + 1);
231  if ((ret = build_vlc(&s->vlcs[class][index], bits_table, val_table,
232  code_max + 1, 0, class > 0)) < 0)
233  return ret;
234 
235  if (class > 0) {
236  ff_free_vlc(&s->vlcs[2][index]);
237  if ((ret = build_vlc(&s->vlcs[2][index], bits_table, val_table,
238  code_max + 1, 0, 0)) < 0)
239  return ret;
240  }
241  }
242  return 0;
243 }
244 
246 {
247  int len, nb_components, i, width, height, pix_fmt_id, ret;
248  int h_count[MAX_COMPONENTS];
249  int v_count[MAX_COMPONENTS];
250 
251  s->cur_scan = 0;
252  s->upscale_h = s->upscale_v = 0;
253 
254  /* XXX: verify len field validity */
255  len = get_bits(&s->gb, 16);
257  s->bits = get_bits(&s->gb, 8);
258 
259  if (s->pegasus_rct)
260  s->bits = 9;
261  if (s->bits == 9 && !s->pegasus_rct)
262  s->rct = 1; // FIXME ugly
263 
264  if(s->lossless && s->avctx->lowres){
265  av_log(s->avctx, AV_LOG_ERROR, "lowres is not possible with lossless jpeg\n");
266  return -1;
267  }
268 
269  height = get_bits(&s->gb, 16);
270  width = get_bits(&s->gb, 16);
271 
272  if (s->avctx->codec_id == AV_CODEC_ID_AMV && (height&15))
273  avpriv_request_sample(s->avctx, "non mod 16 height AMV\n");
274 
275  // HACK for odd_height.mov
276  if (s->interlaced && s->width == width && s->height == height + 1)
277  height= s->height;
278 
279  av_log(s->avctx, AV_LOG_DEBUG, "sof0: picture: %dx%d\n", width, height);
280  if (av_image_check_size(width, height, 0, s->avctx))
281  return AVERROR_INVALIDDATA;
282 
283  nb_components = get_bits(&s->gb, 8);
284  if (nb_components <= 0 ||
285  nb_components > MAX_COMPONENTS)
286  return -1;
287  if (s->interlaced && (s->bottom_field == !s->interlace_polarity)) {
288  if (nb_components != s->nb_components) {
290  "nb_components changing in interlaced picture\n");
291  return AVERROR_INVALIDDATA;
292  }
293  }
294  if (s->ls && !(s->bits <= 8 || nb_components == 1)) {
296  "JPEG-LS that is not <= 8 "
297  "bits/component or 16-bit gray");
298  return AVERROR_PATCHWELCOME;
299  }
300  s->nb_components = nb_components;
301  s->h_max = 1;
302  s->v_max = 1;
303  memset(h_count, 0, sizeof(h_count));
304  memset(v_count, 0, sizeof(v_count));
305  for (i = 0; i < nb_components; i++) {
306  /* component id */
307  s->component_id[i] = get_bits(&s->gb, 8) - 1;
308  h_count[i] = get_bits(&s->gb, 4);
309  v_count[i] = get_bits(&s->gb, 4);
310  /* compute hmax and vmax (only used in interleaved case) */
311  if (h_count[i] > s->h_max)
312  s->h_max = h_count[i];
313  if (v_count[i] > s->v_max)
314  s->v_max = v_count[i];
315  s->quant_index[i] = get_bits(&s->gb, 8);
316  if (s->quant_index[i] >= 4) {
317  av_log(s->avctx, AV_LOG_ERROR, "quant_index is invalid\n");
318  return AVERROR_INVALIDDATA;
319  }
320  if (!h_count[i] || !v_count[i]) {
322  "Invalid sampling factor in component %d %d:%d\n",
323  i, h_count[i], v_count[i]);
324  return AVERROR_INVALIDDATA;
325  }
326 
327  av_log(s->avctx, AV_LOG_DEBUG, "component %d %d:%d id: %d quant:%d\n",
328  i, h_count[i], v_count[i],
329  s->component_id[i], s->quant_index[i]);
330  }
331 
332  if (s->ls && (s->h_max > 1 || s->v_max > 1)) {
333  avpriv_report_missing_feature(s->avctx, "Subsampling in JPEG-LS");
334  return AVERROR_PATCHWELCOME;
335  }
336 
337 
338  /* if different size, realloc/alloc picture */
339  if ( width != s->width || height != s->height
340  || memcmp(s->h_count, h_count, sizeof(h_count))
341  || memcmp(s->v_count, v_count, sizeof(v_count))) {
342 
343  s->width = width;
344  s->height = height;
345  memcpy(s->h_count, h_count, sizeof(h_count));
346  memcpy(s->v_count, v_count, sizeof(v_count));
347  s->interlaced = 0;
348  s->got_picture = 0;
349 
350  /* test interlaced mode */
351  if (s->first_picture &&
352  s->org_height != 0 &&
353  s->height < ((s->org_height * 3) / 4)) {
354  s->interlaced = 1;
358  height *= 2;
359  }
360 
361  ret = ff_set_dimensions(s->avctx, width, height);
362  if (ret < 0)
363  return ret;
364 
365  s->first_picture = 0;
366  }
367 
368  if (s->got_picture && s->interlaced && (s->bottom_field == !s->interlace_polarity)) {
369  if (s->progressive) {
370  avpriv_request_sample(s->avctx, "progressively coded interlaced picture");
371  return AVERROR_INVALIDDATA;
372  }
373  } else{
374  if (s->v_max == 1 && s->h_max == 1 && s->lossless==1 && (nb_components==3 || nb_components==4))
375  s->rgb = 1;
376  else if (!s->lossless)
377  s->rgb = 0;
378  /* XXX: not complete test ! */
379  pix_fmt_id = (s->h_count[0] << 28) | (s->v_count[0] << 24) |
380  (s->h_count[1] << 20) | (s->v_count[1] << 16) |
381  (s->h_count[2] << 12) | (s->v_count[2] << 8) |
382  (s->h_count[3] << 4) | s->v_count[3];
383  av_log(s->avctx, AV_LOG_DEBUG, "pix fmt id %x\n", pix_fmt_id);
384  /* NOTE we do not allocate pictures large enough for the possible
385  * padding of h/v_count being 4 */
386  if (!(pix_fmt_id & 0xD0D0D0D0))
387  pix_fmt_id -= (pix_fmt_id & 0xF0F0F0F0) >> 1;
388  if (!(pix_fmt_id & 0x0D0D0D0D))
389  pix_fmt_id -= (pix_fmt_id & 0x0F0F0F0F) >> 1;
390 
391  for (i = 0; i < 8; i++) {
392  int j = 6 + (i&1) - (i&6);
393  int is = (pix_fmt_id >> (4*i)) & 0xF;
394  int js = (pix_fmt_id >> (4*j)) & 0xF;
395 
396  if (is == 1 && js != 2 && (i < 2 || i > 5))
397  js = (pix_fmt_id >> ( 8 + 4*(i&1))) & 0xF;
398  if (is == 1 && js != 2 && (i < 2 || i > 5))
399  js = (pix_fmt_id >> (16 + 4*(i&1))) & 0xF;
400 
401  if (is == 1 && js == 2) {
402  if (i & 1) s->upscale_h |= 1 << (j/2);
403  else s->upscale_v |= 1 << (j/2);
404  }
405  }
406 
407  switch (pix_fmt_id) {
408  case 0x11111100:
409  if (s->rgb)
411  else {
412  if (s->component_id[0] == 'Q' && s->component_id[1] == 'F' && s->component_id[2] == 'A') {
414  } else {
418  }
419  }
420  av_assert0(s->nb_components == 3);
421  break;
422  case 0x11111111:
423  if (s->rgb)
425  else {
426  if (s->adobe_transform == 0 && s->bits <= 8) {
428  } else {
431  }
432  }
433  av_assert0(s->nb_components == 4);
434  break;
435  case 0x22111122:
436  if (s->adobe_transform == 0 && s->bits <= 8) {
438  s->upscale_v = 6;
439  s->upscale_h = 6;
440  s->chroma_height = s->height;
441  } else if (s->adobe_transform == 2 && s->bits <= 8) {
443  s->upscale_v = 6;
444  s->upscale_h = 6;
445  s->chroma_height = s->height;
447  } else {
448  if (s->bits <= 8) s->avctx->pix_fmt = AV_PIX_FMT_YUVA420P;
451  }
452  av_assert0(s->nb_components == 4);
453  break;
454  case 0x12121100:
455  case 0x22122100:
456  case 0x21211100:
457  case 0x22211200:
459  else
460  goto unk_pixfmt;
462  s->chroma_height = s->height;
463  break;
464  case 0x22221100:
465  case 0x22112200:
466  case 0x11222200:
468  else
469  goto unk_pixfmt;
471  s->chroma_height = (s->height + 1) / 2;
472  break;
473  case 0x11000000:
474  case 0x13000000:
475  case 0x14000000:
476  case 0x31000000:
477  case 0x33000000:
478  case 0x34000000:
479  case 0x41000000:
480  case 0x43000000:
481  case 0x44000000:
482  if(s->bits <= 8)
484  else
486  break;
487  case 0x12111100:
488  case 0x14121200:
489  case 0x22211100:
490  case 0x22112100:
492  else
493  goto unk_pixfmt;
495  s->chroma_height = (s->height + 1) / 2;
496  break;
497  case 0x21111100:
501  break;
502  case 0x22121100:
503  case 0x22111200:
505  else
506  goto unk_pixfmt;
508  break;
509  case 0x22111100:
510  case 0x42111100:
514  if (pix_fmt_id == 0x42111100) {
515  s->upscale_h = 6;
516  s->chroma_height = (s->height + 1) / 2;
517  }
518  break;
519  case 0x41111100:
521  else
522  goto unk_pixfmt;
524  break;
525  default:
526 unk_pixfmt:
527  av_log(s->avctx, AV_LOG_ERROR, "Unhandled pixel format 0x%x\n", pix_fmt_id);
528  s->upscale_h = s->upscale_v = 0;
529  return AVERROR_PATCHWELCOME;
530  }
531  if ((s->upscale_h || s->upscale_v) && s->avctx->lowres) {
532  av_log(s->avctx, AV_LOG_ERROR, "lowres not supported for weird subsampling\n");
533  return AVERROR_PATCHWELCOME;
534  }
535  if (s->ls) {
536  s->upscale_h = s->upscale_v = 0;
537  if (s->nb_components > 1)
539  else if (s->palette_index && s->bits <= 8)
541  else if (s->bits <= 8)
543  else
545  }
546 
548  if (!s->pix_desc) {
549  av_log(s->avctx, AV_LOG_ERROR, "Could not get a pixel format descriptor.\n");
550  return AVERROR_BUG;
551  }
552 
555  return -1;
557  s->picture_ptr->key_frame = 1;
558  s->got_picture = 1;
559 
560  for (i = 0; i < 4; i++)
561  s->linesize[i] = s->picture_ptr->linesize[i] << s->interlaced;
562 
563  av_dlog(s->avctx, "%d %d %d %d %d %d\n",
564  s->width, s->height, s->linesize[0], s->linesize[1],
565  s->interlaced, s->avctx->height);
566 
567  if (len != (8 + (3 * nb_components)))
568  av_log(s->avctx, AV_LOG_DEBUG, "decode_sof0: error, len(%d) mismatch\n", len);
569  }
570 
571  if (s->rgb && !s->lossless && !s->ls) {
572  av_log(s->avctx, AV_LOG_ERROR, "Unsupported coding and pixel format combination\n");
573  return AVERROR_PATCHWELCOME;
574  }
575 
576  /* totally blank picture as progressive JPEG will only add details to it */
577  if (s->progressive) {
578  int bw = (width + s->h_max * 8 - 1) / (s->h_max * 8);
579  int bh = (height + s->v_max * 8 - 1) / (s->v_max * 8);
580  for (i = 0; i < s->nb_components; i++) {
581  int size = bw * bh * s->h_count[i] * s->v_count[i];
582  av_freep(&s->blocks[i]);
583  av_freep(&s->last_nnz[i]);
584  s->blocks[i] = av_mallocz_array(size, sizeof(**s->blocks));
585  s->last_nnz[i] = av_mallocz_array(size, sizeof(**s->last_nnz));
586  if (!s->blocks[i] || !s->last_nnz[i])
587  return AVERROR(ENOMEM);
588  s->block_stride[i] = bw * s->h_count[i];
589  }
590  memset(s->coefs_finished, 0, sizeof(s->coefs_finished));
591  }
592  return 0;
593 }
594 
595 static inline int mjpeg_decode_dc(MJpegDecodeContext *s, int dc_index)
596 {
597  int code;
598  code = get_vlc2(&s->gb, s->vlcs[0][dc_index].table, 9, 2);
599  if (code < 0 || code > 16) {
601  "mjpeg_decode_dc: bad vlc: %d:%d (%p)\n",
602  0, dc_index, &s->vlcs[0][dc_index]);
603  return 0xfffff;
604  }
605 
606  if (code)
607  return get_xbits(&s->gb, code);
608  else
609  return 0;
610 }
611 
612 /* decode block and dequantize */
613 static int decode_block(MJpegDecodeContext *s, int16_t *block, int component,
614  int dc_index, int ac_index, int16_t *quant_matrix)
615 {
616  int code, i, j, level, val;
617 
618  /* DC coef */
619  val = mjpeg_decode_dc(s, dc_index);
620  if (val == 0xfffff) {
621  av_log(s->avctx, AV_LOG_ERROR, "error dc\n");
622  return AVERROR_INVALIDDATA;
623  }
624  val = val * quant_matrix[0] + s->last_dc[component];
625  s->last_dc[component] = val;
626  block[0] = val;
627  /* AC coefs */
628  i = 0;
629  {OPEN_READER(re, &s->gb);
630  do {
631  UPDATE_CACHE(re, &s->gb);
632  GET_VLC(code, re, &s->gb, s->vlcs[1][ac_index].table, 9, 2);
633 
634  i += ((unsigned)code) >> 4;
635  code &= 0xf;
636  if (code) {
637  if (code > MIN_CACHE_BITS - 16)
638  UPDATE_CACHE(re, &s->gb);
639 
640  {
641  int cache = GET_CACHE(re, &s->gb);
642  int sign = (~cache) >> 31;
643  level = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
644  }
645 
646  LAST_SKIP_BITS(re, &s->gb, code);
647 
648  if (i > 63) {
649  av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
650  return AVERROR_INVALIDDATA;
651  }
652  j = s->scantable.permutated[i];
653  block[j] = level * quant_matrix[j];
654  }
655  } while (i < 63);
656  CLOSE_READER(re, &s->gb);}
657 
658  return 0;
659 }
660 
662  int component, int dc_index,
663  int16_t *quant_matrix, int Al)
664 {
665  int val;
666  s->bdsp.clear_block(block);
667  val = mjpeg_decode_dc(s, dc_index);
668  if (val == 0xfffff) {
669  av_log(s->avctx, AV_LOG_ERROR, "error dc\n");
670  return AVERROR_INVALIDDATA;
671  }
672  val = (val * quant_matrix[0] << Al) + s->last_dc[component];
673  s->last_dc[component] = val;
674  block[0] = val;
675  return 0;
676 }
677 
678 /* decode block and dequantize - progressive JPEG version */
680  uint8_t *last_nnz, int ac_index,
681  int16_t *quant_matrix,
682  int ss, int se, int Al, int *EOBRUN)
683 {
684  int code, i, j, level, val, run;
685 
686  if (*EOBRUN) {
687  (*EOBRUN)--;
688  return 0;
689  }
690 
691  {
692  OPEN_READER(re, &s->gb);
693  for (i = ss; ; i++) {
694  UPDATE_CACHE(re, &s->gb);
695  GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
696 
697  run = ((unsigned) code) >> 4;
698  code &= 0xF;
699  if (code) {
700  i += run;
701  if (code > MIN_CACHE_BITS - 16)
702  UPDATE_CACHE(re, &s->gb);
703 
704  {
705  int cache = GET_CACHE(re, &s->gb);
706  int sign = (~cache) >> 31;
707  level = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;
708  }
709 
710  LAST_SKIP_BITS(re, &s->gb, code);
711 
712  if (i >= se) {
713  if (i == se) {
714  j = s->scantable.permutated[se];
715  block[j] = level * quant_matrix[j] << Al;
716  break;
717  }
718  av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);
719  return AVERROR_INVALIDDATA;
720  }
721  j = s->scantable.permutated[i];
722  block[j] = level * quant_matrix[j] << Al;
723  } else {
724  if (run == 0xF) {// ZRL - skip 15 coefficients
725  i += 15;
726  if (i >= se) {
727  av_log(s->avctx, AV_LOG_ERROR, "ZRL overflow: %d\n", i);
728  return AVERROR_INVALIDDATA;
729  }
730  } else {
731  val = (1 << run);
732  if (run) {
733  UPDATE_CACHE(re, &s->gb);
734  val += NEG_USR32(GET_CACHE(re, &s->gb), run);
735  LAST_SKIP_BITS(re, &s->gb, run);
736  }
737  *EOBRUN = val - 1;
738  break;
739  }
740  }
741  }
742  CLOSE_READER(re, &s->gb);
743  }
744 
745  if (i > *last_nnz)
746  *last_nnz = i;
747 
748  return 0;
749 }
750 
751 #define REFINE_BIT(j) { \
752  UPDATE_CACHE(re, &s->gb); \
753  sign = block[j] >> 15; \
754  block[j] += SHOW_UBITS(re, &s->gb, 1) * \
755  ((quant_matrix[j] ^ sign) - sign) << Al; \
756  LAST_SKIP_BITS(re, &s->gb, 1); \
757 }
758 
759 #define ZERO_RUN \
760 for (; ; i++) { \
761  if (i > last) { \
762  i += run; \
763  if (i > se) { \
764  av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i); \
765  return -1; \
766  } \
767  break; \
768  } \
769  j = s->scantable.permutated[i]; \
770  if (block[j]) \
771  REFINE_BIT(j) \
772  else if (run-- == 0) \
773  break; \
774 }
775 
776 /* decode block and dequantize - progressive JPEG refinement pass */
778  uint8_t *last_nnz,
779  int ac_index, int16_t *quant_matrix,
780  int ss, int se, int Al, int *EOBRUN)
781 {
782  int code, i = ss, j, sign, val, run;
783  int last = FFMIN(se, *last_nnz);
784 
785  OPEN_READER(re, &s->gb);
786  if (*EOBRUN) {
787  (*EOBRUN)--;
788  } else {
789  for (; ; i++) {
790  UPDATE_CACHE(re, &s->gb);
791  GET_VLC(code, re, &s->gb, s->vlcs[2][ac_index].table, 9, 2);
792 
793  if (code & 0xF) {
794  run = ((unsigned) code) >> 4;
795  UPDATE_CACHE(re, &s->gb);
796  val = SHOW_UBITS(re, &s->gb, 1);
797  LAST_SKIP_BITS(re, &s->gb, 1);
798  ZERO_RUN;
799  j = s->scantable.permutated[i];
800  val--;
801  block[j] = ((quant_matrix[j]^val) - val) << Al;
802  if (i == se) {
803  if (i > *last_nnz)
804  *last_nnz = i;
805  CLOSE_READER(re, &s->gb);
806  return 0;
807  }
808  } else {
809  run = ((unsigned) code) >> 4;
810  if (run == 0xF) {
811  ZERO_RUN;
812  } else {
813  val = run;
814  run = (1 << run);
815  if (val) {
816  UPDATE_CACHE(re, &s->gb);
817  run += SHOW_UBITS(re, &s->gb, val);
818  LAST_SKIP_BITS(re, &s->gb, val);
819  }
820  *EOBRUN = run - 1;
821  break;
822  }
823  }
824  }
825 
826  if (i > *last_nnz)
827  *last_nnz = i;
828  }
829 
830  for (; i <= last; i++) {
831  j = s->scantable.permutated[i];
832  if (block[j])
833  REFINE_BIT(j)
834  }
835  CLOSE_READER(re, &s->gb);
836 
837  return 0;
838 }
839 #undef REFINE_BIT
840 #undef ZERO_RUN
841 
842 static int handle_rstn(MJpegDecodeContext *s, int nb_components)
843 {
844  int i;
845  int reset = 0;
846 
847  if (s->restart_interval) {
848  s->restart_count--;
849  if(s->restart_count == 0 && s->avctx->codec_id == AV_CODEC_ID_THP){
850  align_get_bits(&s->gb);
851  for (i = 0; i < nb_components; i++) /* reset dc */
852  s->last_dc[i] = (4 << s->bits);
853  }
854 
855  i = 8 + ((-get_bits_count(&s->gb)) & 7);
856  /* skip RSTn */
857  if (s->restart_count == 0) {
858  if( show_bits(&s->gb, i) == (1 << i) - 1
859  || show_bits(&s->gb, i) == 0xFF) {
860  int pos = get_bits_count(&s->gb);
861  align_get_bits(&s->gb);
862  while (get_bits_left(&s->gb) >= 8 && show_bits(&s->gb, 8) == 0xFF)
863  skip_bits(&s->gb, 8);
864  if (get_bits_left(&s->gb) >= 8 && (get_bits(&s->gb, 8) & 0xF8) == 0xD0) {
865  for (i = 0; i < nb_components; i++) /* reset dc */
866  s->last_dc[i] = (4 << s->bits);
867  reset = 1;
868  } else
869  skip_bits_long(&s->gb, pos - get_bits_count(&s->gb));
870  }
871  }
872  }
873  return reset;
874 }
875 
876 static int ljpeg_decode_rgb_scan(MJpegDecodeContext *s, int nb_components, int predictor, int point_transform)
877 {
878  int i, mb_x, mb_y;
879  uint16_t (*buffer)[4];
880  int left[4], top[4], topleft[4];
881  const int linesize = s->linesize[0];
882  const int mask = ((1 << s->bits) - 1) << point_transform;
883  int resync_mb_y = 0;
884  int resync_mb_x = 0;
885 
886  if (s->nb_components != 3 && s->nb_components != 4)
887  return AVERROR_INVALIDDATA;
888  if (s->v_max != 1 || s->h_max != 1 || !s->lossless)
889  return AVERROR_INVALIDDATA;
890 
891 
893 
895  (unsigned)s->mb_width * 4 * sizeof(s->ljpeg_buffer[0][0]));
896  buffer = s->ljpeg_buffer;
897 
898  for (i = 0; i < 4; i++)
899  buffer[0][i] = 1 << (s->bits - 1);
900 
901  for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
902  uint8_t *ptr = s->picture_ptr->data[0] + (linesize * mb_y);
903 
904  if (s->interlaced && s->bottom_field)
905  ptr += linesize >> 1;
906 
907  for (i = 0; i < 4; i++)
908  top[i] = left[i] = topleft[i] = buffer[0][i];
909 
910  for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
911  int modified_predictor = predictor;
912 
913  if (s->restart_interval && !s->restart_count){
915  resync_mb_x = mb_x;
916  resync_mb_y = mb_y;
917  for(i=0; i<4; i++)
918  top[i] = left[i]= topleft[i]= 1 << (s->bits - 1);
919  }
920  if (mb_y == resync_mb_y || mb_y == resync_mb_y+1 && mb_x < resync_mb_x || !mb_x)
921  modified_predictor = 1;
922 
923  for (i=0;i<nb_components;i++) {
924  int pred, dc;
925 
926  topleft[i] = top[i];
927  top[i] = buffer[mb_x][i];
928 
929  PREDICT(pred, topleft[i], top[i], left[i], modified_predictor);
930 
931  dc = mjpeg_decode_dc(s, s->dc_index[i]);
932  if(dc == 0xFFFFF)
933  return -1;
934 
935  left[i] = buffer[mb_x][i] =
936  mask & (pred + (dc << point_transform));
937  }
938 
939  if (s->restart_interval && !--s->restart_count) {
940  align_get_bits(&s->gb);
941  skip_bits(&s->gb, 16); /* skip RSTn */
942  }
943  }
944  if (s->nb_components == 4) {
945  for(i=0; i<nb_components; i++) {
946  int c= s->comp_index[i];
947  if (s->bits <= 8) {
948  for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
949  ptr[4*mb_x+3-c] = buffer[mb_x][i];
950  }
951  } else if(s->bits == 9) {
952  return AVERROR_PATCHWELCOME;
953  } else {
954  for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
955  ((uint16_t*)ptr)[4*mb_x+c] = buffer[mb_x][i];
956  }
957  }
958  }
959  } else if (s->rct) {
960  for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
961  ptr[3*mb_x + 1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2] - 0x200) >> 2);
962  ptr[3*mb_x + 0] = buffer[mb_x][1] + ptr[3*mb_x + 1];
963  ptr[3*mb_x + 2] = buffer[mb_x][2] + ptr[3*mb_x + 1];
964  }
965  } else if (s->pegasus_rct) {
966  for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
967  ptr[3*mb_x + 1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2]) >> 2);
968  ptr[3*mb_x + 0] = buffer[mb_x][1] + ptr[3*mb_x + 1];
969  ptr[3*mb_x + 2] = buffer[mb_x][2] + ptr[3*mb_x + 1];
970  }
971  } else {
972  for(i=0; i<nb_components; i++) {
973  int c= s->comp_index[i];
974  if (s->bits <= 8) {
975  for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
976  ptr[3*mb_x+2-c] = buffer[mb_x][i];
977  }
978  } else if(s->bits == 9) {
979  return AVERROR_PATCHWELCOME;
980  } else {
981  for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
982  ((uint16_t*)ptr)[3*mb_x+2-c] = buffer[mb_x][i];
983  }
984  }
985  }
986  }
987  }
988  return 0;
989 }
990 
992  int point_transform, int nb_components)
993 {
994  int i, mb_x, mb_y, mask;
995  int bits= (s->bits+7)&~7;
996  int resync_mb_y = 0;
997  int resync_mb_x = 0;
998 
999  point_transform += bits - s->bits;
1000  mask = ((1 << s->bits) - 1) << point_transform;
1001 
1002  av_assert0(nb_components>=1 && nb_components<=4);
1003 
1004  for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
1005  for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
1006  if (s->restart_interval && !s->restart_count){
1008  resync_mb_x = mb_x;
1009  resync_mb_y = mb_y;
1010  }
1011 
1012  if(!mb_x || mb_y == resync_mb_y || mb_y == resync_mb_y+1 && mb_x < resync_mb_x || s->interlaced){
1013  int toprow = mb_y == resync_mb_y || mb_y == resync_mb_y+1 && mb_x < resync_mb_x;
1014  int leftcol = !mb_x || mb_y == resync_mb_y && mb_x == resync_mb_x;
1015  for (i = 0; i < nb_components; i++) {
1016  uint8_t *ptr;
1017  uint16_t *ptr16;
1018  int n, h, v, x, y, c, j, linesize;
1019  n = s->nb_blocks[i];
1020  c = s->comp_index[i];
1021  h = s->h_scount[i];
1022  v = s->v_scount[i];
1023  x = 0;
1024  y = 0;
1025  linesize= s->linesize[c];
1026 
1027  if(bits>8) linesize /= 2;
1028 
1029  for(j=0; j<n; j++) {
1030  int pred, dc;
1031 
1032  dc = mjpeg_decode_dc(s, s->dc_index[i]);
1033  if(dc == 0xFFFFF)
1034  return -1;
1035  if(bits<=8){
1036  ptr = s->picture_ptr->data[c] + (linesize * (v * mb_y + y)) + (h * mb_x + x); //FIXME optimize this crap
1037  if(y==0 && toprow){
1038  if(x==0 && leftcol){
1039  pred= 1 << (bits - 1);
1040  }else{
1041  pred= ptr[-1];
1042  }
1043  }else{
1044  if(x==0 && leftcol){
1045  pred= ptr[-linesize];
1046  }else{
1047  PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);
1048  }
1049  }
1050 
1051  if (s->interlaced && s->bottom_field)
1052  ptr += linesize >> 1;
1053  pred &= mask;
1054  *ptr= pred + (dc << point_transform);
1055  }else{
1056  ptr16 = (uint16_t*)(s->picture_ptr->data[c] + 2*(linesize * (v * mb_y + y)) + 2*(h * mb_x + x)); //FIXME optimize this crap
1057  if(y==0 && toprow){
1058  if(x==0 && leftcol){
1059  pred= 1 << (bits - 1);
1060  }else{
1061  pred= ptr16[-1];
1062  }
1063  }else{
1064  if(x==0 && leftcol){
1065  pred= ptr16[-linesize];
1066  }else{
1067  PREDICT(pred, ptr16[-linesize-1], ptr16[-linesize], ptr16[-1], predictor);
1068  }
1069  }
1070 
1071  if (s->interlaced && s->bottom_field)
1072  ptr16 += linesize >> 1;
1073  pred &= mask;
1074  *ptr16= pred + (dc << point_transform);
1075  }
1076  if (++x == h) {
1077  x = 0;
1078  y++;
1079  }
1080  }
1081  }
1082  } else {
1083  for (i = 0; i < nb_components; i++) {
1084  uint8_t *ptr;
1085  uint16_t *ptr16;
1086  int n, h, v, x, y, c, j, linesize, dc;
1087  n = s->nb_blocks[i];
1088  c = s->comp_index[i];
1089  h = s->h_scount[i];
1090  v = s->v_scount[i];
1091  x = 0;
1092  y = 0;
1093  linesize = s->linesize[c];
1094 
1095  if(bits>8) linesize /= 2;
1096 
1097  for (j = 0; j < n; j++) {
1098  int pred;
1099 
1100  dc = mjpeg_decode_dc(s, s->dc_index[i]);
1101  if(dc == 0xFFFFF)
1102  return -1;
1103  if(bits<=8){
1104  ptr = s->picture_ptr->data[c] +
1105  (linesize * (v * mb_y + y)) +
1106  (h * mb_x + x); //FIXME optimize this crap
1107  PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);
1108 
1109  pred &= mask;
1110  *ptr = pred + (dc << point_transform);
1111  }else{
1112  ptr16 = (uint16_t*)(s->picture_ptr->data[c] + 2*(linesize * (v * mb_y + y)) + 2*(h * mb_x + x)); //FIXME optimize this crap
1113  PREDICT(pred, ptr16[-linesize-1], ptr16[-linesize], ptr16[-1], predictor);
1114 
1115  pred &= mask;
1116  *ptr16= pred + (dc << point_transform);
1117  }
1118 
1119  if (++x == h) {
1120  x = 0;
1121  y++;
1122  }
1123  }
1124  }
1125  }
1126  if (s->restart_interval && !--s->restart_count) {
1127  align_get_bits(&s->gb);
1128  skip_bits(&s->gb, 16); /* skip RSTn */
1129  }
1130  }
1131  }
1132  return 0;
1133 }
1134 
1136  uint8_t *dst, const uint8_t *src,
1137  int linesize, int lowres)
1138 {
1139  switch (lowres) {
1140  case 0: s->hdsp.put_pixels_tab[1][0](dst, src, linesize, 8);
1141  break;
1142  case 1: copy_block4(dst, src, linesize, linesize, 4);
1143  break;
1144  case 2: copy_block2(dst, src, linesize, linesize, 2);
1145  break;
1146  case 3: *dst = *src;
1147  break;
1148  }
1149 }
1150 
1151 static void shift_output(MJpegDecodeContext *s, uint8_t *ptr, int linesize)
1152 {
1153  int block_x, block_y;
1154  int size = 8 >> s->avctx->lowres;
1155  if (s->bits > 8) {
1156  for (block_y=0; block_y<size; block_y++)
1157  for (block_x=0; block_x<size; block_x++)
1158  *(uint16_t*)(ptr + 2*block_x + block_y*linesize) <<= 16 - s->bits;
1159  } else {
1160  for (block_y=0; block_y<size; block_y++)
1161  for (block_x=0; block_x<size; block_x++)
1162  *(ptr + block_x + block_y*linesize) <<= 8 - s->bits;
1163  }
1164 }
1165 
1166 static int mjpeg_decode_scan(MJpegDecodeContext *s, int nb_components, int Ah,
1167  int Al, const uint8_t *mb_bitmask,
1168  int mb_bitmask_size,
1169  const AVFrame *reference)
1170 {
1171  int i, mb_x, mb_y;
1173  const uint8_t *reference_data[MAX_COMPONENTS];
1174  int linesize[MAX_COMPONENTS];
1175  GetBitContext mb_bitmask_gb = {0}; // initialize to silence gcc warning
1176  int bytes_per_pixel = 1 + (s->bits > 8);
1177 
1178  if (mb_bitmask) {
1179  if (mb_bitmask_size != (s->mb_width * s->mb_height + 7)>>3) {
1180  av_log(s->avctx, AV_LOG_ERROR, "mb_bitmask_size mismatches\n");
1181  return AVERROR_INVALIDDATA;
1182  }
1183  init_get_bits(&mb_bitmask_gb, mb_bitmask, s->mb_width * s->mb_height);
1184  }
1185 
1186  s->restart_count = 0;
1187 
1188  for (i = 0; i < nb_components; i++) {
1189  int c = s->comp_index[i];
1190  data[c] = s->picture_ptr->data[c];
1191  reference_data[c] = reference ? reference->data[c] : NULL;
1192  linesize[c] = s->linesize[c];
1193  s->coefs_finished[c] |= 1;
1194  }
1195 
1196  for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
1197  for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
1198  const int copy_mb = mb_bitmask && !get_bits1(&mb_bitmask_gb);
1199 
1200  if (s->restart_interval && !s->restart_count)
1202 
1203  if (get_bits_left(&s->gb) < 0) {
1204  av_log(s->avctx, AV_LOG_ERROR, "overread %d\n",
1205  -get_bits_left(&s->gb));
1206  return AVERROR_INVALIDDATA;
1207  }
1208  for (i = 0; i < nb_components; i++) {
1209  uint8_t *ptr;
1210  int n, h, v, x, y, c, j;
1211  int block_offset;
1212  n = s->nb_blocks[i];
1213  c = s->comp_index[i];
1214  h = s->h_scount[i];
1215  v = s->v_scount[i];
1216  x = 0;
1217  y = 0;
1218  for (j = 0; j < n; j++) {
1219  block_offset = (((linesize[c] * (v * mb_y + y) * 8) +
1220  (h * mb_x + x) * 8 * bytes_per_pixel) >> s->avctx->lowres);
1221 
1222  if (s->interlaced && s->bottom_field)
1223  block_offset += linesize[c] >> 1;
1224  ptr = data[c] + block_offset;
1225  if (!s->progressive) {
1226  if (copy_mb)
1227  mjpeg_copy_block(s, ptr, reference_data[c] + block_offset,
1228  linesize[c], s->avctx->lowres);
1229 
1230  else {
1231  s->bdsp.clear_block(s->block);
1232  if (decode_block(s, s->block, i,
1233  s->dc_index[i], s->ac_index[i],
1234  s->quant_matrixes[s->quant_sindex[i]]) < 0) {
1236  "error y=%d x=%d\n", mb_y, mb_x);
1237  return AVERROR_INVALIDDATA;
1238  }
1239  s->idsp.idct_put(ptr, linesize[c], s->block);
1240  if (s->bits & 7)
1241  shift_output(s, ptr, linesize[c]);
1242  }
1243  } else {
1244  int block_idx = s->block_stride[c] * (v * mb_y + y) +
1245  (h * mb_x + x);
1246  int16_t *block = s->blocks[c][block_idx];
1247  if (Ah)
1248  block[0] += get_bits1(&s->gb) *
1249  s->quant_matrixes[s->quant_sindex[i]][0] << Al;
1250  else if (decode_dc_progressive(s, block, i, s->dc_index[i],
1251  s->quant_matrixes[s->quant_sindex[i]],
1252  Al) < 0) {
1254  "error y=%d x=%d\n", mb_y, mb_x);
1255  return AVERROR_INVALIDDATA;
1256  }
1257  }
1258  av_dlog(s->avctx, "mb: %d %d processed\n", mb_y, mb_x);
1259  av_dlog(s->avctx, "%d %d %d %d %d %d %d %d \n",
1260  mb_x, mb_y, x, y, c, s->bottom_field,
1261  (v * mb_y + y) * 8, (h * mb_x + x) * 8);
1262  if (++x == h) {
1263  x = 0;
1264  y++;
1265  }
1266  }
1267  }
1268 
1269  handle_rstn(s, nb_components);
1270  }
1271  }
1272  return 0;
1273 }
1274 
1276  int se, int Ah, int Al)
1277 {
1278  int mb_x, mb_y;
1279  int EOBRUN = 0;
1280  int c = s->comp_index[0];
1281  uint8_t *data = s->picture_ptr->data[c];
1282  int linesize = s->linesize[c];
1283  int last_scan = 0;
1284  int16_t *quant_matrix = s->quant_matrixes[s->quant_sindex[0]];
1285  int bytes_per_pixel = 1 + (s->bits > 8);
1286 
1287  av_assert0(ss>=0 && Ah>=0 && Al>=0);
1288  if (se < ss || se > 63) {
1289  av_log(s->avctx, AV_LOG_ERROR, "SS/SE %d/%d is invalid\n", ss, se);
1290  return AVERROR_INVALIDDATA;
1291  }
1292 
1293  if (!Al) {
1294  s->coefs_finished[c] |= (2ULL << se) - (1ULL << ss);
1295  last_scan = !~s->coefs_finished[c];
1296  }
1297 
1298  if (s->interlaced && s->bottom_field)
1299  data += linesize >> 1;
1300 
1301  s->restart_count = 0;
1302 
1303  for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
1304  uint8_t *ptr = data + (mb_y * linesize * 8 >> s->avctx->lowres);
1305  int block_idx = mb_y * s->block_stride[c];
1306  int16_t (*block)[64] = &s->blocks[c][block_idx];
1307  uint8_t *last_nnz = &s->last_nnz[c][block_idx];
1308  for (mb_x = 0; mb_x < s->mb_width; mb_x++, block++, last_nnz++) {
1309  int ret;
1310  if (s->restart_interval && !s->restart_count)
1312 
1313  if (Ah)
1314  ret = decode_block_refinement(s, *block, last_nnz, s->ac_index[0],
1315  quant_matrix, ss, se, Al, &EOBRUN);
1316  else
1317  ret = decode_block_progressive(s, *block, last_nnz, s->ac_index[0],
1318  quant_matrix, ss, se, Al, &EOBRUN);
1319  if (ret < 0) {
1321  "error y=%d x=%d\n", mb_y, mb_x);
1322  return AVERROR_INVALIDDATA;
1323  }
1324 
1325  if (last_scan) {
1326  s->idsp.idct_put(ptr, linesize, *block);
1327  if (s->bits & 7)
1328  shift_output(s, ptr, linesize);
1329  ptr += bytes_per_pixel*8 >> s->avctx->lowres;
1330  }
1331  if (handle_rstn(s, 0))
1332  EOBRUN = 0;
1333  }
1334  }
1335  return 0;
1336 }
1337 
1339  int mb_bitmask_size, const AVFrame *reference)
1340 {
1341  int len, nb_components, i, h, v, predictor, point_transform;
1342  int index, id, ret;
1343  const int block_size = s->lossless ? 1 : 8;
1344  int ilv, prev_shift;
1345 
1346  if (!s->got_picture) {
1348  "Can not process SOS before SOF, skipping\n");
1349  return -1;
1350  }
1351 
1352  av_assert0(s->picture_ptr->data[0]);
1353  /* XXX: verify len field validity */
1354  len = get_bits(&s->gb, 16);
1355  nb_components = get_bits(&s->gb, 8);
1356  if (nb_components == 0 || nb_components > MAX_COMPONENTS) {
1358  "decode_sos: nb_components (%d) unsupported\n", nb_components);
1359  return AVERROR_PATCHWELCOME;
1360  }
1361  if (len != 6 + 2 * nb_components) {
1362  av_log(s->avctx, AV_LOG_ERROR, "decode_sos: invalid len (%d)\n", len);
1363  return AVERROR_INVALIDDATA;
1364  }
1365  for (i = 0; i < nb_components; i++) {
1366  id = get_bits(&s->gb, 8) - 1;
1367  av_log(s->avctx, AV_LOG_DEBUG, "component: %d\n", id);
1368  /* find component index */
1369  for (index = 0; index < s->nb_components; index++)
1370  if (id == s->component_id[index])
1371  break;
1372  if (index == s->nb_components) {
1374  "decode_sos: index(%d) out of components\n", index);
1375  return AVERROR_INVALIDDATA;
1376  }
1377  /* Metasoft MJPEG codec has Cb and Cr swapped */
1378  if (s->avctx->codec_tag == MKTAG('M', 'T', 'S', 'J')
1379  && nb_components == 3 && s->nb_components == 3 && i)
1380  index = 3 - i;
1381 
1382  s->quant_sindex[i] = s->quant_index[index];
1383  s->nb_blocks[i] = s->h_count[index] * s->v_count[index];
1384  s->h_scount[i] = s->h_count[index];
1385  s->v_scount[i] = s->v_count[index];
1386 
1387  if(nb_components == 3 && s->nb_components == 3 && s->avctx->pix_fmt == AV_PIX_FMT_GBR24P)
1388  index = (i+2)%3;
1389  if(nb_components == 1 && s->nb_components == 3 && s->avctx->pix_fmt == AV_PIX_FMT_GBR24P)
1390  index = (index+2)%3;
1391 
1392  s->comp_index[i] = index;
1393 
1394  s->dc_index[i] = get_bits(&s->gb, 4);
1395  s->ac_index[i] = get_bits(&s->gb, 4);
1396 
1397  if (s->dc_index[i] < 0 || s->ac_index[i] < 0 ||
1398  s->dc_index[i] >= 4 || s->ac_index[i] >= 4)
1399  goto out_of_range;
1400  if (!s->vlcs[0][s->dc_index[i]].table || !(s->progressive ? s->vlcs[2][s->ac_index[0]].table : s->vlcs[1][s->ac_index[i]].table))
1401  goto out_of_range;
1402  }
1403 
1404  predictor = get_bits(&s->gb, 8); /* JPEG Ss / lossless JPEG predictor /JPEG-LS NEAR */
1405  ilv = get_bits(&s->gb, 8); /* JPEG Se / JPEG-LS ILV */
1406  if(s->avctx->codec_tag != AV_RL32("CJPG")){
1407  prev_shift = get_bits(&s->gb, 4); /* Ah */
1408  point_transform = get_bits(&s->gb, 4); /* Al */
1409  }else
1410  prev_shift = point_transform = 0;
1411 
1412  if (nb_components > 1) {
1413  /* interleaved stream */
1414  s->mb_width = (s->width + s->h_max * block_size - 1) / (s->h_max * block_size);
1415  s->mb_height = (s->height + s->v_max * block_size - 1) / (s->v_max * block_size);
1416  } else if (!s->ls) { /* skip this for JPEG-LS */
1417  h = s->h_max / s->h_scount[0];
1418  v = s->v_max / s->v_scount[0];
1419  s->mb_width = (s->width + h * block_size - 1) / (h * block_size);
1420  s->mb_height = (s->height + v * block_size - 1) / (v * block_size);
1421  s->nb_blocks[0] = 1;
1422  s->h_scount[0] = 1;
1423  s->v_scount[0] = 1;
1424  }
1425 
1426  if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1427  av_log(s->avctx, AV_LOG_DEBUG, "%s %s p:%d >>:%d ilv:%d bits:%d skip:%d %s comp:%d\n",
1428  s->lossless ? "lossless" : "sequential DCT", s->rgb ? "RGB" : "",
1429  predictor, point_transform, ilv, s->bits, s->mjpb_skiptosod,
1430  s->pegasus_rct ? "PRCT" : (s->rct ? "RCT" : ""), nb_components);
1431 
1432 
1433  /* mjpeg-b can have padding bytes between sos and image data, skip them */
1434  for (i = s->mjpb_skiptosod; i > 0; i--)
1435  skip_bits(&s->gb, 8);
1436 
1437 next_field:
1438  for (i = 0; i < nb_components; i++)
1439  s->last_dc[i] = (4 << s->bits);
1440 
1441  if (s->lossless) {
1442  av_assert0(s->picture_ptr == s->picture);
1443  if (CONFIG_JPEGLS_DECODER && s->ls) {
1444 // for () {
1445 // reset_ls_coding_parameters(s, 0);
1446 
1447  if ((ret = ff_jpegls_decode_picture(s, predictor,
1448  point_transform, ilv)) < 0)
1449  return ret;
1450  } else {
1451  if (s->rgb) {
1452  if ((ret = ljpeg_decode_rgb_scan(s, nb_components, predictor, point_transform)) < 0)
1453  return ret;
1454  } else {
1455  if ((ret = ljpeg_decode_yuv_scan(s, predictor,
1456  point_transform,
1457  nb_components)) < 0)
1458  return ret;
1459  }
1460  }
1461  } else {
1462  if (s->progressive && predictor) {
1463  av_assert0(s->picture_ptr == s->picture);
1464  if ((ret = mjpeg_decode_scan_progressive_ac(s, predictor,
1465  ilv, prev_shift,
1466  point_transform)) < 0)
1467  return ret;
1468  } else {
1469  if ((ret = mjpeg_decode_scan(s, nb_components,
1470  prev_shift, point_transform,
1471  mb_bitmask, mb_bitmask_size, reference)) < 0)
1472  return ret;
1473  }
1474  }
1475 
1476  if (s->interlaced &&
1477  get_bits_left(&s->gb) > 32 &&
1478  show_bits(&s->gb, 8) == 0xFF) {
1479  GetBitContext bak = s->gb;
1480  align_get_bits(&bak);
1481  if (show_bits(&bak, 16) == 0xFFD1) {
1482  av_log(s->avctx, AV_LOG_DEBUG, "AVRn interlaced picture marker found\n");
1483  s->gb = bak;
1484  skip_bits(&s->gb, 16);
1485  s->bottom_field ^= 1;
1486 
1487  goto next_field;
1488  }
1489  }
1490 
1491  emms_c();
1492  return 0;
1493  out_of_range:
1494  av_log(s->avctx, AV_LOG_ERROR, "decode_sos: ac/dc index out of range\n");
1495  return AVERROR_INVALIDDATA;
1496 }
1497 
1499 {
1500  if (get_bits(&s->gb, 16) != 4)
1501  return AVERROR_INVALIDDATA;
1502  s->restart_interval = get_bits(&s->gb, 16);
1503  s->restart_count = 0;
1504  av_log(s->avctx, AV_LOG_DEBUG, "restart interval: %d\n",
1505  s->restart_interval);
1506 
1507  return 0;
1508 }
1509 
1511 {
1512  int len, id, i;
1513 
1514  len = get_bits(&s->gb, 16);
1515  if (len < 6)
1516  return AVERROR_INVALIDDATA;
1517  if (8 * len > get_bits_left(&s->gb))
1518  return AVERROR_INVALIDDATA;
1519 
1520  id = get_bits_long(&s->gb, 32);
1521  len -= 6;
1522 
1523  if (s->avctx->debug & FF_DEBUG_STARTCODE) {
1524  char id_str[32];
1525  av_get_codec_tag_string(id_str, sizeof(id_str), av_bswap32(id));
1526  av_log(s->avctx, AV_LOG_DEBUG, "APPx (%s / %8X) len=%d\n", id_str, id, len);
1527  }
1528 
1529  /* Buggy AVID, it puts EOI only at every 10th frame. */
1530  /* Also, this fourcc is used by non-avid files too, it holds some
1531  information, but it's always present in AVID-created files. */
1532  if (id == AV_RB32("AVI1")) {
1533  /* structure:
1534  4bytes AVI1
1535  1bytes polarity
1536  1bytes always zero
1537  4bytes field_size
1538  4bytes field_size_less_padding
1539  */
1540  s->buggy_avid = 1;
1541  i = get_bits(&s->gb, 8); len--;
1542  av_log(s->avctx, AV_LOG_DEBUG, "polarity %d\n", i);
1543 #if 0
1544  skip_bits(&s->gb, 8);
1545  skip_bits(&s->gb, 32);
1546  skip_bits(&s->gb, 32);
1547  len -= 10;
1548 #endif
1549  goto out;
1550  }
1551 
1552 // len -= 2;
1553 
1554  if (id == AV_RB32("JFIF")) {
1555  int t_w, t_h, v1, v2;
1556  skip_bits(&s->gb, 8); /* the trailing zero-byte */
1557  v1 = get_bits(&s->gb, 8);
1558  v2 = get_bits(&s->gb, 8);
1559  skip_bits(&s->gb, 8);
1560 
1561  s->avctx->sample_aspect_ratio.num = get_bits(&s->gb, 16);
1562  s->avctx->sample_aspect_ratio.den = get_bits(&s->gb, 16);
1564 
1565  if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1566  av_log(s->avctx, AV_LOG_INFO,
1567  "mjpeg: JFIF header found (version: %x.%x) SAR=%d/%d\n",
1568  v1, v2,
1571 
1572  t_w = get_bits(&s->gb, 8);
1573  t_h = get_bits(&s->gb, 8);
1574  if (t_w && t_h) {
1575  /* skip thumbnail */
1576  if (len -10 - (t_w * t_h * 3) > 0)
1577  len -= t_w * t_h * 3;
1578  }
1579  len -= 10;
1580  goto out;
1581  }
1582 
1583  if (id == AV_RB32("Adob") && (get_bits(&s->gb, 8) == 'e')) {
1584  skip_bits(&s->gb, 16); /* version */
1585  skip_bits(&s->gb, 16); /* flags0 */
1586  skip_bits(&s->gb, 16); /* flags1 */
1587  s->adobe_transform = get_bits(&s->gb, 8);
1588  if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1589  av_log(s->avctx, AV_LOG_INFO, "mjpeg: Adobe header found, transform=%d\n", s->adobe_transform);
1590  len -= 7;
1591  goto out;
1592  }
1593 
1594  if (id == AV_RB32("LJIF")) {
1595  if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1596  av_log(s->avctx, AV_LOG_INFO,
1597  "Pegasus lossless jpeg header found\n");
1598  skip_bits(&s->gb, 16); /* version ? */
1599  skip_bits(&s->gb, 16); /* unknown always 0? */
1600  skip_bits(&s->gb, 16); /* unknown always 0? */
1601  skip_bits(&s->gb, 16); /* unknown always 0? */
1602  switch (i=get_bits(&s->gb, 8)) {
1603  case 1:
1604  s->rgb = 1;
1605  s->pegasus_rct = 0;
1606  break;
1607  case 2:
1608  s->rgb = 1;
1609  s->pegasus_rct = 1;
1610  break;
1611  default:
1612  av_log(s->avctx, AV_LOG_ERROR, "unknown colorspace %d\n", i);
1613  }
1614  len -= 9;
1615  goto out;
1616  }
1617  if (id == AV_RL32("colr") && len > 0) {
1618  s->colr = get_bits(&s->gb, 8);
1619  if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1620  av_log(s->avctx, AV_LOG_INFO, "COLR %d\n", s->colr);
1621  len --;
1622  goto out;
1623  }
1624  if (id == AV_RL32("xfrm") && len > 0) {
1625  s->xfrm = get_bits(&s->gb, 8);
1626  if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1627  av_log(s->avctx, AV_LOG_INFO, "XFRM %d\n", s->xfrm);
1628  len --;
1629  goto out;
1630  }
1631 
1632  /* JPS extension by VRex */
1633  if (s->start_code == APP3 && id == AV_RB32("_JPS") && len >= 10) {
1634  int flags, layout, type;
1635  if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1636  av_log(s->avctx, AV_LOG_INFO, "_JPSJPS_\n");
1637 
1638  skip_bits(&s->gb, 32); len -= 4; /* JPS_ */
1639  skip_bits(&s->gb, 16); len -= 2; /* block length */
1640  skip_bits(&s->gb, 8); /* reserved */
1641  flags = get_bits(&s->gb, 8);
1642  layout = get_bits(&s->gb, 8);
1643  type = get_bits(&s->gb, 8);
1644  len -= 4;
1645 
1646  s->stereo3d = av_stereo3d_alloc();
1647  if (!s->stereo3d) {
1648  goto out;
1649  }
1650  if (type == 0) {
1652  } else if (type == 1) {
1653  switch (layout) {
1654  case 0x01:
1656  break;
1657  case 0x02:
1659  break;
1660  case 0x03:
1662  break;
1663  }
1664  if (!(flags & 0x04)) {
1666  }
1667  }
1668  goto out;
1669  }
1670 
1671  /* EXIF metadata */
1672  if (s->start_code == APP1 && id == AV_RB32("Exif") && len >= 2) {
1673  GetByteContext gbytes;
1674  int ret, le, ifd_offset, bytes_read;
1675  const uint8_t *aligned;
1676 
1677  skip_bits(&s->gb, 16); // skip padding
1678  len -= 2;
1679 
1680  // init byte wise reading
1681  aligned = align_get_bits(&s->gb);
1682  bytestream2_init(&gbytes, aligned, len);
1683 
1684  // read TIFF header
1685  ret = ff_tdecode_header(&gbytes, &le, &ifd_offset);
1686  if (ret) {
1687  av_log(s->avctx, AV_LOG_ERROR, "mjpeg: invalid TIFF header in EXIF data\n");
1688  } else {
1689  bytestream2_seek(&gbytes, ifd_offset, SEEK_SET);
1690 
1691  // read 0th IFD and store the metadata
1692  // (return values > 0 indicate the presence of subimage metadata)
1693  ret = avpriv_exif_decode_ifd(s->avctx, &gbytes, le, 0, &s->exif_metadata);
1694  if (ret < 0) {
1695  av_log(s->avctx, AV_LOG_ERROR, "mjpeg: error decoding EXIF data\n");
1696  }
1697  }
1698 
1699  bytes_read = bytestream2_tell(&gbytes);
1700  skip_bits(&s->gb, bytes_read << 3);
1701  len -= bytes_read;
1702 
1703  goto out;
1704  }
1705 
1706  /* Apple MJPEG-A */
1707  if ((s->start_code == APP1) && (len > (0x28 - 8))) {
1708  id = get_bits_long(&s->gb, 32);
1709  len -= 4;
1710  /* Apple MJPEG-A */
1711  if (id == AV_RB32("mjpg")) {
1712 #if 0
1713  skip_bits(&s->gb, 32); /* field size */
1714  skip_bits(&s->gb, 32); /* pad field size */
1715  skip_bits(&s->gb, 32); /* next off */
1716  skip_bits(&s->gb, 32); /* quant off */
1717  skip_bits(&s->gb, 32); /* huff off */
1718  skip_bits(&s->gb, 32); /* image off */
1719  skip_bits(&s->gb, 32); /* scan off */
1720  skip_bits(&s->gb, 32); /* data off */
1721 #endif
1722  if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1723  av_log(s->avctx, AV_LOG_INFO, "mjpeg: Apple MJPEG-A header found\n");
1724  }
1725  }
1726 
1727 out:
1728  /* slow but needed for extreme adobe jpegs */
1729  if (len < 0)
1731  "mjpeg: error, decode_app parser read over the end\n");
1732  while (--len > 0)
1733  skip_bits(&s->gb, 8);
1734 
1735  return 0;
1736 }
1737 
1739 {
1740  int len = get_bits(&s->gb, 16);
1741  if (len >= 2 && 8 * len - 16 <= get_bits_left(&s->gb)) {
1742  char *cbuf = av_malloc(len - 1);
1743  if (cbuf) {
1744  int i;
1745  for (i = 0; i < len - 2; i++)
1746  cbuf[i] = get_bits(&s->gb, 8);
1747  if (i > 0 && cbuf[i - 1] == '\n')
1748  cbuf[i - 1] = 0;
1749  else
1750  cbuf[i] = 0;
1751 
1752  if (s->avctx->debug & FF_DEBUG_PICT_INFO)
1753  av_log(s->avctx, AV_LOG_INFO, "comment: '%s'\n", cbuf);
1754 
1755  /* buggy avid, it puts EOI only at every 10th frame */
1756  if (!strncmp(cbuf, "AVID", 4)) {
1757  parse_avid(s, cbuf, len);
1758  } else if (!strcmp(cbuf, "CS=ITU601"))
1759  s->cs_itu601 = 1;
1760  else if ((!strncmp(cbuf, "Intel(R) JPEG Library, version 1", 32) && s->avctx->codec_tag) ||
1761  (!strncmp(cbuf, "Metasoft MJPEG Codec", 20)))
1762  s->flipped = 1;
1763 
1764  av_free(cbuf);
1765  }
1766  }
1767 
1768  return 0;
1769 }
1770 
1771 /* return the 8 bit start code value and update the search
1772  state. Return -1 if no start code found */
1773 static int find_marker(const uint8_t **pbuf_ptr, const uint8_t *buf_end)
1774 {
1775  const uint8_t *buf_ptr;
1776  unsigned int v, v2;
1777  int val;
1778  int skipped = 0;
1779 
1780  buf_ptr = *pbuf_ptr;
1781  while (buf_end - buf_ptr > 1) {
1782  v = *buf_ptr++;
1783  v2 = *buf_ptr;
1784  if ((v == 0xff) && (v2 >= 0xc0) && (v2 <= 0xfe) && buf_ptr < buf_end) {
1785  val = *buf_ptr++;
1786  goto found;
1787  }
1788  skipped++;
1789  }
1790  buf_ptr = buf_end;
1791  val = -1;
1792 found:
1793  av_dlog(NULL, "find_marker skipped %d bytes\n", skipped);
1794  *pbuf_ptr = buf_ptr;
1795  return val;
1796 }
1797 
1799  const uint8_t **buf_ptr, const uint8_t *buf_end,
1800  const uint8_t **unescaped_buf_ptr,
1801  int *unescaped_buf_size)
1802 {
1803  int start_code;
1804  start_code = find_marker(buf_ptr, buf_end);
1805 
1806  av_fast_padded_malloc(&s->buffer, &s->buffer_size, buf_end - *buf_ptr);
1807  if (!s->buffer)
1808  return AVERROR(ENOMEM);
1809 
1810  /* unescape buffer of SOS, use special treatment for JPEG-LS */
1811  if (start_code == SOS && !s->ls) {
1812  const uint8_t *src = *buf_ptr;
1813  uint8_t *dst = s->buffer;
1814 
1815  while (src < buf_end) {
1816  uint8_t x = *(src++);
1817 
1818  *(dst++) = x;
1819  if (s->avctx->codec_id != AV_CODEC_ID_THP) {
1820  if (x == 0xff) {
1821  while (src < buf_end && x == 0xff)
1822  x = *(src++);
1823 
1824  if (x >= 0xd0 && x <= 0xd7)
1825  *(dst++) = x;
1826  else if (x)
1827  break;
1828  }
1829  }
1830  }
1831  *unescaped_buf_ptr = s->buffer;
1832  *unescaped_buf_size = dst - s->buffer;
1833  memset(s->buffer + *unescaped_buf_size, 0,
1835 
1836  av_log(s->avctx, AV_LOG_DEBUG, "escaping removed %"PTRDIFF_SPECIFIER" bytes\n",
1837  (buf_end - *buf_ptr) - (dst - s->buffer));
1838  } else if (start_code == SOS && s->ls) {
1839  const uint8_t *src = *buf_ptr;
1840  uint8_t *dst = s->buffer;
1841  int bit_count = 0;
1842  int t = 0, b = 0;
1843  PutBitContext pb;
1844 
1845  /* find marker */
1846  while (src + t < buf_end) {
1847  uint8_t x = src[t++];
1848  if (x == 0xff) {
1849  while ((src + t < buf_end) && x == 0xff)
1850  x = src[t++];
1851  if (x & 0x80) {
1852  t -= FFMIN(2, t);
1853  break;
1854  }
1855  }
1856  }
1857  bit_count = t * 8;
1858  init_put_bits(&pb, dst, t);
1859 
1860  /* unescape bitstream */
1861  while (b < t) {
1862  uint8_t x = src[b++];
1863  put_bits(&pb, 8, x);
1864  if (x == 0xFF) {
1865  x = src[b++];
1866  put_bits(&pb, 7, x);
1867  bit_count--;
1868  }
1869  }
1870  flush_put_bits(&pb);
1871 
1872  *unescaped_buf_ptr = dst;
1873  *unescaped_buf_size = (bit_count + 7) >> 3;
1874  memset(s->buffer + *unescaped_buf_size, 0,
1876  } else {
1877  *unescaped_buf_ptr = *buf_ptr;
1878  *unescaped_buf_size = buf_end - *buf_ptr;
1879  }
1880 
1881  return start_code;
1882 }
1883 
1884 int ff_mjpeg_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,
1885  AVPacket *avpkt)
1886 {
1887  AVFrame *frame = data;
1888  const uint8_t *buf = avpkt->data;
1889  int buf_size = avpkt->size;
1890  MJpegDecodeContext *s = avctx->priv_data;
1891  const uint8_t *buf_end, *buf_ptr;
1892  const uint8_t *unescaped_buf_ptr;
1893  int hshift, vshift;
1894  int unescaped_buf_size;
1895  int start_code;
1896  int i, index;
1897  int ret = 0;
1898  int is16bit;
1899 
1901  av_freep(&s->stereo3d);
1902  s->adobe_transform = -1;
1903 
1904  buf_ptr = buf;
1905  buf_end = buf + buf_size;
1906  while (buf_ptr < buf_end) {
1907  /* find start next marker */
1908  start_code = ff_mjpeg_find_marker(s, &buf_ptr, buf_end,
1909  &unescaped_buf_ptr,
1910  &unescaped_buf_size);
1911  /* EOF */
1912  if (start_code < 0) {
1913  break;
1914  } else if (unescaped_buf_size > INT_MAX / 8) {
1915  av_log(avctx, AV_LOG_ERROR,
1916  "MJPEG packet 0x%x too big (%d/%d), corrupt data?\n",
1917  start_code, unescaped_buf_size, buf_size);
1918  return AVERROR_INVALIDDATA;
1919  }
1920  av_log(avctx, AV_LOG_DEBUG, "marker=%x avail_size_in_buf=%"PTRDIFF_SPECIFIER"\n",
1921  start_code, buf_end - buf_ptr);
1922 
1923  ret = init_get_bits8(&s->gb, unescaped_buf_ptr, unescaped_buf_size);
1924 
1925  if (ret < 0) {
1926  av_log(avctx, AV_LOG_ERROR, "invalid buffer\n");
1927  goto fail;
1928  }
1929 
1930  s->start_code = start_code;
1931  if (s->avctx->debug & FF_DEBUG_STARTCODE)
1932  av_log(avctx, AV_LOG_DEBUG, "startcode: %X\n", start_code);
1933 
1934  /* process markers */
1935  if (start_code >= 0xd0 && start_code <= 0xd7)
1936  av_log(avctx, AV_LOG_DEBUG,
1937  "restart marker: %d\n", start_code & 0x0f);
1938  /* APP fields */
1939  else if (start_code >= APP0 && start_code <= APP15)
1940  mjpeg_decode_app(s);
1941  /* Comment */
1942  else if (start_code == COM)
1943  mjpeg_decode_com(s);
1944 
1945  ret = -1;
1946 
1947  if (!CONFIG_JPEGLS_DECODER &&
1948  (start_code == SOF48 || start_code == LSE)) {
1949  av_log(avctx, AV_LOG_ERROR, "JPEG-LS support not enabled.\n");
1950  return AVERROR(ENOSYS);
1951  }
1952 
1953  switch (start_code) {
1954  case SOI:
1955  s->restart_interval = 0;
1956  s->restart_count = 0;
1957  /* nothing to do on SOI */
1958  break;
1959  case DQT:
1961  break;
1962  case DHT:
1963  if ((ret = ff_mjpeg_decode_dht(s)) < 0) {
1964  av_log(avctx, AV_LOG_ERROR, "huffman table decode error\n");
1965  goto fail;
1966  }
1967  break;
1968  case SOF0:
1969  case SOF1:
1970  s->lossless = 0;
1971  s->ls = 0;
1972  s->progressive = 0;
1973  if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1974  goto fail;
1975  break;
1976  case SOF2:
1977  s->lossless = 0;
1978  s->ls = 0;
1979  s->progressive = 1;
1980  if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1981  goto fail;
1982  break;
1983  case SOF3:
1984  s->lossless = 1;
1985  s->ls = 0;
1986  s->progressive = 0;
1987  if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1988  goto fail;
1989  break;
1990  case SOF48:
1991  s->lossless = 1;
1992  s->ls = 1;
1993  s->progressive = 0;
1994  if ((ret = ff_mjpeg_decode_sof(s)) < 0)
1995  goto fail;
1996  break;
1997  case LSE:
1998  if (!CONFIG_JPEGLS_DECODER ||
1999  (ret = ff_jpegls_decode_lse(s)) < 0)
2000  goto fail;
2001  break;
2002  case EOI:
2003 eoi_parser:
2004  s->cur_scan = 0;
2005  if (!s->got_picture) {
2006  av_log(avctx, AV_LOG_WARNING,
2007  "Found EOI before any SOF, ignoring\n");
2008  break;
2009  }
2010  if (s->interlaced) {
2011  s->bottom_field ^= 1;
2012  /* if not bottom field, do not output image yet */
2013  if (s->bottom_field == !s->interlace_polarity)
2014  break;
2015  }
2016  if ((ret = av_frame_ref(frame, s->picture_ptr)) < 0)
2017  return ret;
2018  *got_frame = 1;
2019  s->got_picture = 0;
2020 
2021  if (!s->lossless) {
2022  int qp = FFMAX3(s->qscale[0],
2023  s->qscale[1],
2024  s->qscale[2]);
2025  int qpw = (s->width + 15) / 16;
2026  AVBufferRef *qp_table_buf = av_buffer_alloc(qpw);
2027  if (qp_table_buf) {
2028  memset(qp_table_buf->data, qp, qpw);
2029  av_frame_set_qp_table(data, qp_table_buf, 0, FF_QSCALE_TYPE_MPEG1);
2030  }
2031 
2032  if(avctx->debug & FF_DEBUG_QP)
2033  av_log(avctx, AV_LOG_DEBUG, "QP: %d\n", qp);
2034  }
2035 
2036  goto the_end;
2037  case SOS:
2038  s->cur_scan++;
2039  if ((ret = ff_mjpeg_decode_sos(s, NULL, 0, NULL)) < 0 &&
2040  (avctx->err_recognition & AV_EF_EXPLODE))
2041  goto fail;
2042  break;
2043  case DRI:
2044  mjpeg_decode_dri(s);
2045  break;
2046  case SOF5:
2047  case SOF6:
2048  case SOF7:
2049  case SOF9:
2050  case SOF10:
2051  case SOF11:
2052  case SOF13:
2053  case SOF14:
2054  case SOF15:
2055  case JPG:
2056  av_log(avctx, AV_LOG_ERROR,
2057  "mjpeg: unsupported coding type (%x)\n", start_code);
2058  break;
2059  }
2060 
2061  /* eof process start code */
2062  buf_ptr += (get_bits_count(&s->gb) + 7) / 8;
2063  av_log(avctx, AV_LOG_DEBUG,
2064  "marker parser used %d bytes (%d bits)\n",
2065  (get_bits_count(&s->gb) + 7) / 8, get_bits_count(&s->gb));
2066  }
2067  if (s->got_picture && s->cur_scan) {
2068  av_log(avctx, AV_LOG_WARNING, "EOI missing, emulating\n");
2069  goto eoi_parser;
2070  }
2071  av_log(avctx, AV_LOG_FATAL, "No JPEG data found in image\n");
2072  return AVERROR_INVALIDDATA;
2073 fail:
2074  s->got_picture = 0;
2075  return ret;
2076 the_end:
2077 
2078  is16bit = av_pix_fmt_desc_get(s->avctx->pix_fmt)->comp[0].step_minus1;
2079 
2080  if (s->upscale_h) {
2081  int p;
2083  avctx->pix_fmt == AV_PIX_FMT_YUV444P ||
2084  avctx->pix_fmt == AV_PIX_FMT_YUVJ440P ||
2085  avctx->pix_fmt == AV_PIX_FMT_YUV440P ||
2086  avctx->pix_fmt == AV_PIX_FMT_YUVA444P ||
2087  avctx->pix_fmt == AV_PIX_FMT_YUVJ420P ||
2088  avctx->pix_fmt == AV_PIX_FMT_YUV420P ||
2089  avctx->pix_fmt == AV_PIX_FMT_YUV420P16||
2090  avctx->pix_fmt == AV_PIX_FMT_GBRAP
2091  );
2092  avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &hshift, &vshift);
2093  for (p = 0; p<4; p++) {
2094  uint8_t *line = s->picture_ptr->data[p];
2095  int w = s->width;
2096  if (!(s->upscale_h & (1<<p)))
2097  continue;
2098  if (p==1 || p==2)
2099  w >>= hshift;
2100  av_assert0(w > 0);
2101  for (i = 0; i < s->chroma_height; i++) {
2102  if (is16bit) ((uint16_t*)line)[w - 1] = ((uint16_t*)line)[(w - 1) / 2];
2103  else line[w - 1] = line[(w - 1) / 2];
2104  for (index = w - 2; index > 0; index--) {
2105  if (is16bit)
2106  ((uint16_t*)line)[index] = (((uint16_t*)line)[index / 2] + ((uint16_t*)line)[(index + 1) / 2]) >> 1;
2107  else
2108  line[index] = (line[index / 2] + line[(index + 1) / 2]) >> 1;
2109  }
2110  line += s->linesize[p];
2111  }
2112  }
2113  }
2114  if (s->upscale_v) {
2115  int p;
2117  avctx->pix_fmt == AV_PIX_FMT_YUV444P ||
2118  avctx->pix_fmt == AV_PIX_FMT_YUVJ422P ||
2119  avctx->pix_fmt == AV_PIX_FMT_YUV422P ||
2120  avctx->pix_fmt == AV_PIX_FMT_YUVA444P ||
2121  avctx->pix_fmt == AV_PIX_FMT_GBRAP
2122  );
2123  avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &hshift, &vshift);
2124  for (p = 0; p < 4; p++) {
2125  uint8_t *dst = &((uint8_t *)s->picture_ptr->data[p])[(s->height - 1) * s->linesize[p]];
2126  int w = s->width;
2127  if (!(s->upscale_v & (1<<p)))
2128  continue;
2129  if (p==1 || p==2)
2130  w = FF_CEIL_RSHIFT(w, hshift);
2131  for (i = s->height - 1; i; i--) {
2132  uint8_t *src1 = &((uint8_t *)s->picture_ptr->data[p])[i / 2 * s->linesize[p]];
2133  uint8_t *src2 = &((uint8_t *)s->picture_ptr->data[p])[(i + 1) / 2 * s->linesize[p]];
2134  if (src1 == src2 || i == s->height - 1) {
2135  memcpy(dst, src1, w);
2136  } else {
2137  for (index = 0; index < w; index++)
2138  dst[index] = (src1[index] + src2[index]) >> 1;
2139  }
2140  dst -= s->linesize[p];
2141  }
2142  }
2143  }
2144  if (s->flipped) {
2145  int j;
2146  avcodec_get_chroma_sub_sample(s->avctx->pix_fmt, &hshift, &vshift);
2147  for (index=0; index<4; index++) {
2148  uint8_t *dst = s->picture_ptr->data[index];
2149  int w = s->picture_ptr->width;
2150  int h = s->picture_ptr->height;
2151  if(index && index<3){
2152  w = FF_CEIL_RSHIFT(w, hshift);
2153  h = FF_CEIL_RSHIFT(h, vshift);
2154  }
2155  if(dst){
2156  uint8_t *dst2 = dst + s->picture_ptr->linesize[index]*(h-1);
2157  for (i=0; i<h/2; i++) {
2158  for (j=0; j<w; j++)
2159  FFSWAP(int, dst[j], dst2[j]);
2160  dst += s->picture_ptr->linesize[index];
2161  dst2 -= s->picture_ptr->linesize[index];
2162  }
2163  }
2164  }
2165  }
2166  if (s->adobe_transform == 0 && s->avctx->pix_fmt == AV_PIX_FMT_GBRAP) {
2167  int w = s->picture_ptr->width;
2168  int h = s->picture_ptr->height;
2169  for (i=0; i<h; i++) {
2170  int j;
2171  uint8_t *dst[4];
2172  for (index=0; index<4; index++) {
2173  dst[index] = s->picture_ptr->data[index]
2174  + s->picture_ptr->linesize[index]*i;
2175  }
2176  for (j=0; j<w; j++) {
2177  int k = dst[3][j];
2178  int r = dst[0][j] * k;
2179  int g = dst[1][j] * k;
2180  int b = dst[2][j] * k;
2181  dst[0][j] = g*257 >> 16;
2182  dst[1][j] = b*257 >> 16;
2183  dst[2][j] = r*257 >> 16;
2184  dst[3][j] = 255;
2185  }
2186  }
2187  }
2188  if (s->adobe_transform == 2 && s->avctx->pix_fmt == AV_PIX_FMT_YUVA444P) {
2189  int w = s->picture_ptr->width;
2190  int h = s->picture_ptr->height;
2191  for (i=0; i<h; i++) {
2192  int j;
2193  uint8_t *dst[4];
2194  for (index=0; index<4; index++) {
2195  dst[index] = s->picture_ptr->data[index]
2196  + s->picture_ptr->linesize[index]*i;
2197  }
2198  for (j=0; j<w; j++) {
2199  int k = dst[3][j];
2200  int r = (255 - dst[0][j]) * k;
2201  int g = (128 - dst[1][j]) * k;
2202  int b = (128 - dst[2][j]) * k;
2203  dst[0][j] = r*257 >> 16;
2204  dst[1][j] = (g*257 >> 16) + 128;
2205  dst[2][j] = (b*257 >> 16) + 128;
2206  dst[3][j] = 255;
2207  }
2208  }
2209  }
2210 
2211  if (s->stereo3d) {
2212  AVStereo3D *stereo = av_stereo3d_create_side_data(data);
2213  if (stereo) {
2214  stereo->type = s->stereo3d->type;
2215  stereo->flags = s->stereo3d->flags;
2216  }
2217  av_freep(&s->stereo3d);
2218  }
2219 
2222 
2223  av_log(avctx, AV_LOG_DEBUG, "decode frame unused %"PTRDIFF_SPECIFIER" bytes\n",
2224  buf_end - buf_ptr);
2225 // return buf_end - buf_ptr;
2226  return buf_ptr - buf;
2227 }
2228 
2230 {
2231  MJpegDecodeContext *s = avctx->priv_data;
2232  int i, j;
2233 
2234  if (s->interlaced && s->bottom_field == !s->interlace_polarity && s->got_picture && !avctx->frame_number) {
2235  av_log(avctx, AV_LOG_INFO, "Single field\n");
2236  }
2237 
2238  if (s->picture) {
2239  av_frame_free(&s->picture);
2240  s->picture_ptr = NULL;
2241  } else if (s->picture_ptr)
2243 
2244  av_freep(&s->buffer);
2245  av_freep(&s->stereo3d);
2246  av_freep(&s->ljpeg_buffer);
2247  s->ljpeg_buffer_size = 0;
2248 
2249  for (i = 0; i < 3; i++) {
2250  for (j = 0; j < 4; j++)
2251  ff_free_vlc(&s->vlcs[i][j]);
2252  }
2253  for (i = 0; i < MAX_COMPONENTS; i++) {
2254  av_freep(&s->blocks[i]);
2255  av_freep(&s->last_nnz[i]);
2256  }
2258  return 0;
2259 }
2260 
2261 static void decode_flush(AVCodecContext *avctx)
2262 {
2263  MJpegDecodeContext *s = avctx->priv_data;
2264  s->got_picture = 0;
2265 }
2266 
2267 #if CONFIG_MJPEG_DECODER
2268 #define OFFSET(x) offsetof(MJpegDecodeContext, x)
2269 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
2270 static const AVOption options[] = {
2271  { "extern_huff", "Use external huffman table.",
2272  OFFSET(extern_huff), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD },
2273  { NULL },
2274 };
2275 
2276 static const AVClass mjpegdec_class = {
2277  .class_name = "MJPEG decoder",
2278  .item_name = av_default_item_name,
2279  .option = options,
2280  .version = LIBAVUTIL_VERSION_INT,
2281 };
2282 
2283 AVCodec ff_mjpeg_decoder = {
2284  .name = "mjpeg",
2285  .long_name = NULL_IF_CONFIG_SMALL("MJPEG (Motion JPEG)"),
2286  .type = AVMEDIA_TYPE_VIDEO,
2287  .id = AV_CODEC_ID_MJPEG,
2288  .priv_data_size = sizeof(MJpegDecodeContext),
2292  .flush = decode_flush,
2293  .capabilities = CODEC_CAP_DR1,
2294  .max_lowres = 3,
2295  .priv_class = &mjpegdec_class,
2296 };
2297 #endif
2298 #if CONFIG_THP_DECODER
2299 AVCodec ff_thp_decoder = {
2300  .name = "thp",
2301  .long_name = NULL_IF_CONFIG_SMALL("Nintendo Gamecube THP video"),
2302  .type = AVMEDIA_TYPE_VIDEO,
2303  .id = AV_CODEC_ID_THP,
2304  .priv_data_size = sizeof(MJpegDecodeContext),
2308  .flush = decode_flush,
2309  .capabilities = CODEC_CAP_DR1,
2310  .max_lowres = 3,
2311 };
2312 #endif