File: dcrleccd.cc

package info (click to toggle)
dcmtk 3.6.0-12
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 32,976 kB
  • sloc: cpp: 193,852; ansic: 46,292; sh: 4,020; makefile: 3,969; perl: 3,278; lex: 94
file content (775 lines) | stat: -rw-r--r-- 30,934 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
/*
 *
 *  Copyright (C) 2002-2010, OFFIS e.V.
 *  All rights reserved.  See COPYRIGHT file for details.
 *
 *  This software and supporting documentation were developed by
 *
 *    OFFIS e.V.
 *    R&D Division Health
 *    Escherweg 2
 *    D-26121 Oldenburg, Germany
 *
 *
 *  Module:  dcmdata
 *
 *  Author:  Marco Eichelberg
 *
 *  Purpose: decoder codec class for RLE
 *
 *  Last Update:      $Author: uli $
 *  Update Date:      $Date: 2010-11-01 10:42:44 $
 *  CVS/RCS Revision: $Revision: 1.18 $
 *  Status:           $State: Exp $
 *
 *  CVS/RCS Log at end of file
 *
 */

#include "dcmtk/config/osconfig.h"
#include "dcmtk/dcmdata/dcrleccd.h"

// dcmdata includes
#include "dcmtk/dcmdata/dcrlecp.h"   /* for class DcmRLECodecParameter */
#include "dcmtk/dcmdata/dcrledec.h"  /* for class DcmRLEDecoder */
#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()*/


DcmRLECodecDecoder::DcmRLECodecDecoder()
: DcmCodec()
{
}


DcmRLECodecDecoder::~DcmRLECodecDecoder()
{
}


OFBool DcmRLECodecDecoder::canChangeCoding(
    const E_TransferSyntax oldRepType,
    const E_TransferSyntax newRepType) const
{
  E_TransferSyntax myXfer = EXS_RLELossless;
  DcmXfer newRep(newRepType);
  if (newRep.isNotEncapsulated() && (oldRepType == myXfer)) return OFTrue; // decompress requested

  // we don't support re-coding for now.
  return OFFalse;
}


OFCondition DcmRLECodecDecoder::decode(
    const DcmRepresentationParameter * /* fromRepParam */,
    DcmPixelSequence * pixSeq,
    DcmPolymorphOBOW& uncompressedPixelData,
    const DcmCodecParameter * cp,
    const DcmStack& objStack) const
{
  OFCondition result = EC_Normal;

  // assume we can cast the codec parameter to what we need
  const DcmRLECodecParameter *djcp = OFstatic_cast(const DcmRLECodecParameter *, cp);

  OFBool enableReverseByteOrder = djcp->getReverseDecompressionByteOrder();

  DcmStack localStack(objStack);
  (void)localStack.pop();             // pop pixel data element from stack
  DcmObject *dataset = localStack.pop(); // this is the item in which the pixel data is located
  if ((!dataset)||((dataset->ident()!= EVR_dataset) && (dataset->ident()!= EVR_item))) result = EC_InvalidTag;
  else
  {
    Uint16 imageSamplesPerPixel = 0;
    Uint16 imageRows = 0;
    Uint16 imageColumns = 0;
    Sint32 imageFrames = 1;
    Uint16 imageBitsAllocated = 0;
    Uint16 imageBytesAllocated = 0;
    Uint16 imagePlanarConfiguration = 0;
    Uint32 rleHeader[16];
    DcmItem *ditem = OFstatic_cast(DcmItem *, dataset);
    OFBool numberOfFramesPresent = OFFalse;

    if (result.good()) result = ditem->findAndGetUint16(DCM_SamplesPerPixel, imageSamplesPerPixel);
    if (result.good()) result = ditem->findAndGetUint16(DCM_Rows, imageRows);
    if (result.good()) result = ditem->findAndGetUint16(DCM_Columns, imageColumns);
    if (result.good()) result = ditem->findAndGetUint16(DCM_BitsAllocated, imageBitsAllocated);
    if (result.good())
    {
      imageBytesAllocated = OFstatic_cast(Uint16, imageBitsAllocated / 8);
      if ((imageBitsAllocated < 8)||(imageBitsAllocated % 8 != 0)) result = EC_CannotChangeRepresentation;
    }
    if (result.good() && (imageSamplesPerPixel > 1))
    {
      result = ditem->findAndGetUint16(DCM_PlanarConfiguration, imagePlanarConfiguration);
    }

    // number of frames is an optional attribute - we don't mind if it isn't present.
    if (result.good())
    {
      if (ditem->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

    if (result.good())
    {
      DcmPixelItem *pixItem = NULL;
      Uint8 * rleData = NULL;
      const size_t bytesPerStripe = imageColumns * imageRows;

      DcmRLEDecoder rledecoder(bytesPerStripe);
      if (rledecoder.fail()) result = EC_MemoryExhausted;  // RLE decoder failed to initialize
      else
      {
        Uint32 frameSize = imageBytesAllocated * imageRows * imageColumns * imageSamplesPerPixel;
        Uint32 totalSize = frameSize * imageFrames;
        if (totalSize & 1) totalSize++; // align on 16-bit word boundary
        Uint16 *imageData16 = NULL;
        Sint32 currentFrame = 0;
        Uint32 currentItem = 1; // ignore offset table
        Uint32 numberOfStripes = 0;
        Uint32 fragmentLength = 0;
        Uint32 i;

        result = uncompressedPixelData.createUint16Array(totalSize/sizeof(Uint16), imageData16);
        if (result.good())
        {
          Uint8 *imageData8 = OFreinterpret_cast(Uint8 *, imageData16);

          while ((currentFrame < imageFrames) && result.good())
          {
            DCMDATA_DEBUG("RLE decoder processes frame " << currentFrame);
            DCMDATA_DEBUG("RLE decoder processes pixel item " << currentItem);
            // get first pixel item of this frame
            result = pixSeq->getItem(pixItem, currentItem++);
            if (result.good())
            {
              fragmentLength = pixItem->getLength();
              result = pixItem->getUint8Array(rleData);
              if (result.good())
              {
                // we require that the RLE header must be completely
                // contained in the first fragment; otherwise bail out
                if (fragmentLength < 64) result = EC_CannotChangeRepresentation;
              }
            }

            if (result.good())
            {
              // copy RLE header to buffer and adjust byte order
              memcpy(rleHeader, rleData, 64);
              swapIfNecessary(gLocalByteOrder, EBO_LittleEndian, rleHeader, 16*sizeof(Uint32), sizeof(Uint32));

              // determine number of stripes.
              numberOfStripes = rleHeader[0];

              // check that number of stripes in RLE header matches our expectation
              if ((numberOfStripes < 1) || (numberOfStripes > 15) ||
                  (numberOfStripes != OFstatic_cast(Uint32, imageBytesAllocated) * imageSamplesPerPixel))
                  result = EC_CannotChangeRepresentation;
            }

            if (result.good())
            {
              // this variable keeps the number of bytes we have processed
              // for the current frame in earlier pixel fragments
              Uint32 fragmentOffset = 0;

              // this variable keeps the current position within the current fragment
              Uint32 byteOffset = 0;

              OFBool lastStripe = OFFalse;
              Uint32 inputBytes = 0;

              // pointers for buffer copy operations
              Uint8 *outputBuffer = NULL;
              Uint8 *pixelPointer = NULL;

              // byte offset for first sample in frame
              Uint32 sampleOffset = 0;

              // byte offset between samples
              Uint32 offsetBetweenSamples = 0;

              // temporary variables
              Uint32 sample = 0;
              Uint32 byte = 0;
              register Uint32 pixel = 0;

              // for each stripe in stripe set
              for (i=0; (i<numberOfStripes) && result.good(); ++i)
              {
                // reset RLE codec
                rledecoder.clear();

                // adjust start point for RLE stripe, ignoring trailing garbage from the last run
                byteOffset = rleHeader[i+1];
                if (byteOffset < fragmentOffset) result = EC_CannotChangeRepresentation;
                else
                {
                  byteOffset -= fragmentOffset; // now byteOffset is correct but may point to next fragment
                  while ((byteOffset > fragmentLength) && result.good())
                  {
                    DCMDATA_DEBUG("RLE decoder processes pixel item " << currentItem);
                    result = pixSeq->getItem(pixItem, currentItem++);
                    if (result.good())
                    {
                      byteOffset -= fragmentLength;
                      fragmentOffset += fragmentLength;
                      fragmentLength = pixItem->getLength();
                      result = pixItem->getUint8Array(rleData);
                    }
                  }
                }

                // byteOffset now points to the first byte of the new RLE stripe
                // check if the current stripe is the last one for this frame
                if (i+1 == numberOfStripes) lastStripe = OFTrue; else lastStripe = OFFalse;

                if (lastStripe)
                {
                  // the last stripe needs special handling because we cannot use the
                  // offset table to determine the number of bytes to feed to the codec
                  // if the RLE data is split in multiple fragments. We need to feed
                  // data fragment by fragment until the RLE codec has produced
                  // sufficient output.
                  while ((rledecoder.size() < bytesPerStripe) && result.good())
                  {
                    // feed complete remaining content of fragment to RLE codec and
                    // switch to next fragment
                    result = rledecoder.decompress(rleData + byteOffset, OFstatic_cast(size_t, fragmentLength - byteOffset));

                    // special handling for zero pad byte at the end of the RLE stream
                    // which results in an EC_StreamNotifyClient return code
                    // or trailing garbage data which results in EC_CorruptedData
                    if (rledecoder.size() == bytesPerStripe) result = EC_Normal;

                    // Check if we're already done. If yes, don't change fragment
                    if (result.good() || result == EC_StreamNotifyClient)
                    {
                      if (rledecoder.size() < bytesPerStripe)
                      {
                        DCMDATA_WARN("RLE decoder is finished but has produced insufficient data for this stripe, will continue with next pixel item");
                        DCMDATA_DEBUG("RLE decoder processes pixel item " << currentItem);
                        result = pixSeq->getItem(pixItem, currentItem++);
                        if (result.good())
                        {
                          byteOffset = 0;
                          fragmentOffset += fragmentLength;
                          fragmentLength = pixItem->getLength();
                          result = pixItem->getUint8Array(rleData);
                        }
                      }
                      else byteOffset = fragmentLength;
                    }
                  } /* while */
                }
                else
                {
                  // not the last stripe. We can use the offset table to determine
                  // the number of bytes to feed to the RLE codec.
                  inputBytes = rleHeader[i+2];
                  if (inputBytes < rleHeader[i+1]) result = EC_CannotChangeRepresentation;
                  else
                  {
                    inputBytes -= rleHeader[i+1]; // number of bytes to feed to codec
                    while ((inputBytes > (fragmentLength - byteOffset)) && result.good())
                    {
                      // feed complete remaining content of fragment to RLE codec and
                      // switch to next fragment
                      result = rledecoder.decompress(rleData + byteOffset, OFstatic_cast(size_t, fragmentLength - byteOffset));

                      if (result.good() || result == EC_StreamNotifyClient)
                      {
                        DCMDATA_DEBUG("RLE decoder processes pixel item " << currentItem);
                        result = pixSeq->getItem(pixItem, currentItem++);
                      }
                      if (result.good())
                      {
                        inputBytes -= fragmentLength - byteOffset;
                        byteOffset = 0;
                        fragmentOffset += fragmentLength;
                        fragmentLength = pixItem->getLength();
                        result = pixItem->getUint8Array(rleData);
                      }
                    } /* while */

                    // last fragment for this RLE stripe
                    result = rledecoder.decompress(rleData + byteOffset, OFstatic_cast(size_t, inputBytes));

                    // special handling for zero pad byte at the end of the RLE stream
                    // which results in an EC_StreamNotifyClient return code
                    // or trailing garbage data which results in EC_CorruptedData
                    if (rledecoder.size() == bytesPerStripe) result = EC_Normal;

                    byteOffset += inputBytes;
                  }
                }

                // make sure the RLE decoder has produced the right amount of data
                if (result.good() && (rledecoder.size() != bytesPerStripe))
                {
                    DCMDATA_ERROR("RLE decoder is finished but has produced insufficient data for this stripe");
                    result = EC_CannotChangeRepresentation;
                }

                // distribute decompressed bytes into output image array
                if (result.good())
                {
                  // which sample and byte are we currently compressing?
                  sample = i / imageBytesAllocated;
                  byte = i % imageBytesAllocated;

                  // raw buffer containing bytesPerStripe bytes of uncompressed data
                  outputBuffer = OFstatic_cast(Uint8 *, rledecoder.getOutputBuffer());

                  // compute byte offsets
                  if (imagePlanarConfiguration == 0)
                  {
                     sampleOffset = sample * imageBytesAllocated;
                     offsetBetweenSamples = imageSamplesPerPixel * imageBytesAllocated;
                  }
                  else
                  {
                     sampleOffset = sample * imageBytesAllocated * imageColumns * imageRows;
                     offsetBetweenSamples = imageBytesAllocated;
                  }

                  // initialize pointer to output data
                  if (enableReverseByteOrder)
                  {
                    // assume incorrect LSB to MSB order of RLE segments as produced by some tools
                    pixelPointer = imageData8 + sampleOffset + byte;
                  }
                  else
                  {
                    pixelPointer = imageData8 + sampleOffset + imageBytesAllocated - byte - 1;
                  }

                  // loop through all pixels of the frame
                  for (pixel = 0; pixel < bytesPerStripe; ++pixel)
                  {
                    *pixelPointer = *outputBuffer++;
                    pixelPointer += offsetBetweenSamples;
                  }
                }
              } /* for */
            }

            // advance by one frame
            if (result.good())
            {
              currentFrame++;
              imageData8 += frameSize;
            }

          } /* while still frames to process */

          // adjust byte order for uncompressed image to little endian
          swapIfNecessary(EBO_LittleEndian, gLocalByteOrder, imageData16, totalSize, sizeof(Uint16));

          // 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 = OFstatic_cast(DcmItem *, dataset)->putAndInsertString(DCM_NumberOfFrames, numBuf);
          }
        }
      }
    }

    // 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)
    {
        // create new SOP instance UID if codec parameters require so
        if (result.good() && djcp->getUIDCreation()) result =
          DcmCodec::newInstance(OFstatic_cast(DcmItem *, dataset), NULL, NULL, NULL);
    }
  }
  return result;
}


OFCondition DcmRLECodecDecoder::decodeFrame(
    const DcmRepresentationParameter * /* fromParam */,
    DcmPixelSequence * fromPixSeq,
    const DcmCodecParameter * cp,
    DcmItem *dataset,
    Uint32 frameNo,
    Uint32& startFragment,
    void *buffer,
    Uint32 bufSize,
    OFString& decompressedColorModel) const
{
    OFCondition result = EC_Normal;

    // assume we can cast the codec parameter to what we need
    const DcmRLECodecParameter *djcp = OFstatic_cast(const DcmRLECodecParameter *, cp);

    OFBool enableReverseByteOrder = djcp->getReverseDecompressionByteOrder();

    if ((!dataset)||((dataset->ident()!= EVR_dataset) && (dataset->ident()!= EVR_item))) return EC_InvalidTag;

    Uint16 imageSamplesPerPixel = 0;
    Uint16 imageRows = 0;
    Uint16 imageColumns = 0;
    Sint32 imageFrames = 1;
    Uint16 imageBitsAllocated = 0;
    Uint16 imageBytesAllocated = 0;
    Uint16 imagePlanarConfiguration = 0;
    Uint32 rleHeader[16];
    OFString photometricInterpretation;
    DcmItem *ditem = OFstatic_cast(DcmItem *, dataset);

    if (result.good()) result = ditem->findAndGetUint16(DCM_SamplesPerPixel, imageSamplesPerPixel);
    if (result.good()) result = ditem->findAndGetUint16(DCM_Rows, imageRows);
    if (result.good()) result = ditem->findAndGetUint16(DCM_Columns, imageColumns);
    if (result.good()) result = ditem->findAndGetUint16(DCM_BitsAllocated, imageBitsAllocated);
    if (result.good()) result = dataset->findAndGetOFString(DCM_PhotometricInterpretation, photometricInterpretation);
    if (result.good())
    {
        imageBytesAllocated = OFstatic_cast(Uint16, imageBitsAllocated / 8);
        if ((imageBitsAllocated < 8)||(imageBitsAllocated % 8 != 0)) return EC_CannotChangeRepresentation;
    }
    if (result.good() && (imageSamplesPerPixel > 1))
    {
        result = ditem->findAndGetUint16(DCM_PlanarConfiguration, imagePlanarConfiguration);
    }

    // number of frames is an optional attribute - we don't mind if it isn't present.
    if (result.good()) (void) ditem->findAndGetSint32(DCM_NumberOfFrames, imageFrames);
    if (imageFrames < 1) imageFrames = 1; // default in case this attribute contains garbage

    if (result.bad())
       return result;

    DcmPixelItem *pixItem = NULL;
    Uint8 * rleData = NULL;
    const size_t bytesPerStripe = imageColumns * imageRows;
    Uint32 numberOfStripes = 0;
    Uint32 fragmentLength = 0;
    Uint32 i;
    Uint32 frameSize = imageBytesAllocated * imageRows * imageColumns * imageSamplesPerPixel;

    if (frameSize > bufSize) return EC_IllegalCall;

    DcmRLEDecoder rledecoder(bytesPerStripe);
    if (rledecoder.fail()) return EC_MemoryExhausted;  // RLE decoder failed to initialize

    DCMDATA_DEBUG("RLE decoder processes frame " << frameNo);

    // determine the corresponding item (first fragment) for this frame
    Uint32 currentItem = startFragment;

    // 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.good())
    {
        result = determineStartFragment(frameNo, imageFrames, fromPixSeq, currentItem);
        if (result.bad())
            return result;
    }

    DCMDATA_DEBUG("RLE decoder processes pixel item " << currentItem);
    // now access and decompress the frame starting at the item we have identified
    result = fromPixSeq->getItem(pixItem, currentItem);
    if (result.bad())
       return result;

    fragmentLength = pixItem->getLength();
    result = pixItem->getUint8Array(rleData);
    if (result.bad())
       return result;

    // copy RLE header to buffer and adjust byte order
    memcpy(rleHeader, rleData, 64);
    swapIfNecessary(gLocalByteOrder, EBO_LittleEndian, rleHeader, 16*sizeof(Uint32), sizeof(Uint32));

    // determine number of stripes.
    numberOfStripes = rleHeader[0];

    // check that number of stripes in RLE header matches our expectation
    if ((numberOfStripes < 1) || (numberOfStripes > 15) || (numberOfStripes != OFstatic_cast(Uint32, imageBytesAllocated) * imageSamplesPerPixel))
        return EC_CannotChangeRepresentation;

    // this variable keeps the current position within the current fragment
    Uint32 byteOffset = 0;

    OFBool lastStripe = OFFalse;
    Uint32 inputBytes = 0;

    // pointers for buffer copy operations
    Uint8 *outputBuffer = NULL;
    Uint8 *pixelPointer = NULL;
    Uint16 *imageData16 = OFreinterpret_cast(Uint16 *, buffer);
    Uint8 *imageData8 = OFreinterpret_cast(Uint8 *, buffer);

    // byte offset for first sample in frame
    Uint32 sampleOffset = 0;

    // byte offset between samples
    Uint32 offsetBetweenSamples = 0;

    // temporary variables
    Uint32 sample = 0;
    Uint32 byte = 0;
    register Uint32 pixel = 0;
    size_t bytesToDecode;

    // for each stripe in stripe set
    for (i = 0; i < numberOfStripes; ++i)
    {
        // reset RLE codec
        rledecoder.clear();

        // adjust start point for RLE stripe
        byteOffset = rleHeader[i+1];

        // byteOffset now points to the first byte of the new RLE stripe
        // check if the current stripe is the last one for this frame
        if (i+1 == numberOfStripes) lastStripe = OFTrue; else lastStripe = OFFalse;

        if (lastStripe)
        {
            // the last stripe needs special handling because we cannot use the
            // offset table to determine the number of bytes to feed to the codec
            // if the RLE data is split in multiple fragments. We need to feed
            // data fragment by fragment until the RLE codec has produced
            // sufficient output.
            bytesToDecode = OFstatic_cast(size_t, fragmentLength - byteOffset);
        }
        else
        {
            // not the last stripe. We can use the offset table to determine
            // the number of bytes to feed to the RLE codec.
            inputBytes = rleHeader[i+2];
            if (inputBytes < rleHeader[i+1]) return EC_CannotChangeRepresentation;

            inputBytes -= rleHeader[i+1]; // number of bytes to feed to codec

            bytesToDecode = OFstatic_cast(size_t, inputBytes);
        }

        // last fragment for this RLE stripe
        result = rledecoder.decompress(rleData + byteOffset, bytesToDecode);

        // special handling for zero pad byte at the end of the RLE stream
        // which results in an EC_StreamNotifyClient return code
        // or trailing garbage data which results in EC_CorruptedData
        if (rledecoder.size() == bytesPerStripe) result = EC_Normal;

        byteOffset += inputBytes;

        // copy the decoded stuff over to the buffer here...
        // make sure the RLE decoder has produced the right amount of data
        if (lastStripe && (rledecoder.size() < bytesPerStripe))
        {
            // stream ended premature? report a warning and continue
            if (result == EC_StreamNotifyClient)
            {
                DCMDATA_WARN("RLE decoder is finished but has produced insufficient data for this stripe, filling remaining pixels");
                result = EC_Normal;
            }
        }
        else if (rledecoder.size() != bytesPerStripe)
        {
            DCMDATA_ERROR("RLE decoder is finished but has produced insufficient data for this stripe");
            return EC_CannotChangeRepresentation;
        }

        // distribute decompressed bytes into output image array
        // which sample and byte are we currently decompressing?
        sample = i / imageBytesAllocated;
        byte = i % imageBytesAllocated;

        // raw buffer containing bytesPerStripe bytes of uncompressed data
        outputBuffer = OFstatic_cast(Uint8 *, rledecoder.getOutputBuffer());

        // compute byte offsets
        if (imagePlanarConfiguration == 0)
        {
            sampleOffset = sample * imageBytesAllocated;
            offsetBetweenSamples = imageSamplesPerPixel * imageBytesAllocated;
        }
        else
        {
            sampleOffset = sample * imageBytesAllocated * imageColumns * imageRows;
            offsetBetweenSamples = imageBytesAllocated;
        }

        // initialize pointer to output data
        if (enableReverseByteOrder)
        {
            // assume incorrect LSB to MSB order of RLE segments as produced by some tools
            pixelPointer = imageData8 + sampleOffset + byte;
        }
        else
        {
            pixelPointer = imageData8 + sampleOffset + imageBytesAllocated - byte - 1;
        }

        // copy the pixel data that was decoded
        const size_t decoderSize = rledecoder.size();
        for (pixel = 0; pixel < decoderSize; ++pixel)
        {
            *pixelPointer = *outputBuffer++;
            pixelPointer += offsetBetweenSamples;
        }
        // and fill the remainder of the image with copies of the last decoded pixel
        const Uint8 lastPixelValue = *(outputBuffer - 1);
        for (pixel = decoderSize; pixel < bytesPerStripe; ++pixel)
        {
            *pixelPointer = lastPixelValue;
            pixelPointer += offsetBetweenSamples;
        }
    }

    /* remove used fragment from memory */
    pixItem->compact(); // there should only be one...

    if (result.good())
    {
      // compression was successful. Now update output parameters
      startFragment = currentItem + 1;
      decompressedColorModel = photometricInterpretation;
    }

    // adjust byte order for uncompressed image to little endian
    swapIfNecessary(EBO_LittleEndian, gLocalByteOrder, imageData16, frameSize, sizeof(Uint16));

    return result;
}


OFCondition DcmRLECodecDecoder::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 DcmRLECodecDecoder::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 DcmRLECodecDecoder::determineDecompressedColorModel(
    const DcmRepresentationParameter * /* fromParam */,
    DcmPixelSequence * /* fromPixSeq */,
    const DcmCodecParameter * /* cp */,
    DcmItem *dataset,
    OFString &decompressedColorModel) const
{
    OFCondition result = EC_InvalidTag;
    if ((dataset != NULL ) && ((dataset->ident() == EVR_dataset) || (dataset->ident() == EVR_item)))
    {
        // retrieve color model from given dataset
        result = dataset->findAndGetOFString(DCM_PhotometricInterpretation, decompressedColorModel);
    }
    return result;
}


/*
 * CVS/RCS Log
 * $Log: dcrleccd.cc,v $
 * Revision 1.18  2010-11-01 10:42:44  uli
 * Fixed some compiler warnings reported by gcc with additional flags.
 *
 * Revision 1.17  2010-10-14 13:14:09  joergr
 * Updated copyright header. Added reference to COPYRIGHT file.
 *
 * Revision 1.16  2010-10-01 10:21:05  uli
 * Fixed most compiler warnings from -Wall -Wextra -pedantic in dcmdata.
 *
 * Revision 1.15  2010-05-27 16:52:32  joergr
 * Re-added comment that was accidentally removed by the last commit.
 *
 * Revision 1.14  2010-05-21 14:02:48  joergr
 * Fixed issue with incorrectly encoded RLE images: Now, if the RLE decoder is
 * finished but has produced insufficient data, the remaining pixels of the
 * image are filled with the value of the last pixel. Applies to decodeFrame().
 * Added useful log messages on various levels to decode() and decodeFrame().
 *
 * Revision 1.13  2009-11-17 16:41:26  joergr
 * Added new method that allows for determining the color model of the
 * decompressed image.
 *
 * Revision 1.12  2009-11-04 09:58:10  uli
 * Switched to logging mechanism provided by the "new" oflog module
 *
 * Revision 1.11  2009-08-10 11:27:00  meichel
 * Added working implementation of DcmRLECodecDecoder::decodeFrame().
 *
 * Revision 1.10  2009-08-10 09:38:06  meichel
 * All decompression codecs now replace NumberOfFrames if larger than one
 *   or present in the original image.
 *
 * Revision 1.9  2008-08-15 09:18:13  meichel
 * Decoder now gracefully handles the case of faulty images where value of
 *   NumberOfFrames is larger than the number of compressed fragments, if and only
 *   if there is just a single fragment per frame.
 *
 * Revision 1.8  2008-05-29 10:46:16  meichel
 * Implemented new method DcmPixelData::getUncompressedFrame
 *   that permits frame-wise access to compressed and uncompressed
 *   objects without ever loading the complete object into main memory.
 *   For this new method to work with compressed images, all classes derived from
 *   DcmCodec need to implement a new method decodeFrame(). For now, only
 *   dummy implementations returning an error code have been defined.
 *
 * Revision 1.7  2005/12/08 15:41:29  meichel
 * Changed include path schema for all DCMTK header files
 *
 * Revision 1.6  2005/07/26 17:08:35  meichel
 * Added option to RLE decoder that allows to correctly decode images with
 *   incorrect byte order of byte segments (LSB instead of MSB).
 *
 * Revision 1.5  2004/08/24 14:54:20  meichel
 *  Updated compression helper methods. Image type is not set to SECONDARY
 *   any more, support for the purpose of reference code sequence added.
 *
 * Revision 1.4  2003/08/14 09:01:06  meichel
 * Adapted type casts to new-style typecast operators defined in ofcast.h
 *
 * Revision 1.3  2003/03/21 13:08:04  meichel
 * Minor code purifications for warnings reported by MSVC in Level 4
 *
 * Revision 1.2  2002/07/18 12:15:39  joergr
 * Added explicit type casts to keep Sun CC 2.0.1 quiet.
 *
 * Revision 1.1  2002/06/06 14:52:40  meichel
 * Initial release of the new RLE codec classes
 *   and the dcmcrle/dcmdrle tools in module dcmdata
 *
 *
 */