File: jpeg.cpp

package info (click to toggle)
libjpeg 0.0~git20250815.25f7128-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,108 kB
  • sloc: cpp: 36,493; makefile: 619; ansic: 275; sh: 54; python: 39; perl: 11
file content (977 lines) | stat: -rw-r--r-- 27,987 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
/*************************************************************************

    This project implements a complete(!) JPEG (Recommendation ITU-T
    T.81 | ISO/IEC 10918-1) codec, plus a library that can be used to
    encode and decode JPEG streams. 
    It also implements ISO/IEC 18477 aka JPEG XT which is an extension
    towards intermediate, high-dynamic-range lossy and lossless coding
    of JPEG. In specific, it supports ISO/IEC 18477-3/-6/-7/-8 encoding.

    Note that only Profiles C and D of ISO/IEC 18477-7 are supported
    here. Check the JPEG XT reference software for a full implementation
    of ISO/IEC 18477-7.

    Copyright (C) 2012-2018 Thomas Richter, University of Stuttgart and
    Accusoft. (C) 2019-2020 Thomas Richter, Fraunhofer IIS.

    This program is available under two licenses, GPLv3 and the ITU
    Software licence Annex A Option 2, RAND conditions.

    For the full text of the GPU license option, see README.license.gpl.
    For the full text of the ITU license option, see README.license.itu.
    
    You may freely select between these two options.

    For the GPL option, please note the following:

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*************************************************************************/

/*
** Definition of the library interface
**
** This file defines the main entry points and user accessible data
** for the 10918 (JPEG) codec. Except for the tagitem and hook methods,
** no other headers should be publically accessible.
** 
** $Id: jpeg.cpp,v 1.29 2021/12/01 11:14:42 thor Exp $
**
*/

/// Includes
#include "tools/environment.hpp"
#include "interface/tagitem.hpp"
#include "interface/hooks.hpp"
#include "interface/jpeg.hpp"
#include "interface/bitmaphook.hpp"
#include "codestream/rectanglerequest.hpp"
#include "codestream/encoder.hpp"
#include "codestream/decoder.hpp"
#include "codestream/image.hpp"
#include "codestream/tables.hpp"
#include "marker/frame.hpp"
#include "marker/scan.hpp"
#include "marker/component.hpp"
#include "boxes/mergingspecbox.hpp"
#include "boxes/checksumbox.hpp"
#include "tools/checksum.hpp"
#include "io/iostream.hpp"
#include "std/assert.hpp"
///

/// Opaque helper structure for both the environment and the main class.
struct JPEG_Helper : public JPEG {
  class Environ m_Env;
};
///

/// JPEG::JPEG
// Does really nothing sensible right now. Main stuff is done in
// the doConstruct call.
JPEG::JPEG(void)
{
}
///

/// JPEG::~JPEG
JPEG::~JPEG(void)
{
  assert(m_pEnviron == NULL);
  assert(m_pEncoder == NULL);
  assert(m_pDecoder == NULL);
}
///

/// JPEG::doConstruct
// The real constructor. We must use this, since we're not using
// NEW to allocate objects, but MALLOC.
void JPEG::doConstruct(class Environ *env)
{
  m_pEnviron = env;
  m_pEncoder = NULL;
  m_pDecoder = NULL;

  //
  // State variables.
  m_pIOStream          = NULL;
  m_pImage             = NULL;
  m_pFrame             = NULL;
  m_pScan              = NULL;
  m_bRow               = false;
  m_bDecoding          = false;
  m_bEncoding          = false;
  m_bHeaderWritten     = false;
  m_bOptimized         = false;
  m_bOptimizeHuffman   = false;
  m_bOptimizeQuantizer = false;
}
///

/// JPEG::doDestruct
// The real destructor. We must use this, since we're not using
// NEW to allocate objects, but MALLOC.
void JPEG::doDestruct(void)
{
  delete m_pEncoder;
  m_pEncoder = NULL;

  delete m_pDecoder;
  m_pDecoder = NULL;

  delete m_pIOStream;
  m_pIOStream = NULL;

  m_pEnviron = NULL; // Deleted elsewhere
}
///

/// JPEG::Construct
// Create an instance of this class.
class JPEG *JPEG::Construct(struct JPG_TagItem *tags)
{
  class Environ ev(tags);           // build up a temporary environment.
  class Environ *m_pEnviron = &ev;  // needed for J2K infrastructure
  struct JPEG_Helper *volatile h_jpeg = NULL;

  JPG_TRY {
    class Environ *env;

    h_jpeg = (struct JPEG_Helper *)JPG_MALLOC(sizeof(struct JPEG_Helper));
    env    = &(h_jpeg->m_Env);
    *env   = ev; // Copy the temporary environment over.
    h_jpeg->doConstruct(env);

  } JPG_CATCH {
    if (h_jpeg) {
      h_jpeg->m_Env.PostLastError();
      h_jpeg->m_Env.PrintException();
      h_jpeg->doDestruct();
      // This looks silly, but is required for orderly shutdown.
      ev = h_jpeg->m_Env;
      JPG_FREE(h_jpeg);
    } else {
      ev.PostLastError();
      ev.PrintException();
    }
    h_jpeg = NULL;
    // Return immediately. Do not try to clean up!
    return NULL;
  } JPG_ENDTRY;

#if CHECK_LEVEL > 0
  h_jpeg->m_Env.TestExceptionStack();
#endif
  return h_jpeg;
}
///

/// JPEG::Destruct
// The real destructor. We must use this, since we're not using
// NEW to allocate objects, but MALLOC.
void JPEG::Destruct(class JPEG *o)
{
  if (o) {
    struct JPEG_Helper *h_jpeg = (struct JPEG_Helper *)o;
    o->doDestruct();
#if CHECK_LEVEL > 0
    h_jpeg->m_Env.TestExceptionStack();
#endif
    {
      // Build a temporary environment for releasing
      // this thingy.
      class Environ ev(h_jpeg->m_Env);
      class Environ *m_pEnviron = &ev;
      JPG_FREE(o);
    }
  }
}
///

/// JPEG::Read
// This is a slim wrapper around the reader which handles
// errors.
JPG_LONG JPEG::Read(struct JPG_TagItem *tags)
{ 
  volatile JPG_LONG ret = TRUE;

  JPG_TRY {
    ReadInternal(tags);
  } JPG_CATCH {
    ret = JPG_FALSE;
  } JPG_ENDTRY;

  return ret;
}
///

/// JPEG::StopDecoding
// Complete the decoding, test for the checksum,
// then exit.
void JPEG::StopDecoding(void)
{ 
  if (m_pImage) {
    class ChecksumBox *box;
    class Checksum    *sum;
    // Make sure we don't get the residual, but the legacy image.
    m_pImage->ResetToFirstFrame();
    box = m_pImage->TablesOf()->ChecksumOf();
    sum = m_pImage->ChecksumOf();
    if (box && sum) {
      if (sum->ValueOf() != box->ValueOf()) {
        JPG_WARN(PHASE_ERROR,"Frame::StopDecoding",
                 "Found a mismatching checksum of the legacy stream, HDR reconstructed image may be wrong");
      }
    }
  }
  m_bDecoding = false;
}
///

/// JPEG::ReadInternal
// Read a file. This takes all of the tags, class Decode takes.
void JPEG::ReadInternal(struct JPG_TagItem *tags)
{   
  LONG stopflags = tags->GetTagData(JPGTAG_DECODER_STOP);

  if (m_pEncoder)
    JPG_THROW(OBJECT_EXISTS,"JPEG::ReadInternal","encoding in process, cannot start decoding");

  if (m_pDecoder == NULL) {
    m_pDecoder       = new(m_pEnviron) class Decoder(m_pEnviron);
    m_bDecoding      = true; 
    m_pFrame         = NULL;
    m_pScan          = NULL;
    m_bRow           = false;
    m_bEncoding      = false;
  }

  if (!m_bDecoding)
    return;

  if (m_pIOStream == NULL) {
    struct JPG_Hook *iohook = (struct JPG_Hook *)(tags->GetTagPtr(JPGTAG_HOOK_IOHOOK));
    if (iohook == NULL)
      JPG_THROW(OBJECT_DOESNT_EXIST,"JPEG::ReadInternal","no IOHook defined to read the data from");

    m_pIOStream = new(m_pEnviron) class IOStream(m_pEnviron,tags);
  }

  assert(m_pIOStream);
  
  while (m_pImage == NULL) {
    // Several iterations may be necessary to parse
    // off the header, each taking one marker of the
    // header.
    m_pImage = m_pDecoder->ParseHeaderIncremental(m_pIOStream);
    if (stopflags & JPGFLAG_DECODER_STOP_IMAGE)
      return;
  }

  assert(m_pImage);

  while(m_bDecoding) {
    if (m_pFrame == NULL) {
      m_pFrame = m_pImage->StartParseFrame(m_pIOStream);
      if (m_pFrame) {
        m_pDecoder->ParseTags(tags);
        if (stopflags & JPGFLAG_DECODER_STOP_FRAME)
          return;
      }
    }

    if (m_pFrame) {
      while (m_pScan == NULL) {
        m_pScan = m_pFrame->StartParseScan(m_pImage->InputStreamOf(m_pIOStream),m_pImage->ChecksumOf());
        //
        if (m_pScan == NULL) {
          // This is not yet the start of the scan, but might
          // either be a frame trailer, or part of the frame header.
          if (m_pFrame->isEndOfFrame()) {
            if (!m_pFrame->ParseTrailer(m_pImage->InputStreamOf(m_pIOStream))) {
              // Frame done, advance to the next frame.
              m_pFrame = NULL;
              if (!m_pImage->ParseTrailer(m_pIOStream)) {
                // Image done, stop decoding, image is now loaded.
                StopDecoding();
                return;
              }
            }
          } else {
            if (stopflags & JPGFLAG_DECODER_STOP_FRAME)
              return;
          }
          // else continue looking for the start of scan.
        } else {
          if (stopflags & JPGFLAG_DECODER_STOP_SCAN)
            return;
        }
      }

      if (m_pScan) {
        if (m_bRow == false) {
          m_bRow = m_pScan->StartMCURow();
          if (m_bRow) {
            if (stopflags & JPGFLAG_DECODER_STOP_ROW)
              return;
          } else {
            // Scan done, advance to the next scan.
            m_pFrame->EndParseScan();
            m_pScan = NULL;
            if (!m_pFrame->ParseTrailer(m_pImage->InputStreamOf(m_pIOStream))) {
              // Frame done, advance to the next frame.
              m_pFrame = NULL;
              if (!m_pImage->ParseTrailer(m_pIOStream)) {
                // Image done, stop decoding, image is now loaded.
                StopDecoding();
                return;
              }
            }
          }
        }
        
        if (m_bRow) {
          while (m_pScan->ParseMCU()) {
            if (stopflags & JPGFLAG_DECODER_STOP_MCU)
              return;
          } 
          m_bRow = false;
        }
      }
    }
  }
}
///

/// JPEG::Write
// Write a file. This takes all of the tags, class Encode takes.
JPG_LONG JPEG::Write(struct JPG_TagItem *tags)
{ 
  volatile JPG_LONG ret = JPG_TRUE;

  JPG_TRY {
    WriteInternal(tags);
  } JPG_CATCH {
    ret = JPG_FALSE;
  } JPG_ENDTRY;

  return ret;
}
///

/// JPEG::WriteInternal
// Write a file. Exceptions are thrown here and captured outside.
void JPEG::WriteInternal(struct JPG_TagItem *tags)
{ 
  LONG stopflags = tags->GetTagData(JPGTAG_ENCODER_STOP);

  if (m_pDecoder)
    JPG_THROW(OBJECT_EXISTS,"JPEG::WriteInternal","decoding in process, cannot start encoding");

  if (m_pImage == NULL)
    JPG_THROW(OBJECT_DOESNT_EXIST,"JPEG::WriteInternal","no image data loaded, use ProvideImage first");
  
  if (m_pEncoder == NULL) {
    m_bEncoding      = true; 
    m_pFrame         = NULL;
    m_pScan          = NULL;
    m_bRow           = false;
    m_bDecoding      = false;
    m_bHeaderWritten = false;
    m_bOptimized     = false;
  }

  //
  // Actually, we do not need the encoder class here.
  m_bOptimizeHuffman   = RequiresTwoPassEncoding(tags);

  if (!m_bEncoding)
    return;

  if (m_pIOStream == NULL) {
    struct JPG_Hook *iohook = (struct JPG_Hook *)(tags->GetTagPtr(JPGTAG_HOOK_IOHOOK));
    if (iohook == NULL)
      JPG_THROW(OBJECT_DOESNT_EXIST,"JPEG::WriteInternal","no IOHook defined to write the data to");

    m_pIOStream = new(m_pEnviron) class IOStream(m_pEnviron,tags);
  }

  assert(m_pIOStream);
  
  if (m_bHeaderWritten == false) {
    m_pImage->WriteHeader(m_pIOStream);
    m_bHeaderWritten = true;
    if (stopflags & JPGFLAG_ENCODER_STOP_IMAGE)
      return;
  }

  assert(m_pImage);


  if (!m_bOptimized) {
    // Run the R/D optimization over the DC part if we have not yet
    // done that. This is a joint optimization that requires full
    // access to all data and cannot be run on the fly.
    if (m_bOptimizeQuantizer) {
      do {
        class Frame *frame = m_pImage->StartOptimizeFrame();
        do {
          class Scan *scan = frame->StartOptimizeScan();
          scan->OptimizeDC();
        } while(frame->NextScan());
      } while(m_pImage->NextFrame());
    }
    // Now try find a better Huffman coding.
    if (m_bOptimizeHuffman) {
      do {
        class Frame *frame = m_pImage->StartMeasureFrame();
        do {
          class Scan *scan = frame->StartMeasureScan();
          while(scan->StartMCURow()) { 
            while(scan->WriteMCU()) {
              ;
            }
          }
          scan->Flush();
        } while(frame->NextScan());
      } while(m_pImage->NextFrame());
    }
    m_bOptimized = true;
    m_pImage->ResetToFirstFrame();
  }

  while(m_bEncoding) {
    if (m_pFrame == NULL) {
      m_pFrame = m_pImage->StartWriteFrame(m_pIOStream);
      if (stopflags & JPGFLAG_ENCODER_STOP_FRAME)
        return;
    }
    assert(m_pFrame);

    if (m_pScan == NULL) {
      m_pScan = m_pFrame->StartWriteScan(m_pImage->OutputStreamOf(m_pIOStream),m_pImage->ChecksumOf());
      if (stopflags & JPGFLAG_ENCODER_STOP_SCAN)
        return;
    }
    assert(m_pScan);

    if (!m_bRow) {
      if (m_pScan->StartMCURow()) {
        m_bRow = true;
        if (stopflags & JPGFLAG_ENCODER_STOP_ROW)
          return;
      } else {
        // Scan done, flush it out.
        m_pFrame->EndWriteScan();
        //m_pScan->Flush(); included in the above.
        // This will write the DNL marker.
        m_pFrame->CompleteRefimentScan(m_pIOStream);
        m_pFrame->WriteTrailer(m_pImage->OutputStreamOf(m_pIOStream));
        m_pScan = NULL;
        if (!m_pFrame->NextScan()) {
          m_pFrame = NULL;
          if (!m_pImage->NextFrame()) {
            m_pImage->WriteTrailer(m_pIOStream);
            m_pIOStream->Flush();
            m_bEncoding = false;
            return;
          }
        }
      }
    }

    if (m_bRow) {
      while (m_pScan->WriteMCU()) {
        if (stopflags & JPGFLAG_ENCODER_STOP_MCU)
          return;
      }
      m_bRow = false;
    }
  }
}
///

/// JPEG::PeekMarker
// In case reading was interrupted by a JPGTAG_DECODER_STOP mask
// at some point in the codestream, this call returns the next
// 16 bits at the current stop position without removing them
// from the stream. You may want to use these bits to decide
// whether you (instead of the library) want to parse the following
// data off yourself with the calls below. This call returns -1 on
// an EOF or any other error.
// Currently, the tags argument is not used, just pass NULL.
JPG_LONG JPEG::PeekMarker(struct JPG_TagItem *tags)
{
  volatile JPG_LONG ret = 0;

  JPG_TRY {
    ret = InternalPeekMarker(tags);
  } JPG_CATCH {
    ret = -1; // Deliver an error.
  } JPG_ENDTRY;

  return ret;
}
///

/// JPEG::InternalPeekMarker
// Return the marker at the current stream position or -1 for an error.
// tags is currently unused.
JPG_LONG JPEG::InternalPeekMarker(struct JPG_TagItem *) const
{
  LONG marker;
  
  if (m_pEncoder)
     JPG_THROW(OBJECT_EXISTS,"JPEG::PeekMarker","encoding in process, cannot read data");

  if (m_pDecoder == NULL)
    JPG_THROW(OBJECT_DOESNT_EXIST,"JPEG::PeekMarker","decoding not in progress");

  if (m_pIOStream == NULL)
    JPG_THROW(OBJECT_DOESNT_EXIST,"JPEG::PeekMarker","I/O stream does not exist, decoding did not start yet");

  marker = m_pIOStream->PeekWord();
  
  switch(marker) {
  case 0xffc0:
  case 0xffc1:
  case 0xffc2:
  case 0xffc3:
  case 0xffc5:
  case 0xffc6:
  case 0xffc7:
  case 0xffc8:
  case 0xffc9:
  case 0xffca:
  case 0xffcb:
  case 0xffcd:
  case 0xffce:
  case 0xffcf: // all start of frame markers.
  case 0xffb1: // residual scan
  case 0xffb2: // residual scan, progressive
  case 0xffb3: // residual scan, large dct
  case 0xffb9: // residual scan, ac coded
  case 0xffba: // residual scan, ac coded, progressive
  case 0xffbb: // residual scan, ac coded, large dct
  case 0xffd9: // EOI
  case 0xffda: // Start of scan.
  case 0xffde: // DHP
  case 0xfff7: // JPEG LS SOF55
    // These are all markers that cannot be handled externally in any case.
    return 0;
  }
  
  return marker;
}
///

/// JPEG::ReadMarker
// In case reading was interrupted by a JPGTAG_DECODER_STOP mask,
// remove parts of the data from the stream outside of the library.
// This call reads the given number of bytes into the supplied
// buffer and returns the number of bytes it was able to read, or -1
// for an error. The tags argument is currently unused and should be
// set to NULL.
JPG_LONG JPEG::ReadMarker(void *buffer,JPG_LONG bufsize,struct JPG_TagItem *tags)
{
  volatile JPG_LONG ret = 0;

  JPG_TRY {
    ret = InternalReadMarker(buffer,bufsize,tags);
  } JPG_CATCH {
    ret = -1; // Deliver an error.
  } JPG_ENDTRY;

  return ret;
}
///

/// JPEG::InternalReadMarker
// Read data from the current stream position, return -1 for an error.
JPG_LONG JPEG::InternalReadMarker(void *buffer,JPG_LONG bufsize,struct JPG_TagItem *) const
{
  if (m_pEncoder)
     JPG_THROW(OBJECT_EXISTS,"JPEG::ReadMarker","encoding in process, cannot read data");

  if (m_pDecoder == NULL)
    JPG_THROW(OBJECT_DOESNT_EXIST,"JPEG::ReadMarker","decoding not in progress");

  if (m_pIOStream == NULL)
    JPG_THROW(OBJECT_DOESNT_EXIST,"JPEG::ReadMarker","I/O stream does not exist, decoding did not start yet");

  return m_pIOStream->Read((UBYTE *)buffer,bufsize);
}
///

/// JPEG::SkipMarker
// Skip over the given number of bytes. Returns -1 for failure, anything
// else for success. The tags argument is currently unused and should
// be set to NULL.
JPG_LONG JPEG::SkipMarker(JPG_LONG bytes,struct JPG_TagItem *tags)
{
  volatile JPG_LONG ret = 0;

  JPG_TRY {
    ret = InternalSkipMarker(bytes,tags);
  } JPG_CATCH {
    ret = -1; // Deliver an error.
  } JPG_ENDTRY;

  return ret;
}
///

/// JPEG::InternalSkipMarker
// Skip over the given number of bytes.
JPG_LONG JPEG::InternalSkipMarker(JPG_LONG bytes,struct JPG_TagItem *) const
{
  if (m_pEncoder)
     JPG_THROW(OBJECT_EXISTS,"JPEG::SkipMarker","encoding in process, cannot read data");

  if (m_pDecoder == NULL)
    JPG_THROW(OBJECT_DOESNT_EXIST,"JPEG::SkipMarker","decoding not in progress");

  if (m_pIOStream == NULL)
    JPG_THROW(OBJECT_DOESNT_EXIST,"JPEG::SkipMarker","I/O stream does not exist, decoding did not start yet");

  m_pIOStream->SkipBytes(bytes);

  return 0;
}
///

/// JPEG::WriteMarker
// In case writing was interrupted by a JPGTAG_ENCODER_STOP mask,
// this call can be used to inject additional data into the codestream.
// The typical application of this call is to inject custom markers.
// It writes the bytes in the buffer of the given size to the stream,
// and returns the number of bytes it could write, or -1 for an error.
// The tags argument is currently unused and should be set to NULL.
JPG_LONG JPEG::WriteMarker(void *buffer,JPG_LONG bufsize,struct JPG_TagItem *tags)
{
  volatile JPG_LONG ret = 0;

  JPG_TRY {
    ret = InternalWriteMarker(buffer,bufsize,tags);
  } JPG_CATCH {
    ret = -1; // Deliver an error.
  } JPG_ENDTRY;

  return ret;
}
///

/// JPEG::InternalWriteMarker
// Write data to the current stream position.
JPG_LONG JPEG::InternalWriteMarker(void *buffer,JPG_LONG bufsize,struct JPG_TagItem *) const
{
  if (m_pDecoder)
     JPG_THROW(OBJECT_EXISTS,"JPEG::WriteMarker","decoding in process, cannot write data");

  if (m_pEncoder == NULL)
    JPG_THROW(OBJECT_DOESNT_EXIST,"JPEG::WriteMarker","encoding not in progress");

  if (m_pIOStream == NULL)
    JPG_THROW(OBJECT_DOESNT_EXIST,"JPEG::WriteMarker","I/O stream does not exist, decoding did not start yet");

  return m_pIOStream->Write((UBYTE *)buffer,bufsize);
}
///

/// JPEG::DisplayRectangle
// Reverse transform a given rectangle
JPG_LONG JPEG::DisplayRectangle(struct JPG_TagItem *tags)
{  
  volatile JPG_LONG ret = JPG_TRUE;

  JPG_TRY {
    InternalDisplayRectangle(tags);
  } JPG_CATCH {
    ret = JPG_FALSE;
  } JPG_ENDTRY;

  return ret;
}
///

/// JPEG::InternalDisplayRectangle
// Reverse transform a given rectangle, internal version that
// throws exceptions.
void JPEG::InternalDisplayRectangle(struct JPG_TagItem *tags)
{
  class BitMapHook bmh(tags);
  struct RectangleRequest rr;
  
  if (m_pImage == NULL)
    JPG_THROW(OBJECT_DOESNT_EXIST,"JPEG::InternalDisplayRectangle","no image loaded that could be displayed");


  rr.ParseTags(tags,m_pImage);
  m_pImage->ReconstructRegion(&bmh,&rr);
}
///

/// JPEG::ProvideImage
// Forward transform an image, push it into the encoder.
JPG_LONG JPEG::ProvideImage(struct JPG_TagItem *tags)
{
  volatile JPG_LONG ret = JPG_TRUE;

  JPG_TRY {
    InternalProvideImage(tags);
  } JPG_CATCH {
    ret = JPG_FALSE;
  } JPG_ENDTRY;

  return ret;
}
///

/// JPEG::RequiresTwoPassEncoding
// Check whether any of the scans is optimized Huffman and thus requires a two-pass
// go over the data.
bool JPEG::RequiresTwoPassEncoding(const struct JPG_TagItem *tags) const
{
  if (m_bOptimizeHuffman)
    return true;

  if (tags) {
    const struct JPG_TagItem *alphatags = (const struct JPG_TagItem *)tags->GetTagPtr(JPGTAG_ALPHA_TAGLIST);
    
    if (tags->GetTagData(JPGTAG_IMAGE_FRAMETYPE) & JPGFLAG_OPTIMIZE_HUFFMAN)
      return true;

    if (tags->GetTagData(JPGTAG_RESIDUAL_FRAMETYPE) & JPGFLAG_OPTIMIZE_HUFFMAN)
      return true;

    if (alphatags) {
      if (alphatags->GetTagData(JPGTAG_IMAGE_FRAMETYPE) & JPGFLAG_OPTIMIZE_HUFFMAN)
        return true;

      if (alphatags->GetTagData(JPGTAG_RESIDUAL_FRAMETYPE) & JPGFLAG_OPTIMIZE_HUFFMAN)
        return true;
    }
  }

  return false;
}
///

/// JPEG::InternalProvideImage
// Forward transform an image, push it into the encoder - this is the internal
// version that generates exceptions.
void JPEG::InternalProvideImage(struct JPG_TagItem *tags)
{
  class BitMapHook bmh(tags);
  struct RectangleRequest rr;
  bool loop = tags->GetTagData(JPGTAG_ENCODER_LOOP_ON_INCOMPLETE)?true:false;

  if (m_bDecoding)
    JPG_THROW(OBJECT_EXISTS,"JPEG::InternalProvideImage","Decoding is active, cannot provide image data");

  if (m_pDecoder) {
    delete m_pDecoder;m_pDecoder = NULL;

    delete m_pImage;m_pImage = NULL;

    delete m_pIOStream;m_pIOStream = NULL;

    m_pFrame             = NULL;
    m_pScan              = NULL;
    m_bRow               = false;
    m_bDecoding          = false;
    m_bEncoding          = false;
    m_bHeaderWritten     = false;
    m_bOptimized         = false;
    m_bOptimizeHuffman   = false;
    m_bOptimizeQuantizer = false;
  }

  if (m_pImage == NULL) {
    if (m_pEncoder == NULL) {
      m_pEncoder  = new(m_pEnviron) class Encoder(m_pEnviron);
      m_bEncoding = true;
    }
    m_bOptimizeHuffman   = RequiresTwoPassEncoding(tags);
    m_bOptimizeQuantizer = tags->GetTagData(JPGTAG_OPTIMIZE_QUANTIZER,false)?true:false;
    m_pImage             = m_pEncoder->CreateImage(tags);
  }
  
  do {
    rr.ParseTags(tags,m_pImage);
    m_pImage->EncodeRegion(&bmh,&rr);
  } while(!m_pImage->isImageComplete() && loop);
  
  tags->SetTagData(JPGTAG_ENCODER_IMAGE_COMPLETE,m_pImage->isImageComplete());
}
///

/// JPEG::GetInformation
// Request information from the JPEG object.
JPG_LONG JPEG::GetInformation(struct JPG_TagItem *tags)
{ 
  volatile JPG_LONG ret = JPG_TRUE;
 
  JPG_TRY {
    InternalGetInformation(tags);
  } JPG_CATCH {
    ret = JPG_FALSE;
  } JPG_ENDTRY;

  return ret;
}
///

/// JPEG::GetOutputInformation
// Return layout information about floating point and conversion from the specs
// and insert it into the given tag list.
void JPEG::GetOutputInformation(class MergingSpecBox *specs,struct JPG_TagItem *tags) const
{
  bool isfloat = false;
  bool usesoc  = false;
  
  if (specs) {
    if (specs->usesOutputConversion()) {
      isfloat = true;
      usesoc  = true;
    } else if (specs->usesClipping()) {
      isfloat = false;
      usesoc  = false;
    } else if (specs->isLossless()) {
      isfloat = false;
      usesoc  = false;
    } else {
      isfloat = true;
      usesoc  = false;
    }
  }

  tags->SetTagData(JPGTAG_IMAGE_IS_FLOAT,isfloat);
  tags->SetTagData(JPGTAG_IMAGE_OUTPUT_CONVERSION,usesoc);
}
///

/// JPEG::InternalGetInformation
// Request information from the JPEG object - the internal version that creates exceptions.
void JPEG::InternalGetInformation(struct JPG_TagItem *tags)
{ 
  class Tables *tables;
  struct JPG_TagItem *alphatag  = tags->FindTagItem(JPGTAG_ALPHA_MODE);
  struct JPG_TagItem *alphalist = tags->FindTagItem(JPGTAG_ALPHA_TAGLIST);

  if (m_pImage == NULL)
    JPG_THROW(OBJECT_DOESNT_EXIST,"JPEG::InternalGetInformation","no image loaded to request information from");

  assert(m_pImage);

  //
  // Currently, that's all. More to come later.
  tags->SetTagData(JPGTAG_IMAGE_WIDTH ,m_pImage->WidthOf());
  tags->SetTagData(JPGTAG_IMAGE_HEIGHT,m_pImage->HeightOf());
  tags->SetTagData(JPGTAG_IMAGE_DEPTH ,m_pImage->DepthOf());
  tags->SetTagData(JPGTAG_IMAGE_PRECISION,m_pImage->PrecisionOf());
  tables = m_pImage->TablesOf();
  if (tables) {
    class MergingSpecBox *specs = tables->ResidualSpecsOf();
    class MergingSpecBox *alpha = tables->AlphaSpecsOf();
    class Image *alphachannel   = m_pImage->AlphaChannelOf();
    ULONG tablesz               = tags->GetTagData(JPGTAG_IMAGE_SUBLENGTH);
    UBYTE *subxtable            = NULL;
    UBYTE *subytable            = NULL;

    if (tablesz) {
      UWORD c,depth = m_pImage->DepthOf();
      subxtable = (UBYTE *)tags->GetTagPtr(JPGTAG_IMAGE_SUBX);
      subytable = (UBYTE *)tags->GetTagPtr(JPGTAG_IMAGE_SUBY);
      if (subxtable)
        memset(subxtable,0,tablesz);
      if (subytable)
        memset(subytable,0,tablesz);
      //
      // Request now the subsampling parameters of the components in the image.
      if (depth > tablesz)
        depth = tablesz;
      for(c = 0;c < depth;c++) {
        class Frame *frame    = m_pImage->FirstFrameOf();
        if (frame) {
          class Component *comp = frame->ComponentOf(c);
          if (comp) {
            if (subxtable)
              subxtable[c] = comp->SubXOf();
            if (subytable)
              subytable[c] = comp->SubYOf();
          }
        }
      }
    }

    GetOutputInformation(specs,tags);

    
    
    if (alpha && alphachannel) {
      ULONG r,g,b;
      BYTE mode = alpha->AlphaModeOf(r,g,b);
      
      if (mode >= 0) {
        if (alphatag)
          alphatag->ti_Data.ti_lData = mode;
        tags->SetTagData(JPGTAG_ALPHA_MATTE(0),r);
        tags->SetTagData(JPGTAG_ALPHA_MATTE(1),g);
        tags->SetTagData(JPGTAG_ALPHA_MATTE(2),b);
        
        if (alphalist) {
          alphalist = (struct JPG_TagItem *)(alphalist->ti_Data.ti_pPtr);
          alphalist->SetTagData(JPGTAG_IMAGE_PRECISION,alphachannel->PrecisionOf());
          GetOutputInformation(alpha,alphalist);
        }
      } else {
        if (alphatag) 
          alphatag->ti_Tag  = JPGTAG_TAG_IGNORE;
        if (alphalist)
          alphalist->ti_Tag = JPGTAG_TAG_IGNORE;
      }
    } else {
      if (alphatag)
        alphatag->ti_Tag  = JPGTAG_TAG_IGNORE;
      if (alphalist)
        alphalist->ti_Tag = JPGTAG_TAG_IGNORE;
    }
  } else {
    JPG_THROW(OBJECT_DOESNT_EXIST,"JPEG::InternalGetInformation","no image created or loaded");
  }
}
///

/// JPEG::LastError
// Return the last exception - the error code, if present - in
// the primary result code, a pointer to the error string in the
// argument. If no error happened, return 0. For finer error handling,
// define an exception hook upon creation of the library.
JPG_LONG JPEG::LastError(const char *&error)
{
  return m_pEnviron->LastException(error);
}
///

/// JPEG::LastWarning
// Return the last warning - the error code, if present - in the
// primary result code and the warning message in the argument. Returns
// 0 if no warning happened. Define a warning hook for finer warning
// control.
JPG_LONG JPEG::LastWarning(const char *&warning)
{
  return m_pEnviron->LastWarning(warning);
}
///