forked from DraconPern/fmjpeg2koj
-
Notifications
You must be signed in to change notification settings - Fork 0
/
djcodece.cc
1361 lines (1171 loc) · 41.6 KB
/
djcodece.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
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
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
*
* 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: dcmjpeg2k
*
* Author: Ing-Long Eric Kuo
*
* Purpose: codec classes for JPEG 2000 encoders.
*
*/
#include "dcmtk/config/osconfig.h"
#include "fmjpeg2k/djcodece.h"
// ofstd includes
#include "dcmtk/ofstd/oflist.h"
#include "dcmtk/ofstd/ofstd.h"
#include "dcmtk/ofstd/ofstream.h"
#include "dcmtk/ofstd/offile.h" /* for class OFFile */
#include "dcmtk/ofstd/ofbmanip.h"
#include <cmath>
#include "dcmtk/ofstd/ofstdinc.h"
// dcmdata includes
#include "dcmtk/dcmdata/dcdatset.h" /* for class DcmDataset */
#include "dcmtk/dcmdata/dcdeftag.h" /* for tag constants */
#include "dcmtk/dcmdata/dcovlay.h" /* for class DcmOverlayData */
#include "dcmtk/dcmdata/dcpixseq.h" /* for class DcmPixelSequence */
#include "dcmtk/dcmdata/dcpxitem.h" /* for class DcmPixelItem */
#include "dcmtk/dcmdata/dcuid.h" /* for dcmGenerateUniqueIdentifer()*/
#include "dcmtk/dcmdata/dcvrcs.h" /* for class DcmCodeString */
#include "dcmtk/dcmdata/dcvrds.h" /* for class DcmDecimalString */
#include "dcmtk/dcmdata/dcvrlt.h" /* for class DcmLongText */
#include "dcmtk/dcmdata/dcvrst.h" /* for class DcmShortText */
#include "dcmtk/dcmdata/dcvrus.h" /* for class DcmUnsignedShort */
#include "dcmtk/dcmdata/dcswap.h" /* for swapIfNecessary */
// dcmjpls includes
#include "fmjpeg2k/djcparam.h" /* for class DJP2KCodecParameter */
#include "fmjpeg2k/djrparam.h" /* for class D2RepresentationParameter */
#include "fmjpeg2k/djerror.h" /* for private class DJLSError */
// dcmimgle includes
#include "dcmtk/dcmimgle/dcmimage.h" /* for class DicomImage */
// JPEG-2000 library (OpenJPEG) includes
#include "openjpeg.h"
#include "fmjpeg2k/memory_file.h"
BEGIN_EXTERN_C
#ifdef HAVE_FCNTL_H
#include <fcntl.h> /* for O_RDONLY */
#endif
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h> /* required for sys/stat.h */
#endif
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h> /* for stat, fstat */
#endif
END_EXTERN_C
E_TransferSyntax DJPEG2KLosslessEncoder::supportedTransferSyntax() const
{
return EXS_JPEG2000LosslessOnly;
}
E_TransferSyntax DJPEG2KNearLosslessEncoder::supportedTransferSyntax() const
{
return EXS_JPEG2000;
}
// --------------------------------------------------------------------------
DJPEG2KEncoderBase::DJPEG2KEncoderBase()
: DcmCodec()
{
}
DJPEG2KEncoderBase::~DJPEG2KEncoderBase()
{
}
OFBool DJPEG2KEncoderBase::canChangeCoding(
const E_TransferSyntax oldRepType,
const E_TransferSyntax newRepType) const
{
// this codec only handles conversion from uncompressed to JPEG 2000.
DcmXfer oldRep(oldRepType);
return (oldRep.isNotEncapsulated() && (newRepType == supportedTransferSyntax()));
}
OFCondition DJPEG2KEncoderBase::decode(
const DcmRepresentationParameter * /* fromRepParam */,
DcmPixelSequence * /* pixSeq */,
DcmPolymorphOBOW& /* uncompressedPixelData */,
const DcmCodecParameter * /* cp */,
const DcmStack& /* objStack */) const
{
// we are an encoder only
return EC_IllegalCall;
}
OFCondition DJPEG2KEncoderBase::decode(
const DcmRepresentationParameter * fromRepParam,
DcmPixelSequence * pixSeq,
DcmPolymorphOBOW& uncompressedPixelData,
const DcmCodecParameter * cp,
const DcmStack& objStack,
OFBool& removeOldRep) const
{
return EC_IllegalCall;
}
OFCondition DJPEG2KEncoderBase::decodeFrame(
const DcmRepresentationParameter * /* fromParam */ ,
DcmPixelSequence * /* fromPixSeq */ ,
const DcmCodecParameter * /* cp */ ,
DcmItem * /* dataset */ ,
Uint32 /* frameNo */ ,
Uint32& /* startFragment */ ,
void * /* buffer */ ,
Uint32 /* bufSize */ ,
OFString& /* decompressedColorModel */ ) const
{
// we are an encoder only
return EC_IllegalCall;
}
OFCondition DJPEG2KEncoderBase::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 DJPEG2KEncoderBase::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 DJPEG2KEncoderBase::encode(
const Uint16 * pixelData,
const Uint32 length,
const DcmRepresentationParameter * toRepParam,
DcmPixelSequence * & pixSeq,
const DcmCodecParameter *cp,
DcmStack & objStack) const
{
OFCondition result = EC_Normal;
FMJPEG2KRepresentationParameter defRep;
// 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);
// assume we can cast the codec and representation parameters to what we need
const DJPEG2KCodecParameter *djcp = OFreinterpret_cast(const DJPEG2KCodecParameter *, cp);
const FMJPEG2KRepresentationParameter *djrp = OFreinterpret_cast(const FMJPEG2KRepresentationParameter *, toRepParam);
double compressionRatio = 0.0;
if (!djrp)
djrp = &defRep;
if (supportedTransferSyntax() == EXS_JPEG2000LosslessOnly || djrp->useLosslessProcess())
{
if (djcp->cookedEncodingPreferred())
result = RenderedEncode(pixelData, length, dataset, djrp, pixSeq, djcp, compressionRatio);
else result = losslessRawEncode(pixelData, length, dataset, djrp, pixSeq, djcp, compressionRatio);
}
else
{
// near-lossless mode always uses the "cooked" encoder since this one is guaranteed not to "mix"
// overlays and pixel data in one cell subjected to lossy compression.
result = RenderedEncode(pixelData, length, dataset, djrp, pixSeq, djcp, compressionRatio);
}
// 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 (result.good() && dataset->ident() == EVR_dataset)
{
if (result.good())
{
if (supportedTransferSyntax() == EXS_JPEG2000LosslessOnly || supportedTransferSyntax() == EXS_JPEG2000MulticomponentLosslessOnly || djrp->useLosslessProcess())
{
// lossless process - create new UID if mode is EUC_always or if we're converting to Secondary Capture
if (djcp->getConvertToSC() || (djcp->getUIDCreation() == EJ2KUC_always))
result = DcmCodec::newInstance(dataset, "DCM", "121320", "Uncompressed predecessor");
}
else
{
// lossy process - create new UID unless mode is EUC_never and we're not converting to Secondary Capture
if (djcp->getConvertToSC() || (djcp->getUIDCreation() != EJ2KUC_never))
result = DcmCodec::newInstance(dataset, "DCM", "121320", "Uncompressed predecessor");
// update image type
if (result.good()) result = DcmCodec::updateImageType(dataset);
// update derivation description
if (result.good()) result = updateDerivationDescription(dataset, djrp, compressionRatio);
// update lossy compression ratio
if (result.good()) result = updateLossyCompressionRatio(dataset, compressionRatio);
}
}
// convert to Secondary Capture if requested by user.
// This method creates a new SOP class UID, so it should be executed
// after the call to newInstance() which creates a Source Image Sequence.
if (result.good() && djcp->getConvertToSC()) result = DcmCodec::convertToSecondaryCapture(dataset);
}
return result;
}
OFCondition DJPEG2KEncoderBase::encode(
const Uint16 * pixelData,
const Uint32 length,
const DcmRepresentationParameter * toRepParam,
DcmPixelSequence * & pixSeq,
const DcmCodecParameter *cp,
DcmStack & objStack,
OFBool& removeOldRep) const
{
// removeOldRep is left as it is, pixel data in original DICOM dataset is not modified
return encode(pixelData, length, toRepParam, pixSeq, cp, objStack);
}
OFCondition DJPEG2KEncoderBase::determineDecompressedColorModel(
const DcmRepresentationParameter * /* fromParam */,
DcmPixelSequence * /* fromPixSeq */,
const DcmCodecParameter * /* cp */,
DcmItem * /* dataset */,
OFString & /* decompressedColorModel */) const
{
return EC_IllegalCall;
}
OFCondition DJPEG2KEncoderBase::adjustOverlays(
DcmItem *dataset,
DicomImage& image) const
{
if (dataset == NULL) return EC_IllegalCall;
unsigned int overlayCount = image.getOverlayCount();
if (overlayCount > 0)
{
Uint16 group = 0;
DcmStack stack;
unsigned long bytesAllocated = 0;
Uint8 *buffer = NULL;
unsigned int width = 0;
unsigned int height = 0;
unsigned long frames = 0;
DcmElement *elem = NULL;
OFCondition result = EC_Normal;
// adjust overlays (prior to grayscale compression)
for (unsigned int i=0; i < overlayCount; i++)
{
// check if current overlay is embedded in pixel data
group = OFstatic_cast(Uint16, image.getOverlayGroupNumber(i));
stack.clear();
if ((dataset->search(DcmTagKey(group, 0x3000), stack, ESM_fromHere, OFFalse)).bad())
{
// separate Overlay Data not found. Assume overlay is embedded.
bytesAllocated = image.create6xxx3000OverlayData(buffer, i, width, height, frames);
if (bytesAllocated > 0)
{
elem = new DcmOverlayData(DcmTagKey(group, 0x3000)); // DCM_OverlayData
if (elem)
{
result = elem->putUint8Array(buffer, bytesAllocated);
delete[] buffer;
if (result.good())
{
dataset->insert(elem, OFTrue /*replaceOld*/);
// DCM_OverlayBitsAllocated
result = dataset->putAndInsertUint16(DcmTagKey(group, 0x0100), 1);
// DCM_OverlayBitPosition
if (result.good()) result = dataset->putAndInsertUint16(DcmTagKey(group, 0x0102), 0);
}
else
{
delete elem;
return result;
}
}
else
{
delete[] buffer;
return EC_MemoryExhausted;
}
}
else return EC_IllegalCall;
}
}
}
return EC_Normal;
}
OFCondition DJPEG2KEncoderBase::updateLossyCompressionRatio(
DcmItem *dataset,
double ratio) const
{
if (dataset == NULL) return EC_IllegalCall;
// set Lossy Image Compression to "01" (see DICOM part 3, C.7.6.1.1.5)
OFCondition result = dataset->putAndInsertString(DCM_LossyImageCompression, "01");
if (result.bad()) return result;
// set Lossy Image Compression Ratio
OFString s;
const char *oldRatio = NULL;
if ((dataset->findAndGetString(DCM_LossyImageCompressionRatio, oldRatio)).good() && oldRatio)
{
s = oldRatio;
s += "\\";
}
// append lossy compression ratio
char buf[64];
OFStandard::ftoa(buf, sizeof(buf), ratio, OFStandard::ftoa_uppercase, 0, 5);
s += buf;
result = dataset->putAndInsertString(DCM_LossyImageCompressionRatio, s.c_str());
if (result.bad()) return result;
// count VM of lossy image compression ratio
size_t i;
size_t s_vm = 0;
size_t s_sz = s.size();
for (i = 0; i < s_sz; ++i)
if (s[i] == '\\') ++s_vm;
// set Lossy Image Compression Method
const char *oldMethod = NULL;
OFString m;
if ((dataset->findAndGetString(DCM_LossyImageCompressionMethod, oldMethod)).good() && oldMethod)
{
m = oldMethod;
m += "\\";
}
// count VM of lossy image compression method
size_t m_vm = 0;
size_t m_sz = m.size();
for (i = 0; i < m_sz; ++i)
if (m[i] == '\\') ++m_vm;
// make sure that VM of Compression Method is not smaller than VM of Compression Ratio
while (m_vm++ < s_vm) m += "\\";
m += "ISO_14495_1";
return dataset->putAndInsertString(DCM_LossyImageCompressionMethod, m.c_str());
}
OFCondition DJPEG2KEncoderBase::updateDerivationDescription(
DcmItem *dataset,
const FMJPEG2KRepresentationParameter *djrp,
double ratio) const
{
OFString derivationDescription;
char buf[64];
derivationDescription = "near lossless JPEG-2000 compression, factor ";
OFStandard::ftoa(buf, sizeof(buf), ratio, OFStandard::ftoa_uppercase, 0, 5);
derivationDescription += buf;
sprintf(buf, " (PSNR=%lu)", OFstatic_cast(unsigned long, djrp->getnearlosslessPSNR()));
derivationDescription += buf;
// append old Derivation Description, if any
const char *oldDerivation = NULL;
if ((dataset->findAndGetString(DCM_DerivationDescription, oldDerivation)).good() && oldDerivation)
{
derivationDescription += " [";
derivationDescription += oldDerivation;
derivationDescription += "]";
if (derivationDescription.length() > 1024)
{
// ST is limited to 1024 characters, cut off tail
derivationDescription.erase(1020);
derivationDescription += "...]";
}
}
OFCondition result = dataset->putAndInsertString(DCM_DerivationDescription, derivationDescription.c_str());
if (result.good()) result = DcmCodec::insertCodeSequence(dataset, DCM_DerivationCodeSequence, "DCM", "113040", "Lossy Compression");
return result;
}
OFCondition DJPEG2KEncoderBase::losslessRawEncode(
const Uint16 *pixelData,
const Uint32 length,
DcmItem *dataset,
const FMJPEG2KRepresentationParameter *djrp,
DcmPixelSequence * & pixSeq,
const DJPEG2KCodecParameter *djcp,
double& compressionRatio) const
{
compressionRatio = 0.0; // initialize if something goes wrong
// determine image properties
Uint16 bitsAllocated = 0;
Uint16 bitsStored = 0;
Uint16 bytesAllocated = 0;
Uint16 samplesPerPixel = 0;
Uint16 planarConfiguration = 0;
Uint16 columns = 0;
Uint16 rows = 0;
Sint32 numberOfFrames = 1;
OFBool byteSwapped = OFFalse; // true if we have byte-swapped the original pixel data
OFString photometricInterpretation;
Uint16 pixelRepresentation = 0;
OFCondition result = dataset->findAndGetUint16(DCM_BitsAllocated, bitsAllocated);
if (result.good()) result = dataset->findAndGetUint16(DCM_BitsStored, bitsStored);
if (result.good()) result = dataset->findAndGetUint16(DCM_SamplesPerPixel, samplesPerPixel);
if (result.good()) result = dataset->findAndGetUint16(DCM_Columns, columns);
if (result.good()) result = dataset->findAndGetUint16(DCM_Rows, rows);
if (result.good()) dataset->findAndGetUint16(DCM_PixelRepresentation, pixelRepresentation);
if (result.good()) result = dataset->findAndGetOFString(DCM_PhotometricInterpretation, photometricInterpretation);
if (result.good())
{
result = dataset->findAndGetSint32(DCM_NumberOfFrames, numberOfFrames);
if (result.bad() || numberOfFrames < 1) numberOfFrames = 1;
result = EC_Normal;
}
if (result.good() && (samplesPerPixel > 1))
{
result = dataset->findAndGetUint16(DCM_PlanarConfiguration, planarConfiguration);
}
if (result.good())
{
// check if bitsAllocated is 8 or 16 or 32 - we don't handle anything else
if (bitsAllocated == 8)
{
bytesAllocated = 1;
}
else if (bitsAllocated == 16)
{
bytesAllocated = 2;
}
else if (bitsAllocated == 32)
{
bytesAllocated = 4;
}
else
{
if (photometricInterpretation == "MONOCHROME1" ||
photometricInterpretation == "MONOCHROME2" ||
photometricInterpretation == "RGB" ||
photometricInterpretation == "YBR_FULL")
{
// A bitsAllocated value that we don't handle, but a color model that indicates
// that the cooked encoder could handle this case. Fall back to cooked encoder.
return RenderedEncode(pixelData, length, dataset, djrp, pixSeq, djcp, compressionRatio);
}
// an image that is not supported by either the raw or the cooked encoder.
result = EC_J2KUnsupportedImageType;
}
// make sure that all the descriptive attributes have sensible values
if ((columns < 1)||(rows < 1)||(samplesPerPixel < 1)) result = EC_J2KUnsupportedImageType;
// make sure that we have at least as many bytes of pixel data as we expect
if (bytesAllocated * samplesPerPixel * columns * rows *
OFstatic_cast(unsigned long,numberOfFrames) > length)
result = EC_J2KUncompressedBufferTooSmall;
}
DcmPixelSequence *pixelSequence = NULL;
DcmPixelItem *offsetTable = NULL;
// create initial pixel sequence
if (result.good())
{
pixelSequence = new DcmPixelSequence(DcmTag(DCM_PixelData,EVR_OB));
if (pixelSequence == NULL) result = EC_MemoryExhausted;
else
{
// create empty offset table
offsetTable = new DcmPixelItem(DcmTag(DCM_Item,EVR_OB));
if (offsetTable == NULL) result = EC_MemoryExhausted;
else pixelSequence->insert(offsetTable);
}
}
DcmOffsetList offsetList;
unsigned long compressedSize = 0;
unsigned long compressedFrameSize = 0;
double uncompressedSize = 0.0;
// render and compress each frame
if (result.good())
{
// byte swap pixel data to little endian if bits allocate is 8
if ((gLocalByteOrder == EBO_BigEndian) && (bitsAllocated == 8))
{
swapIfNecessary(EBO_LittleEndian, gLocalByteOrder, OFstatic_cast(void *, OFconst_cast(Uint16 *, pixelData)), length, sizeof(Uint16));
byteSwapped = OFTrue;
}
unsigned long frameCount = OFstatic_cast(unsigned long, numberOfFrames);
unsigned long frameSize = columns * rows * samplesPerPixel * bytesAllocated;
const Uint8 *framePointer = OFreinterpret_cast(const Uint8 *, pixelData);
// compute original image size in bytes, ignoring any padding bits.
uncompressedSize = columns * rows * samplesPerPixel * bitsStored * frameCount / 8.0;
for (unsigned long i=0; (i<frameCount) && (result.good()); ++i)
{
// compress frame
FMJPEG2K_DEBUG("JPEG-2000 encoder processes frame " << (i+1) << " of " << frameCount);
result = compressRawFrame(framePointer, bitsAllocated, columns, rows,
samplesPerPixel, planarConfiguration, pixelRepresentation, photometricInterpretation,
pixelSequence, offsetList, compressedFrameSize, djcp);
compressedSize += compressedFrameSize;
framePointer += frameSize;
}
}
// store pixel sequence if everything went well.
if (result.good()) pixSeq = pixelSequence;
else
{
delete pixelSequence;
pixSeq = NULL;
}
// create offset table
if ((result.good()) && (djcp->getCreateOffsetTable()))
{
result = offsetTable->createOffsetTable(offsetList);
}
if (compressedSize > 0) compressionRatio = uncompressedSize / compressedSize;
// byte swap pixel data back to local endian if necessary
if (byteSwapped)
{
swapIfNecessary(gLocalByteOrder, EBO_LittleEndian, OFstatic_cast(void *, OFconst_cast(Uint16 *, pixelData)), length, sizeof(Uint16));
}
return result;
}
OFCondition frametoimage(const Uint8 *framePointer, int planarConfiguration, OFString photometricInterpretation, int samplesPerPixel, int width, int height, int bitsAllocated, OFBool isSigned, opj_cparameters_t *parameters, opj_image_t **ret_image);
opj_image_t *frameToImage2(const Uint8 *framePointer, int width, int height, opj_cparameters_t *parameters);
opj_image_t *frameToImage3(const Uint8 *framePointer, int width, int height, opj_cparameters_t *parameters);
OFCondition DJPEG2KEncoderBase::compressRawFrame(
const Uint8 *framePointer,
Uint16 bitsAllocated,
Uint16 width,
Uint16 height,
Uint16 samplesPerPixel,
Uint16 planarConfiguration,
OFBool pixelRepresentation,
const OFString& photometricInterpretation,
DcmPixelSequence *pixelSequence,
DcmOffsetList &offsetList,
unsigned long &compressedSize,
const DJPEG2KCodecParameter *djcp) const
{
OFCondition result = EC_Normal;
Uint16 bytesAllocated = bitsAllocated / 8;
Uint32 frameSize = width*height*bytesAllocated*samplesPerPixel;
Uint32 fragmentSize = djcp->getFragmentSize();
opj_cparameters_t parameters;
opj_image_t *image = NULL;
opj_set_default_encoder_parameters(¶meters);
result = frametoimage(framePointer, planarConfiguration, photometricInterpretation, samplesPerPixel, width, height, bitsAllocated, pixelRepresentation, ¶meters, &image);
if (result.good())
{
// set lossless
parameters.tcp_numlayers = 1;
parameters.tcp_rates[0] = 0;
parameters.cp_disto_alloc = 1;
if(djcp->getUseCustomOptions())
{
parameters.cblockw_init = djcp->get_cblkwidth();
parameters.cblockh_init = djcp->get_cblkheight();
}
// turn on/off MCT depending on transfer syntax
if(supportedTransferSyntax() == EXS_JPEG2000LosslessOnly)
parameters.tcp_mct = 0;
else if(supportedTransferSyntax() == EXS_JPEG2000MulticomponentLosslessOnly)
parameters.tcp_mct = (image->numcomps >= 3) ? 1 : 0;
// We have no idea how big the compressed pixel data will be and we have no
// way to find out, so we just allocate a buffer large enough for the raw data
// plus a little more for JPEG metadata.
// Yes, this is way too much for just a little JPEG metadata, but some
// test-images showed that the buffer previously was too small. Plus, at some
// places charls fails to do proper bounds checking and writes behind the end
// of the buffer (sometimes way behind its end...).
size_t size = frameSize + 1024;
Uint8 *buffer = new Uint8[size];
// Set up the information structure for OpenJPEG
opj_stream_t *l_stream = NULL;
opj_codec_t* l_codec = NULL;
l_codec = opj_create_compress(OPJ_CODEC_J2K);
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);
if (result.good() && !opj_setup_encoder(l_codec, ¶meters, image))
{
opj_destroy_codec(l_codec);
l_codec = NULL;
result = EC_MemoryExhausted;
}
DecodeData mysrc((unsigned char*)buffer, size);
l_stream = opj_stream_create_memory_stream(&mysrc, size, OPJ_FALSE);
if(!opj_start_compress(l_codec,image,l_stream))
{
result = EC_CorruptedData;
}
if(result.good() && !opj_encode(l_codec, l_stream))
{
result = EC_InvalidStream;
}
if(result.good() && opj_end_compress(l_codec, l_stream))
{
result = EC_Normal;
}
opj_stream_destroy(l_stream); l_stream = NULL;
opj_destroy_codec(l_codec); l_codec = NULL;
opj_image_destroy(image); image = NULL;
size = mysrc.offset;
if (result.good())
{
// 'size' now contains the size of the compressed data in buffer
compressedSize = size;
result = pixelSequence->storeCompressedFrame(offsetList, buffer, size, fragmentSize);
}
delete[] buffer;
}
return result;
}
OFCondition DJPEG2KEncoderBase::RenderedEncode(
const Uint16 *pixelData,
const Uint32 length,
DcmItem *dataset,
const FMJPEG2KRepresentationParameter *djrp,
DcmPixelSequence * & pixSeq,
const DJPEG2KCodecParameter *djcp,
double& compressionRatio) const
{
compressionRatio = 0.0; // initialize if something goes wrong
// determine a few image properties
OFString photometricInterpretation;
Uint16 bitsAllocated = 0;
OFCondition result = dataset->findAndGetOFString(DCM_PhotometricInterpretation, photometricInterpretation);
if (result.good()) result = dataset->findAndGetUint16(DCM_BitsAllocated, bitsAllocated);
if (result.bad()) return result;
// The cooked encoder only handles the following photometic interpretations
if (photometricInterpretation != "MONOCHROME1" &&
photometricInterpretation != "MONOCHROME2" &&
photometricInterpretation != "RGB" &&
photometricInterpretation != "YBR_FULL")
{
// a photometric interpretation that we don't handle. Fall back to raw encoder (unless in near-lossless mode)
return losslessRawEncode(pixelData, length, dataset, djrp, pixSeq, djcp, compressionRatio);
}
Uint16 pixelRepresentation = 0;
result = dataset->findAndGetUint16(DCM_PixelRepresentation, pixelRepresentation);
if (result.bad()) return result;
DcmPixelSequence *pixelSequence = NULL;
DcmPixelItem *offsetTable = NULL;
// ignore modality transformation (rescale slope/intercept or LUT) stored in the dataset
unsigned long flags = CIF_IgnoreModalityTransformation;
// don't convert YCbCr (Full and Full 4:2:2) color images to RGB
flags |= CIF_KeepYCbCrColorModel;
// Don't optimize memory usage, but keep using the same bitsAllocated.
// Without this, the DICOM and the JPEG-2000 value for bitsAllocated could
// differ and the decoder would error out.
flags |= CIF_UseAbsolutePixelRange;
DicomImage *dimage = new DicomImage(dataset, EXS_LittleEndianImplicit, flags); // read all frames
if (dimage == NULL) return EC_MemoryExhausted;
if (dimage->getStatus() != EIS_Normal)
{
delete dimage;
return EC_IllegalCall;
}
// create overlay data for embedded overlays
result = adjustOverlays(dataset, *dimage);
// determine number of bits per sample
int bitsPerSample = dimage->getDepth();
if (result.good() && (bitsPerSample > 16)) result = EC_J2KUnsupportedBitDepth;
// create initial pixel sequence
if (result.good())
{
pixelSequence = new DcmPixelSequence(DcmTag(DCM_PixelData,EVR_OB));
if (pixelSequence == NULL) result = EC_MemoryExhausted;
else
{
// create empty offset table
offsetTable = new DcmPixelItem(DcmTag(DCM_Item,EVR_OB));
if (offsetTable == NULL) result = EC_MemoryExhausted;
else pixelSequence->insert(offsetTable);
}
}
DcmOffsetList offsetList;
unsigned long compressedSize = 0;
unsigned long compressedFrameSize = 0;
double uncompressedSize = 0.0;
// render and compress each frame
if (result.good())
{
unsigned long frameCount = dimage->getFrameCount();
// compute original image size in bytes, ignoring any padding bits.
Uint16 samplesPerPixel = 0;
if ((dataset->findAndGetUint16(DCM_SamplesPerPixel, samplesPerPixel)).bad()) samplesPerPixel = 1;
uncompressedSize = dimage->getWidth() * dimage->getHeight() *
bitsPerSample * frameCount * samplesPerPixel / 8.0;
for (unsigned long i=0; (i<frameCount) && (result.good()); ++i)
{
// compress frame
FMJPEG2K_DEBUG("JPEG-2000 encoder processes frame " << (i+1) << " of " << frameCount);
result = compressRenderedFrame(pixelSequence, dimage,
photometricInterpretation, offsetList, compressedFrameSize, djcp, i, djrp);
compressedSize += compressedFrameSize;
}
}
// store pixel sequence if everything went well.
if (result.good()) pixSeq = pixelSequence;
else
{
delete pixelSequence;
pixSeq = NULL;
}
// create offset table
if ((result.good()) && (djcp->getCreateOffsetTable()))
{
result = offsetTable->createOffsetTable(offsetList);
}
// adapt attributes in image pixel module
if (result.good())
{
// adjustments needed for both color and monochrome
if (bitsPerSample > 8)
result = dataset->putAndInsertUint16(DCM_BitsAllocated, 16);
else
result = dataset->putAndInsertUint16(DCM_BitsAllocated, 8);
if (result.good()) result = dataset->putAndInsertUint16(DCM_BitsStored, bitsPerSample);
if (result.good()) result = dataset->putAndInsertUint16(DCM_HighBit, bitsPerSample-1);
}
if (compressedSize > 0) compressionRatio = uncompressedSize / compressedSize;
delete dimage;
return result;
}
OFCondition DJPEG2KEncoderBase::compressRenderedFrame(
DcmPixelSequence *pixelSequence,
DicomImage *dimage,
const OFString& photometricInterpretation,
DcmOffsetList &offsetList,
unsigned long &compressedSize,
const DJPEG2KCodecParameter *djcp,
Uint32 frame,
const FMJPEG2KRepresentationParameter *djrp) const
{
if (dimage == NULL) return EC_IllegalCall;
// access essential image parameters
int width = dimage->getWidth();
int height = dimage->getHeight();
int depth = dimage->getDepth();
if ((depth < 1) || (depth > 16)) return EC_J2KUnsupportedBitDepth;
Uint32 fragmentSize = djcp->getFragmentSize();
const DiPixel *dinter = dimage->getInterData();
if (dinter == NULL) return EC_IllegalCall;
// There should be no other possibilities
int samplesPerPixel = dinter->getPlanes();
if (samplesPerPixel != 1 && samplesPerPixel != 3) return EC_IllegalCall;
// get pointer to internal raw representation of image data
const void *draw = dinter->getData();
if (draw == NULL) return EC_IllegalCall;
OFCondition result = EC_Normal;
const void *planes[3] = {NULL, NULL, NULL};
if (samplesPerPixel == 3)
{
// for color images, dinter->getData() returns a pointer to an array
// of pointers pointing to the real plane data
const void * const * draw_array = OFstatic_cast(const void * const *,draw);
planes[0] = draw_array[0];
planes[1] = draw_array[1];
planes[2] = draw_array[2];
}
else
{
// for monochrome images, dinter->getData() directly returns a pointer
// to the single monochrome plane.
planes[0] = draw;
}
// This is the buffer with the uncompressed pixel data
Uint8 *buffer;
size_t buffer_size;
Uint32 framesize = dimage->getWidth() * dimage->getHeight();
switch(dinter->getRepresentation())
{
case EPR_Uint8:
case EPR_Sint8:
{
// image representation is 8 bit signed or unsigned
if (samplesPerPixel == 1)
{
const Uint8 *yv = OFreinterpret_cast(const Uint8 *, planes[0]) + framesize * frame;
buffer_size = framesize;
buffer = new Uint8[buffer_size];
memcpy(buffer, yv, framesize);
}
else
{
const Uint8 *rv = OFreinterpret_cast(const Uint8 *, planes[0]) + framesize * frame;
const Uint8 *gv = OFreinterpret_cast(const Uint8 *, planes[1]) + framesize * frame;
const Uint8 *bv = OFreinterpret_cast(const Uint8 *, planes[2]) + framesize * frame;
buffer_size = framesize * 3;
buffer = new Uint8[buffer_size];
size_t i = 0;
for (int row=height; row; --row)
{
for (int col=width; col; --col)
{
buffer[i++] = *rv;
buffer[i++] = *gv;
buffer[i++] = *bv;
rv++;
gv++;
bv++;
}
}
}
}
break;
case EPR_Uint16:
case EPR_Sint16:
{
// image representation is 16 bit signed or unsigned
if (samplesPerPixel == 1)
{
const Uint16 *yv = OFreinterpret_cast(const Uint16 *, planes[0]) + framesize * frame;
buffer_size = framesize*sizeof(Uint16);
buffer = new Uint8[buffer_size];
memcpy(buffer, yv, buffer_size);
}
else
{
const Uint16 *rv = OFreinterpret_cast(const Uint16 *, planes[0]) + framesize * frame;
const Uint16 *gv = OFreinterpret_cast(const Uint16 *, planes[1]) + framesize * frame;
const Uint16 *bv = OFreinterpret_cast(const Uint16 *, planes[2]) + framesize * frame;
buffer_size = framesize * 3;
Uint16 *buffer16 = new Uint16[buffer_size];
buffer = OFreinterpret_cast(Uint8 *, buffer16);
// Convert to byte count
buffer_size *= 2;
size_t i = 0;
for (int row=height; row; --row)
{
for (int col=width; col; --col)
{
buffer16[i++] = *rv;
buffer16[i++] = *gv;
buffer16[i++] = *bv;
rv++;
gv++;
bv++;
}
}
}
}
break;
default:
// we don't support images with > 16 bits/sample
return EC_J2KUnsupportedBitDepth;
break;
}
opj_cparameters_t parameters;
opj_image_t *image = NULL;
opj_set_default_encoder_parameters(¶meters);
int bitsAllocated = 8;
int pixelRepresentation = 0;
switch(dinter->getRepresentation())
{
case EPR_Uint8:
bitsAllocated = 8;
pixelRepresentation = 0;
break;
case EPR_Sint8:
bitsAllocated = 8;
pixelRepresentation = 1;
break;
case EPR_Uint16: