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