forked from DraconPern/fmjpeg2koj
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdjcodecd.cc
948 lines (806 loc) · 30.6 KB
/
djcodecd.cc
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
/*
*
* Copyright 2015-2017 Ing-Long Eric Kuo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* Module: fmjpeg2k
*
* Author: Ing-Long Eric Kuo
*
* Purpose: codec classes for JPEG-2000 decoders.
*
*/
#include "dcmtk/config/osconfig.h"
#include "fmjpeg2k/djcodecd.h"
#include "dcmtk/ofstd/ofstream.h" /* for ofstream */
#include "dcmtk/ofstd/ofcast.h" /* for casts */
#include "dcmtk/ofstd/offile.h" /* for class OFFile */
#include "dcmtk/ofstd/ofstd.h" /* for class OFStandard */
#include "dcmtk/dcmdata/dcdatset.h" /* for class DcmDataset */
#include "dcmtk/dcmdata/dcdeftag.h" /* for tag constants */
#include "dcmtk/dcmdata/dcpixseq.h" /* for class DcmPixelSequence */
#include "dcmtk/dcmdata/dcpxitem.h" /* for class DcmPixelItem */
#include "dcmtk/dcmdata/dcvrpobw.h" /* for class DcmPolymorphOBOW */
#include "dcmtk/dcmdata/dcswap.h" /* for swapIfNecessary() */
#include "dcmtk/dcmdata/dcuid.h" /* for dcmGenerateUniqueIdentifer()*/
#include "fmjpeg2k/djcparam.h" /* for class DJP2KCodecParameter */
#include "fmjpeg2k/djerror.h" /* for private class DJLSError */
// JPEG-2000 library (OpenJPEG) includes
#include "openjpeg.h"
#include "fmjpeg2k/memory_file.h"
DJPEG2KDecoderBase::DJPEG2KDecoderBase()
: DcmCodec()
{
}
DJPEG2KDecoderBase::~DJPEG2KDecoderBase()
{
}
OFBool DJPEG2KDecoderBase::canChangeCoding(
const E_TransferSyntax oldRepType,
const E_TransferSyntax newRepType) const
{
// this codec only handles conversion from JPEG-2000 to uncompressed.
DcmXfer newRep(newRepType);
if (newRep.isNotEncapsulated() &&
((oldRepType == EXS_JPEG2000LosslessOnly)||(oldRepType == EXS_JPEG2000)||
(oldRepType == EXS_JPEG2000MulticomponentLosslessOnly)||(oldRepType == EXS_JPEG2000Multicomponent)))
return OFTrue;
return OFFalse;
}
OFCondition DJPEG2KDecoderBase::decode(
const DcmRepresentationParameter * /* fromRepParam */,
DcmPixelSequence * pixSeq,
DcmPolymorphOBOW& uncompressedPixelData,
const DcmCodecParameter * cp,
const DcmStack& objStack) const
{
// retrieve pointer to dataset from parameter stack
DcmStack localStack(objStack);
(void)localStack.pop(); // pop pixel data element from stack
DcmObject *dobject = localStack.pop(); // this is the item in which the pixel data is located
if ((!dobject)||((dobject->ident()!= EVR_dataset) && (dobject->ident()!= EVR_item))) return EC_InvalidTag;
DcmItem *dataset = OFstatic_cast(DcmItem *, dobject);
OFBool numberOfFramesPresent = OFFalse;
// determine properties of uncompressed dataset
Uint16 imageSamplesPerPixel = 0;
if (dataset->findAndGetUint16(DCM_SamplesPerPixel, imageSamplesPerPixel).bad()) return EC_TagNotFound;
// we only handle one or three samples per pixel
if ((imageSamplesPerPixel != 3) && (imageSamplesPerPixel != 1)) return EC_InvalidTag;
Uint16 imageRows = 0;
if (dataset->findAndGetUint16(DCM_Rows, imageRows).bad()) return EC_TagNotFound;
if (imageRows < 1) return EC_InvalidTag;
Uint16 imageColumns = 0;
if (dataset->findAndGetUint16(DCM_Columns, imageColumns).bad()) return EC_TagNotFound;
if (imageColumns < 1) return EC_InvalidTag;
// number of frames is an optional attribute - we don't mind if it isn't present.
Sint32 imageFrames = 0;
if (dataset->findAndGetSint32(DCM_NumberOfFrames, imageFrames).good()) numberOfFramesPresent = OFTrue;
if (imageFrames >= OFstatic_cast(Sint32, pixSeq->card()))
imageFrames = pixSeq->card() - 1; // limit number of frames to number of pixel items - 1
if (imageFrames < 1)
imageFrames = 1; // default in case the number of frames attribute is absent or contains garbage
Uint16 imageBitsStored = 0;
if (dataset->findAndGetUint16(DCM_BitsStored, imageBitsStored).bad()) return EC_TagNotFound;
Uint16 imageBitsAllocated = 0;
if (dataset->findAndGetUint16(DCM_BitsAllocated, imageBitsAllocated).bad()) return EC_TagNotFound;
Uint16 imageHighBit = 0;
if (dataset->findAndGetUint16(DCM_HighBit, imageHighBit).bad()) return EC_TagNotFound;
//we only support up to 16 bits per sample
if ((imageBitsStored < 1) || (imageBitsStored > 16)) return EC_J2KUnsupportedBitDepth;
// determine the number of bytes per sample (bits allocated) for the de-compressed object.
Uint16 bytesPerSample = 1;
if (imageBitsStored > 8) bytesPerSample = 2;
else if (imageBitsAllocated > 8) bytesPerSample = 2;
// compute size of uncompressed frame, in bytes
Uint32 frameSize = bytesPerSample * imageRows * imageColumns * imageSamplesPerPixel;
// compute size of pixel data attribute, in bytes
Uint32 totalSize = frameSize * imageFrames;
if (totalSize & 1) totalSize++; // align on 16-bit word boundary
// assume we can cast the codec parameter to what we need
const DJPEG2KCodecParameter *djcp = OFreinterpret_cast(const DJPEG2KCodecParameter *, cp);
// determine planar configuration for uncompressed data
OFString imageSopClass;
OFString imagePhotometricInterpretation;
dataset->findAndGetOFString(DCM_SOPClassUID, imageSopClass);
dataset->findAndGetOFString(DCM_PhotometricInterpretation, imagePhotometricInterpretation);
// allocate space for uncompressed pixel data element
Uint16 *pixeldata16 = NULL;
OFCondition result = uncompressedPixelData.createUint16Array(totalSize/sizeof(Uint16), pixeldata16);
if (result.bad()) return result;
Uint8 *pixeldata8 = OFreinterpret_cast(Uint8 *, pixeldata16);
Sint32 currentFrame = 0;
Uint32 currentItem = 1; // item 0 contains the offset table
OFBool done = OFFalse;
while (result.good() && !done)
{
FMJPEG2K_DEBUG("JPEG-2000 decoder processes frame " << (currentFrame+1));
result = decodeFrame(pixSeq, djcp, dataset, currentFrame, currentItem, pixeldata8, frameSize,
imageFrames, imageColumns, imageRows, imageSamplesPerPixel, bytesPerSample);
if (result.good())
{
// increment frame number, check if we're finished
if (++currentFrame == imageFrames) done = OFTrue;
pixeldata8 += frameSize;
}
}
// Number of Frames might have changed in case the previous value was wrong
if (result.good() && (numberOfFramesPresent || (imageFrames > 1)))
{
char numBuf[20];
sprintf(numBuf, "%ld", OFstatic_cast(long, imageFrames));
result = ((DcmItem *)dataset)->putAndInsertString(DCM_NumberOfFrames, numBuf);
}
if (result.good())
{
// the following operations do not affect the Image Pixel Module
// but other modules such as SOP Common. We only perform these
// changes if we're on the main level of the dataset,
// which should always identify itself as dataset, not as item.
if ((dataset->ident() == EVR_dataset) && (djcp->getUIDCreation() == EJ2KUC_always))
{
// create new SOP instance UID
result = DcmCodec::newInstance((DcmItem *)dataset, NULL, NULL, NULL);
}
}
return result;
}
OFCondition DJPEG2KDecoderBase::decode(
const DcmRepresentationParameter * fromRepParam,
DcmPixelSequence * pixSeq,
DcmPolymorphOBOW& uncompressedPixelData,
const DcmCodecParameter * cp,
const DcmStack& objStack,
OFBool& removeOldRep) const
{
// removeOldRep is left as it is, pixel data in original DICOM dataset is not modified
return decode(fromRepParam, pixSeq, uncompressedPixelData, cp, objStack);
}
OFCondition DJPEG2KDecoderBase::decodeFrame(
const DcmRepresentationParameter * /* fromParam */,
DcmPixelSequence *fromPixSeq,
const DcmCodecParameter *cp,
DcmItem *dataset,
Uint32 frameNo,
Uint32& currentItem,
void * buffer,
Uint32 bufSize,
OFString& decompressedColorModel) const
{
OFCondition result = EC_Normal;
// assume we can cast the codec parameter to what we need
const DJPEG2KCodecParameter *djcp = OFreinterpret_cast(const DJPEG2KCodecParameter *, cp);
// determine properties of uncompressed dataset
Uint16 imageSamplesPerPixel = 0;
if (dataset->findAndGetUint16(DCM_SamplesPerPixel, imageSamplesPerPixel).bad()) return EC_TagNotFound;
// we only handle one or three samples per pixel
if ((imageSamplesPerPixel != 3) && (imageSamplesPerPixel != 1)) return EC_InvalidTag;
Uint16 imageRows = 0;
if (dataset->findAndGetUint16(DCM_Rows, imageRows).bad()) return EC_TagNotFound;
if (imageRows < 1) return EC_InvalidTag;
Uint16 imageColumns = 0;
if (dataset->findAndGetUint16(DCM_Columns, imageColumns).bad()) return EC_TagNotFound;
if (imageColumns < 1) return EC_InvalidTag;
Uint16 imageBitsStored = 0;
if (dataset->findAndGetUint16(DCM_BitsStored, imageBitsStored).bad()) return EC_TagNotFound;
Uint16 imageBitsAllocated = 0;
if (dataset->findAndGetUint16(DCM_BitsAllocated, imageBitsAllocated).bad()) return EC_TagNotFound;
//we only support up to 16 bits per sample
if ((imageBitsStored < 1) || (imageBitsStored > 16)) return EC_J2KUnsupportedBitDepth;
// determine the number of bytes per sample (bits allocated) for the de-compressed object.
Uint16 bytesPerSample = 1;
if (imageBitsStored > 8) bytesPerSample = 2;
else if (imageBitsAllocated > 8) bytesPerSample = 2;
// number of frames is an optional attribute - we don't mind if it isn't present.
Sint32 imageFrames = 0;
dataset->findAndGetSint32(DCM_NumberOfFrames, imageFrames).good();
if (imageFrames >= OFstatic_cast(Sint32, fromPixSeq->card()))
imageFrames = fromPixSeq->card() - 1; // limit number of frames to number of pixel items - 1
if (imageFrames < 1)
imageFrames = 1; // default in case the number of frames attribute is absent or contains garbage
// if the user has provided this information, we trust him.
// If the user has passed a zero, try to find out ourselves.
if (currentItem == 0)
{
result = determineStartFragment(frameNo, imageFrames, fromPixSeq, currentItem);
}
if (result.good())
{
// We got all the data we need from the dataset, let's start decoding
FMJPEG2K_DEBUG("Starting to decode frame " << frameNo << " with fragment " << currentItem);
result = decodeFrame(fromPixSeq, djcp, dataset, frameNo, currentItem, buffer, bufSize,
imageFrames, imageColumns, imageRows, imageSamplesPerPixel, bytesPerSample);
}
if (result.good())
{
// retrieve color model from given dataset
result = dataset->findAndGetOFString(DCM_PhotometricInterpretation, decompressedColorModel);
}
return result;
}
OFCondition copyUint32ToUint8(
opj_image_t * image,
Uint8 *imageFrame,
Uint16 columns,
Uint16 rows);
OFCondition copyUint32ToUint16(
opj_image_t * image,
Uint16 *imageFrame,
Uint16 columns,
Uint16 rows);
OFCondition copyRGBUint8ToRGBUint8(
opj_image_t * image,
Uint8 *imageFrame,
Uint16 columns,
Uint16 rows);
OFCondition copyRGBUint8ToRGBUint8Planar(
opj_image_t * image,
Uint8 *imageFrame,
Uint16 columns,
Uint16 rows);
OFCondition DJPEG2KDecoderBase::decodeFrame(
DcmPixelSequence * fromPixSeq,
const DJPEG2KCodecParameter *cp,
DcmItem *dataset,
Uint32 frameNo,
Uint32& currentItem,
void * buffer,
Uint32 bufSize,
Sint32 imageFrames,
Uint16 imageColumns,
Uint16 imageRows,
Uint16 imageSamplesPerPixel,
Uint16 bytesPerSample)
{
DcmPixelItem *pixItem = NULL;
Uint8 * jlsData = NULL;
Uint8 * jlsFragmentData = NULL;
Uint32 fragmentLength = 0;
size_t compressedSize = 0;
Uint32 fragmentsForThisFrame = 0;
OFCondition result = EC_Normal;
OFBool ignoreOffsetTable = cp->ignoreOffsetTable();
// compute the number of JPEG-LS fragments we need in order to decode the next frame
fragmentsForThisFrame = computeNumberOfFragments(imageFrames, frameNo, currentItem, ignoreOffsetTable, fromPixSeq);
if (fragmentsForThisFrame == 0) result = EC_J2KCannotComputeNumberOfFragments;
// determine planar configuration for uncompressed data
OFString imageSopClass;
OFString imagePhotometricInterpretation;
dataset->findAndGetOFString(DCM_SOPClassUID, imageSopClass);
dataset->findAndGetOFString(DCM_PhotometricInterpretation, imagePhotometricInterpretation);
Uint16 imagePlanarConfiguration = 0; // 0 is color-by-pixel, 1 is color-by-plane
if (imageSamplesPerPixel > 1)
{
switch (cp->getPlanarConfiguration())
{
case EJ2KPC_restore:
// get planar configuration from dataset
imagePlanarConfiguration = 2; // invalid value
dataset->findAndGetUint16(DCM_PlanarConfiguration, imagePlanarConfiguration);
// determine auto default if not found or invalid
if (imagePlanarConfiguration > 1)
imagePlanarConfiguration = determinePlanarConfiguration(imageSopClass, imagePhotometricInterpretation);
break;
case EJ2KPC_auto:
imagePlanarConfiguration = determinePlanarConfiguration(imageSopClass, imagePhotometricInterpretation);
break;
case EJ2KPC_colorByPixel:
imagePlanarConfiguration = 0;
break;
case EJ2KPC_colorByPlane:
imagePlanarConfiguration = 1;
break;
}
}
// get the size of all the fragments
if (result.good())
{
// Don't modify the original values for now
Uint32 fragmentsForThisFrame2 = fragmentsForThisFrame;
Uint32 currentItem2 = currentItem;
while (result.good() && fragmentsForThisFrame2--)
{
result = fromPixSeq->getItem(pixItem, currentItem2++);
if (result.good() && pixItem)
{
fragmentLength = pixItem->getLength();
if (result.good())
compressedSize += fragmentLength;
}
} /* while */
}
// get the compressed data
if (result.good())
{
Uint32 offset = 0;
jlsData = new Uint8[compressedSize];
while (result.good() && fragmentsForThisFrame--)
{
result = fromPixSeq->getItem(pixItem, currentItem++);
if (result.good() && pixItem)
{
fragmentLength = pixItem->getLength();
result = pixItem->getUint8Array(jlsFragmentData);
if (result.good() && jlsFragmentData)
{
memcpy(&jlsData[offset], jlsFragmentData, fragmentLength);
offset += fragmentLength;
}
}
} /* while */
}
if (result.good())
{
// see if the last byte is a padding, otherwise, it should be 0xd9
if(jlsData[compressedSize - 1] == 0)
compressedSize--;
DecodeData mysrc((unsigned char*)jlsData, compressedSize);
// start of open jpeg stuff
opj_dparameters_t parameters;
opj_codec_t* l_codec = NULL;
opj_stream_t *l_stream = NULL;
opj_image_t *image = NULL;
l_stream = opj_stream_create_memory_stream(&mysrc, OPJ_J2K_STREAM_CHUNK_SIZE, true);
// figure out codec
#define JP2_RFC3745_MAGIC "\x00\x00\x00\x0c\x6a\x50\x20\x20\x0d\x0a\x87\x0a"
#define JP2_MAGIC "\x0d\x0a\x87\x0a"
/* position 45: "\xff\x52" */
#define J2K_CODESTREAM_MAGIC "\xff\x4f\xff\x51"
OPJ_CODEC_FORMAT format = OPJ_CODEC_UNKNOWN;
if(memcmp(jlsData, JP2_RFC3745_MAGIC, 12) == 0 || memcmp(jlsData, JP2_MAGIC, 4) == 0)
format = OPJ_CODEC_JP2;
else if (memcmp(jlsData, J2K_CODESTREAM_MAGIC, 4) == 0)
format = OPJ_CODEC_J2K;
else
format = OPJ_CODEC_J2K;
l_codec = opj_create_decompress(format);
opj_set_info_handler(l_codec, msg_callback, NULL);
opj_set_warning_handler(l_codec, msg_callback, NULL);
opj_set_error_handler(l_codec, msg_callback, NULL);
opj_set_default_decoder_parameters(¶meters);
if(!opj_setup_decoder(l_codec, ¶meters))
{
opj_stream_destroy(l_stream); l_stream = NULL;
opj_destroy_codec(l_codec); l_codec = NULL;
result = EC_CorruptedData;
}
if(result.good() && !opj_read_header(l_stream, l_codec, &image))
{
opj_stream_destroy(l_stream); l_stream = NULL;
opj_destroy_codec(l_codec); l_codec = NULL;
opj_image_destroy(image); image = NULL;
result = EC_CorruptedData;
}
if (result.good())
{
if (image->x1 != imageColumns) result = EC_J2KImageDataMismatch;
else if (image->y1 != imageRows) result = EC_J2KImageDataMismatch;
else if (image->numcomps != imageSamplesPerPixel) result = EC_J2KImageDataMismatch;
//else if ((bytesPerSample == 1) && (image->bitspersample > 8)) result = EC_J2KImageDataMismatch;
//else if ((bytesPerSample == 2) && (image->bitspersample <= 8)) result = EC_J2KImageDataMismatch;
}
if (!result.good())
{
delete[] jlsData;
}
else
{
if (!(opj_decode(l_codec, l_stream, image) && opj_end_decompress(l_codec, l_stream))) {
opj_stream_destroy(l_stream); l_stream = NULL;
opj_destroy_codec(l_codec); l_codec = NULL;
opj_image_destroy(image); image = NULL;
result = EC_CorruptedData;
}
if(result.good())
{
// copy the image depending on planer configuration and bits
if(image->numcomps == 1) // Greyscale
{
if(image->comps[0].prec <= 8)
copyUint32ToUint8(image, OFreinterpret_cast(Uint8*, buffer), imageColumns, imageRows);
if(image->comps[0].prec > 8)
copyUint32ToUint16(image, OFreinterpret_cast(Uint16*, buffer), imageColumns, imageRows);
}
else if(image->numcomps == 3)
{
if(imagePlanarConfiguration == 0)
{
copyRGBUint8ToRGBUint8(image, OFreinterpret_cast(Uint8*, buffer), imageColumns, imageRows);
}
else if(imagePlanarConfiguration == 1)
{
copyRGBUint8ToRGBUint8Planar(image, OFreinterpret_cast(Uint8*, buffer), imageColumns, imageRows);
}
}
}
opj_stream_destroy(l_stream); l_stream = NULL;
opj_destroy_codec(l_codec); l_codec = NULL;
opj_image_destroy(image); image = NULL;
delete[] jlsData;
if (result.good())
{
// decompression is complete, finally adjust byte order if necessary
if (bytesPerSample == 1) // we're writing bytes into words
{
result = swapIfNecessary(gLocalByteOrder, EBO_LittleEndian, buffer,
bufSize, sizeof(Uint16));
}
}
}
}
return result;
}
OFCondition DJPEG2KDecoderBase::encode(
const Uint16 * /* pixelData */,
const Uint32 /* length */,
const DcmRepresentationParameter * /* toRepParam */,
DcmPixelSequence * & /* pixSeq */,
const DcmCodecParameter * /* cp */,
DcmStack & /* objStack */) const
{
// we are a decoder only
return EC_IllegalCall;
}
OFCondition DJPEG2KDecoderBase::encode(
const Uint16 * pixelData,
const Uint32 length,
const DcmRepresentationParameter * toRepParam,
DcmPixelSequence * & pixSeq,
const DcmCodecParameter *cp,
DcmStack & objStack,
OFBool& removeOldRep) const
{
return EC_IllegalCall;
}
OFCondition DJPEG2KDecoderBase::encode(
const E_TransferSyntax /* fromRepType */,
const DcmRepresentationParameter * /* fromRepParam */,
DcmPixelSequence * /* fromPixSeq */,
const DcmRepresentationParameter * /* toRepParam */,
DcmPixelSequence * & /* toPixSeq */,
const DcmCodecParameter * /* cp */,
DcmStack & /* objStack */) const
{
// we don't support re-coding for now.
return EC_IllegalCall;
}
OFCondition DJPEG2KDecoderBase::encode(
const E_TransferSyntax fromRepType,
const DcmRepresentationParameter * fromRepParam,
DcmPixelSequence * fromPixSeq,
const DcmRepresentationParameter * toRepParam,
DcmPixelSequence * & toPixSeq,
const DcmCodecParameter * cp,
DcmStack & objStack,
OFBool& removeOldRep) const
{
return EC_IllegalCall;
}
OFCondition DJPEG2KDecoderBase::determineDecompressedColorModel(
const DcmRepresentationParameter * /* fromParam */,
DcmPixelSequence * /* fromPixSeq */,
const DcmCodecParameter * /* cp */,
DcmItem * dataset,
OFString & decompressedColorModel) const
{
OFCondition result = EC_IllegalParameter;
if (dataset != NULL)
{
// retrieve color model from given dataset
result = dataset->findAndGetOFString(DCM_PhotometricInterpretation, decompressedColorModel);
}
return result;
}
Uint16 DJPEG2KDecoderBase::determinePlanarConfiguration(
const OFString& sopClassUID,
const OFString& photometricInterpretation)
{
// Hardcopy Color Image always requires color-by-plane
if (sopClassUID == UID_RETIRED_HardcopyColorImageStorage) return 1;
// The 1996 Ultrasound Image IODs require color-by-plane if color model is YBR_FULL.
if (photometricInterpretation == "YBR_FULL")
{
if ((sopClassUID == UID_UltrasoundMultiframeImageStorage)
||(sopClassUID == UID_UltrasoundImageStorage)) return 1;
}
// default for all other cases
return 0;
}
Uint32 DJPEG2KDecoderBase::computeNumberOfFragments(
Sint32 numberOfFrames,
Uint32 currentFrame,
Uint32 startItem,
OFBool ignoreOffsetTable,
DcmPixelSequence * pixSeq)
{
unsigned long numItems = pixSeq->card();
DcmPixelItem *pixItem = NULL;
// We first check the simple cases, that is, a single-frame image,
// the last frame of a multi-frame image and the standard case where we do have
// a single fragment per frame.
if ((numberOfFrames <= 1) || (currentFrame + 1 == OFstatic_cast(Uint32, numberOfFrames)))
{
// single-frame image or last frame. All remaining fragments belong to this frame
return (numItems - startItem);
}
if (OFstatic_cast(Uint32, numberOfFrames + 1) == numItems)
{
// multi-frame image with one fragment per frame
return 1;
}
OFCondition result = EC_Normal;
if (! ignoreOffsetTable)
{
// We do have a multi-frame image with multiple fragments per frame, and we are
// not working on the last frame. Let's check the offset table if present.
result = pixSeq->getItem(pixItem, 0);
if (result.good() && pixItem)
{
Uint32 offsetTableLength = pixItem->getLength();
if (offsetTableLength == (OFstatic_cast(Uint32, numberOfFrames) * 4))
{
// offset table is non-empty and contains one entry per frame
Uint8 *offsetData = NULL;
result = pixItem->getUint8Array(offsetData);
if (result.good() && offsetData)
{
// now we can access the offset table
Uint32 *offsetData32 = OFreinterpret_cast(Uint32 *, offsetData);
// extract the offset for the NEXT frame. This offset is guaranteed to exist
// because the "last frame/single frame" case is handled above.
Uint32 offset = offsetData32[currentFrame+1];
// convert to local endian byte order (always little endian in file)
swapIfNecessary(gLocalByteOrder, EBO_LittleEndian, &offset, sizeof(Uint32), sizeof(Uint32));
// determine index of start fragment for next frame
Uint32 byteCount = 0;
Uint32 fragmentIndex = 1;
while ((byteCount < offset) && (fragmentIndex < numItems))
{
pixItem = NULL;
result = pixSeq->getItem(pixItem, fragmentIndex++);
if (result.good() && pixItem)
{
byteCount += pixItem->getLength() + 8; // add 8 bytes for item tag and length
if ((byteCount == offset) && (fragmentIndex > startItem))
{
// bingo, we have found the offset for the next frame
return fragmentIndex - startItem;
}
}
else break; /* something went wrong, break out of while loop */
} /* while */
}
}
}
}
// So we have a multi-frame image with multiple fragments per frame and the
// offset table is empty or wrong. Our last chance is to peek into the JPEG-2000
// bistream and identify the start of the next frame.
Uint32 nextItem = startItem;
Uint8 *fragmentData = NULL;
while (++nextItem < numItems)
{
pixItem = NULL;
result = pixSeq->getItem(pixItem, nextItem);
if (result.good() && pixItem)
{
fragmentData = NULL;
result = pixItem->getUint8Array(fragmentData);
if (result.good() && fragmentData && (pixItem->getLength() > 3))
{
if (isJPEGLSStartOfImage(fragmentData))
{
// found a JPEG-2000 SOI marker. Assume that this is the start of the next frame.
return (nextItem - startItem);
}
}
else break; /* something went wrong, break out of while loop */
}
else break; /* something went wrong, break out of while loop */
}
// We're bust. No way to determine the number of fragments per frame.
return 0;
}
OFBool DJPEG2KDecoderBase::isJPEGLSStartOfImage(Uint8 *fragmentData)
{
// A valid JPEG-2000 bitstream will always start with an SOI marker FFD8, followed
// by either an SOF55 (FFF7), COM (FFFE) or APPn (FFE0-FFEF) marker.
if ((*fragmentData++) != 0xFF) return OFFalse;
if ((*fragmentData++) != 0xD8) return OFFalse;
if ((*fragmentData++) != 0xFF) return OFFalse;
if ((*fragmentData == 0xF7)||(*fragmentData == 0xFE)||((*fragmentData & 0xF0) == 0xE0))
{
return OFTrue;
}
return OFFalse;
}
OFCondition DJPEG2KDecoderBase::createPlanarConfiguration1Byte(
Uint8 *imageFrame,
Uint16 columns,
Uint16 rows)
{
if (imageFrame == NULL) return EC_IllegalCall;
unsigned long numPixels = columns * rows;
if (numPixels == 0) return EC_IllegalCall;
Uint8 *buf = new Uint8[3*numPixels + 3];
if (buf)
{
memcpy(buf, imageFrame, (size_t)(3*numPixels));
Uint8 *s = buf; // source
Uint8 *r = imageFrame; // red plane
Uint8 *g = imageFrame + numPixels; // green plane
Uint8 *b = imageFrame + (2*numPixels); // blue plane
for (unsigned long i=numPixels; i; i--)
{
*r++ = *s++;
*g++ = *s++;
*b++ = *s++;
}
delete[] buf;
} else return EC_MemoryExhausted;
return EC_Normal;
}
OFCondition DJPEG2KDecoderBase::createPlanarConfiguration1Word(
Uint16 *imageFrame,
Uint16 columns,
Uint16 rows)
{
if (imageFrame == NULL) return EC_IllegalCall;
unsigned long numPixels = columns * rows;
if (numPixels == 0) return EC_IllegalCall;
Uint16 *buf = new Uint16[3*numPixels + 3];
if (buf)
{
memcpy(buf, imageFrame, (size_t)(3*numPixels*sizeof(Uint16)));
Uint16 *s = buf; // source
Uint16 *r = imageFrame; // red plane
Uint16 *g = imageFrame + numPixels; // green plane
Uint16 *b = imageFrame + (2*numPixels); // blue plane
for (unsigned long i=numPixels; i; i--)
{
*r++ = *s++;
*g++ = *s++;
*b++ = *s++;
}
delete[] buf;
} else return EC_MemoryExhausted;
return EC_Normal;
}
OFCondition DJPEG2KDecoderBase::createPlanarConfiguration0Byte(
Uint8 *imageFrame,
Uint16 columns,
Uint16 rows)
{
if (imageFrame == NULL) return EC_IllegalCall;
unsigned long numPixels = columns * rows;
if (numPixels == 0) return EC_IllegalCall;
Uint8 *buf = new Uint8[3*numPixels + 3];
if (buf)
{
memcpy(buf, imageFrame, (size_t)(3*numPixels));
Uint8 *t = imageFrame; // target
Uint8 *r = buf; // red plane
Uint8 *g = buf + numPixels; // green plane
Uint8 *b = buf + (2*numPixels); // blue plane
for (unsigned long i=numPixels; i; i--)
{
*t++ = *r++;
*t++ = *g++;
*t++ = *b++;
}
delete[] buf;
} else return EC_MemoryExhausted;
return EC_Normal;
}
OFCondition DJPEG2KDecoderBase::createPlanarConfiguration0Word(
Uint16 *imageFrame,
Uint16 columns,
Uint16 rows)
{
if (imageFrame == NULL) return EC_IllegalCall;
unsigned long numPixels = columns * rows;
if (numPixels == 0) return EC_IllegalCall;
Uint16 *buf = new Uint16[3*numPixels + 3];
if (buf)
{
memcpy(buf, imageFrame, (size_t)(3*numPixels*sizeof(Uint16)));
Uint16 *t = imageFrame; // target
Uint16 *r = buf; // red plane
Uint16 *g = buf + numPixels; // green plane
Uint16 *b = buf + (2*numPixels); // blue plane
for (unsigned long i=numPixels; i; i--)
{
*t++ = *r++;
*t++ = *g++;
*t++ = *b++;
}
delete[] buf;
} else return EC_MemoryExhausted;
return EC_Normal;
}
OFCondition copyUint32ToUint8(
opj_image_t * image,
Uint8 *imageFrame,
Uint16 columns,
Uint16 rows)
{
if (imageFrame == NULL) return EC_IllegalCall;
unsigned long numPixels = columns * rows;
if (numPixels == 0) return EC_IllegalCall;
Uint8 *t = imageFrame; // target
OPJ_INT32 *g = image->comps[0].data; // grey plane
for (unsigned long i=numPixels; i; i--)
{
*t++ = *g++;
}
return EC_Normal;
}
OFCondition copyUint32ToUint16(
opj_image_t * image,
Uint16 *imageFrame,
Uint16 columns,
Uint16 rows)
{
if (imageFrame == NULL) return EC_IllegalCall;
unsigned long numPixels = columns * rows;
if (numPixels == 0) return EC_IllegalCall;
Uint16 *t = imageFrame; // target
OPJ_INT32 *g = image->comps[0].data; // grey plane
for (unsigned long i=numPixels; i; i--)
{
*t++ = *g++;
}
return EC_Normal;
}
OFCondition copyRGBUint8ToRGBUint8(
opj_image_t * image,
Uint8 *imageFrame,
Uint16 columns,
Uint16 rows)
{
if (imageFrame == NULL) return EC_IllegalCall;
unsigned long numPixels = columns * rows;
if (numPixels == 0) return EC_IllegalCall;
Uint8 *t = imageFrame; // target
OPJ_INT32 *r = image->comps[0].data; // red plane
OPJ_INT32 *g = image->comps[1].data; // green plane
OPJ_INT32 *b = image->comps[2].data; // blue plane
for (unsigned long i=numPixels; i; i--)
{
*t++ = *r++;
*t++ = *g++;
*t++ = *b++;
}
return EC_Normal;
}
OFCondition copyRGBUint8ToRGBUint8Planar(
opj_image_t * image,
Uint8 *imageFrame,
Uint16 columns,
Uint16 rows)
{
if (imageFrame == NULL) return EC_IllegalCall;
unsigned long numPixels = columns * rows;
if (numPixels == 0) return EC_IllegalCall;
Uint8 *t = imageFrame; // target
for(unsigned long j=0; j<3; j++)
{
OPJ_INT32 *r = image->comps[j].data; // color plane
for (unsigned long i=numPixels; i; i--)
{
*t++ = *r++;
}
}
return EC_Normal;
}