summaryrefslogtreecommitdiff
blob: aa0d11318991f015cd280c0b1379c66c320ef9fd (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
/* Copyright (C) 2001-2020 Artifex Software, Inc.
   All Rights Reserved.

   This software is provided AS-IS with no warranty, either express or
   implied.

   This software is distributed under license and may not be copied,
   modified or distributed except as expressly authorized under the terms
   of the license contained in the file LICENSE in this distribution.

   Refer to licensing information at http://www.artifex.com or contact
   Artifex Software, Inc.,  1305 Grant Avenue - Suite 200, Novato,
   CA 94945, U.S.A., +1(415)492-9861, for further information.
*/


/* JPXDecode filter implementation -- hooks in the Luratech JPEG2K CSDK */

#include "memory_.h"
#include "gserrors.h"
#include "gdebug.h"
#include "strimpl.h"
#include "sjpx_luratech.h"

#include <lwf_jp2.h>

/* JPXDecode stream implementation using the Luratech library */

/* if linking against a SDK build that requires a separate license key,
   you can change the following undefs to defines and set them here. */
/***
#ifndef JP2_LICENSE_NUM_1
# undef JP2_LICENSE_NUM_1
#endif
#ifndef JP2_LICENSE_NUM_2
# undef JP2_LICENSE_NUM_2
#endif
***/

private_st_jpxd_state(); /* creates a gc object for our state,
                            defined in sjpx.h */

#define JPX_BUFFER_SIZE 1024

/** callback for the codec library */

/* memory allocation */
static void * JP2_Callback_Conv
s_jpx_alloc(long size, JP2_Callback_Param param)
{
	return gs_alloc_byte_array((gs_memory_t *)param, size, 1, "s_jpx_alloc");
}

/* memory free */
static JP2_Error JP2_Callback_Conv
s_jpx_free(void *ptr, JP2_Callback_Param param)
{
	gs_free_object((gs_memory_t *)param, ptr, "s_jpx_free");
    return cJP2_Error_OK;
}

/* pass any available input to the library */
static unsigned long JP2_Callback_Conv
s_jpxd_read_data(unsigned char *pucData,
                            unsigned long ulPos, unsigned long ulSize,
                            JP2_Callback_Param param)
{
    stream_jpxd_state *const state = (stream_jpxd_state *) param;
    unsigned long copy_bytes = min(ulSize, state->inbuf_fill - ulPos);

    memcpy(pucData, state->inbuf + ulPos, copy_bytes);

    return copy_bytes;
}

static unsigned long
jp2_get_value(JP2_Decomp_Handle *handle,
              JP2_Property_Tag tag,
              short comp,
              unsigned long def)
{
    JP2_Property_Value v;

    if (JP2_Decompress_GetProp(handle, tag, &v, -1, comp) != cJP2_Error_OK)
        return def;

    return (unsigned long)v;
}

/* write decompressed data into our image buffer */
static JP2_Error JP2_Callback_Conv
s_jpxd_write_data(unsigned char * pucData,
                               short sComponent,
                               unsigned long ulRow,
                               unsigned long ulStart,
                               unsigned long ulNum,
                               JP2_Callback_Param param)
{
    stream_jpxd_state *const state = (stream_jpxd_state *) param;
    int comp = state->clut[sComponent];

    /* check input */
    if (ulRow >= state->height) return cJP2_Error_Invalid_Height;
    if (ulStart + ulNum >= state->width) ulNum = state->width - ulStart;

    /* Here we just copy a byte at a time into an image buffer,
       interleaving with whatever data already exists. For multi-
       component images, it would be more efficient to save rows
       from each call in planar buffers and interleave a tile at
       a time into a stipe buffer for output */

    if (state->image_is_indexed && sComponent == 0 && !state->alpha) {
        JP2_Palette_Params *pal;
        JP2_Error err;
        int i, c;
        unsigned char *dst;

        err = JP2_Decompress_GetPalette(state->handle, &pal);
        if (err != cJP2_Error_OK)
            return err;

        if (state->colorspace != gs_jpx_cs_indexed) {
            dst = &state->image[state->stride * ulRow +
                            state->ncomp * ulStart + comp];
            /* expand the data */
            for (i = 0; i < ulNum; i++) {
                unsigned char v = pucData[i];

                if (v >= pal->ulEntries)
                    return cJP2_Error_Invalid_Colorspace;

                for (c = 0; c < state->ncomp; c++)
                    *dst++ = (unsigned char)pal->ppulPalette[c][v];
            }
        } else {
            /* copy indexes */
            if (state->bpc == 4) {
                int even = ulNum & ~1;
                dst = &state->image[state->stride * ulRow + ulStart/2];
                for (i = 0; i < even; i += 2)
                    *dst++ = pucData[i] << 4 | pucData[i+1];
                if (ulNum & 1)
                    *dst++ = pucData[ulNum - 1] << 4;
            } else {
                dst = &state->image[state->stride * ulRow + ulStart + comp];
                memcpy(dst, pucData, ulNum);
            }
        }
    } else if (state->ncomp == 1 && comp == 0) {
        if (state->bpc == 8) {
            memcpy(&state->image[state->stride*ulRow + state->ncomp*ulStart],
                   pucData, ulNum);
        }  else if (state->bpc > 8) {
            unsigned long i;
            unsigned short *src = (unsigned short *)pucData;
            unsigned char *dst = &state->image[state->stride * ulRow + 2 * ulStart];
            unsigned int shift = 16 - state->bpc;
            for (i = 0; i < ulNum; i++) {
                unsigned short v = *src++ << shift;
                *dst++ = (v >> 8) & 0xff;
                *dst++ = v & 0xff;
            }
        } else if (state->bpc == 4) {
            int i;
            unsigned char *dst = &state->image[state->stride * ulRow + ulStart/2];
            int even = ulNum & ~1;

            for (i = 0; i < even; i+=2)
                *dst++ = pucData[i] << 4 | pucData[i+1];
                if (ulNum & 1)
                    *dst++ = pucData[ulNum - 1] << 4;
        } else
        {
            unsigned int bt=0; unsigned long i;
            int bit_pos = state->bpc * ulStart; /* starting bit position to fill for this component */
            int bit_cnt; /* bit count for current byte */
            unsigned char *p = &state->image[state->stride * ulRow + bit_pos/8]; /* starting byte to fill */;
            bit_cnt = bit_pos % 8;
            for (i = 0; i < ulNum; i++)
            {
                bt <<= state->bpc;
                bt |= pucData[i];
                bit_cnt += state->bpc;
                if (bit_cnt >= 8)
                {
                    *(p++) |= bt >> (bit_cnt-8);
                    bit_cnt -= 8;
                    bt &= (1<<bit_cnt)-1;
                 }
            }
            /* end of row */
            if (bit_cnt > 0)
            {
                *p |= bt<<(8-bit_cnt);
                bt = 0;
            }
         }
    }
    else if (comp >= 0) {
        unsigned long cw, ch, i, hstep, vstep, x, y;
        unsigned char *row;

        /* repeat subsampled pixels */
        cw = jp2_get_value(state->handle, cJP2_Prop_Width, comp, state->width);
        ch = jp2_get_value(state->handle, cJP2_Prop_Height, comp, state->height);
        hstep = state->width / cw;
        vstep = state->height / ch;

        if (state->bpc == 8) {
            row = &state->image[state->stride * ulRow * vstep +
                                state->ncomp * ulStart * hstep + comp];
            for (y = 0; y < vstep; y++) {
                unsigned char *p = row;
                for (i = 0; i < ulNum; i++)
                    for (x = 0; x < hstep; x++) {
                        *p = pucData[i];
                        p += state->ncomp;
                    }
                row += state->stride;
            }
        } else if (state->bpc > 8) {
            int shift = 16 - state->bpc;
            unsigned short *src = (unsigned short *)pucData;
            row = &state->image[state->stride * ulRow * vstep +
                                2 * state->ncomp * ulStart * hstep + 2 * comp];
            for (y = 0; y < vstep; y++) {
                unsigned char *p = row;
                for (i = 0; i < ulNum; i++)
                    for (x = 0; x < hstep; x++) {
                        unsigned short v = *src++ << shift;
                        p[0] = (v >> 8) & 0xff;
                        p[1] = v & 0xff;
                        p += 2 * state->ncomp;
                    }
                row += state->stride;
            }
        } else {
            unsigned int bt=0;
            int bit_pos = state->bpc * state->ncomp * ulStart * hstep + state->bpc * comp; /* starting bit position to fill for this component */
            int bit_cnt; /* bit count for current byte */

            row = &state->image[state->stride * ulRow * vstep + bit_pos/8]; /* starting byte to fill */
            for (y = 0; y < vstep; y++) {
                unsigned char *p = row;
                bit_cnt = bit_pos % 8;
                for (i = 0; i < ulNum; i++) {
                    for (x = 0; x < hstep; x++) {
                        bt <<= state->bpc * state->ncomp;
                        bt |= pucData[i];
                        bit_cnt += state->bpc;
                        while (bit_cnt >= 8) {
                            *(p++) |= bt >> (bit_cnt-8);
                            bit_cnt -= 8;
                            bt &= (1<<bit_cnt)-1;
                        }
                        bit_cnt += state->bpc * (state->ncomp - 1); /* skip other components */
                    }
                }
                /* end of row */
                bit_cnt -= state->bpc * (state->ncomp - 1); /* return the last extra count */
                if (bit_cnt > 0) {
                    *p |= bt<<(8-bit_cnt);
                    bt = 0;
                }
                row += state->stride;
            }
        }
    }
    return cJP2_Error_OK;
}

/* convert state->image from YCrCb to RGBa */
static int
s_jpxd_ycc_to_rgb(stream_jpxd_state *state)
{
    int i, y, x;
    int is_signed[2];  /* Cr, Cb */

    if (state->ncomp != 3)
        return -1;

    for (i = 0; i < 2; i++) {
        int comp = state->clut[i + 1];  /* skip Y */
        is_signed[i] = !jp2_get_value(state->handle,
                                   cJP2_Prop_Signed_Samples, comp, 0);
    }

    for (y = 0; y < state->height; y++) {
        unsigned char *row = &state->image[y * state->stride];

        for (x = 0; x < state->stride; x += 3) {
            int p[3], q[3];

            for (i = 0; i < 3; i++)
                p[i] = (int)row[x + i];

            if (is_signed[0])
                p[1] -= 0x80;
            if (is_signed[1])
                p[2] -= 0x80;

            /* rotate to RGB */
#ifdef JPX_USE_IRT
            q[1] = p[0] - ((p[1] + p[2])>>2);
            q[0] = p[1] + q[1];
            q[2] = p[2] + q[1];
#else
            q[0] = (int)((double)p[0] + 1.402 * p[2]);
            q[1] = (int)((double)p[0] - 0.34413 * p[1] - 0.71414 * p[2]);
            q[2] = (int)((double)p[0] + 1.772 * p[1]);
#endif
            /* clamp */
            for (i = 0; i < 3; i++){
                if (q[i] < 0) q[i] = 0;
                else if (q[i] > 0xFF) q[i] = 0xFF;
            }
            /* write out the pixel */
            for (i = 0; i < 3; i++)
                row[x + i] = (unsigned char)q[i];
        }
    }

    return 0;
}

static int
s_jpxd_inbuf(stream_jpxd_state *state, stream_cursor_read * pr)
{
    long in_size = pr->limit - pr->ptr;

    /* allocate the input buffer if needed */
    if (state->inbuf == NULL) {
        state->inbuf = s_jpx_alloc(JPX_BUFFER_SIZE, (JP2_Callback_Param)state->memory->non_gc_memory);
        if (state->inbuf == NULL) return_error(gs_error_VMerror);
        state->inbuf_size = JPX_BUFFER_SIZE;
        state->inbuf_fill = 0;
    }

    /* grow the input buffer if needed */
    if (state->inbuf_size < state->inbuf_fill + in_size) {
        unsigned char *new;
        unsigned long new_size = state->inbuf_size;

        while (new_size < state->inbuf_fill + in_size)
            new_size = new_size << 1;

        if_debug1m('s', state->memory, "[s]jpxd growing input buffer to %lu bytes\n",
                   new_size);

        new = gs_resize_object(state->memory->non_gc_memory, state->inbuf, new_size, "s_jpxd_inbuf");
        if (new == NULL) return_error(gs_error_VMerror);

        state->inbuf = new;
        state->inbuf_size = new_size;
    }

    /* copy the available input into our buffer */
    /* note that the gs stream library uses offset-by-one
        indexing of its buffers while we use zero indexing */
    memcpy(state->inbuf + state->inbuf_fill, pr->ptr + 1, in_size);
    state->inbuf_fill += in_size;
    pr->ptr += in_size;

    return 0;
}

/* initialize the steam.
   this involves allocating the stream and image structures, and
   initializing the decoder.
 */
static int
s_jpxd_init(stream_state * ss)
{
    stream_jpxd_state *const state = (stream_jpxd_state *) ss;

    state->handle = (JP2_Decomp_Handle)NULL;
    state->inbuf = NULL;
    state->inbuf_size = 0;
    state->inbuf_fill = 0;

    state->ncomp = 0;
    state->bpc = 0;
    state->clut = NULL;
    state->width = 0;
    state->height = 0;
    state->stride = 0;
    state->image = NULL;
    state->offset = 0;

    return 0;
}

/* Set the defaults */
static void
s_jpxd_set_defaults(stream_state * ss) {
    stream_jpxd_state *const state = (stream_jpxd_state *) ss;

    state->alpha = false;
    state->image_is_indexed = false;
    state->colorspace = gs_jpx_cs_rgb;
}

/* write component mapping into 'clut' and return number of used components
 */
static int
map_components(JP2_Channel_Def_Params *chans, int nchans, int alpha, int clut[])
{
    int i, cnt = 0;

    for (i = 0; i < nchans; i++)
        clut[i] = -1;

    /* always write the alpha channel as first component */
    if (alpha) {
        for (i = 0; i < nchans; i++) {
            if (chans[i].ulType == cJP2_Channel_Type_Opacity) {
                clut[i] = 0;
                cnt++;
                break;
            }
        }
    } else {
        for (i = 0; i < nchans; i++) {
            if (chans[i].ulType == cJP2_Channel_Type_Color) {
                int assoc = chans[i].ulAssociated -1;
                if (assoc >= nchans)
                    return -1;
                clut[i] = assoc;
                cnt++;
            }
        }
    }
    return cnt;
}

/* process a secton of the input and return any decoded data.
   see strimpl.h for return codes.
 */
static int
s_jpxd_process(stream_state * ss, stream_cursor_read * pr,
                 stream_cursor_write * pw, bool last)
{
    stream_jpxd_state *const state = (stream_jpxd_state *) ss;
    JP2_Error err;
    JP2_Property_Value result;
    long in_size = pr->limit - pr->ptr;
    long out_size = pw->limit - pw->ptr;
    JP2_Colorspace image_cs = cJP2_Colorspace_RGBa;

    if (in_size > 0) {
        /* buffer available data */
        s_jpxd_inbuf(state, pr);
    }

    if (last == 1) {
        /* we have all the data, decode and return */

        if (state->handle == (JP2_Decomp_Handle)NULL) {
            int ncomp;
            /* initialize decompressor */
            err = JP2_Decompress_Start(&state->handle,
                /* memory allocator callbacks */
                s_jpx_alloc, (JP2_Callback_Param)state->memory->non_gc_memory,
                s_jpx_free,  (JP2_Callback_Param)state->memory->non_gc_memory,
                /* our read callback */
                s_jpxd_read_data, (JP2_Callback_Param)state
            );
            if (err != cJP2_Error_OK) {
                dmlprintf1(state->memory, "Luratech JP2 error %d starting decompression\n", (int)err);
                return ERRC;
            }
#if defined(JP2_LICENSE_NUM_1) && defined(JP2_LICENSE_NUM_2)
            /* set the license keys if appropriate */
            err = JP2_Decompress_SetLicense(state->handle,
                JP2_LICENSE_NUM_1, JP2_LICENSE_NUM_2);
            if (err != cJP2_Error_OK) {
                dmlprintf1(state->memory, "Luratech JP2 error %d setting license\n", (int)err);
                return ERRC;
            }
#endif
            /* parse image parameters */
            err = JP2_Decompress_GetProp(state->handle,
                cJP2_Prop_Components, &result, -1, -1);
            if (err != cJP2_Error_OK) {
                dmlprintf1(state->memory, "Luratech JP2 error %d decoding number of image components\n", (int)err);
                return ERRC;
            }
            ncomp = result;

            {
                JP2_Channel_Def_Params *chans = NULL;
                unsigned long nchans = 0;
                err = JP2_Decompress_GetChannelDefs(state->handle, &chans, &nchans);
                if (err != cJP2_Error_OK) {
                    dmlprintf1(state->memory, "Luratech JP2 error %d reading channel definitions\n", (int)err);
                    return ERRC;
                }
                state->clut = s_jpx_alloc(nchans * sizeof(int), (JP2_Callback_Param)state->memory->non_gc_memory);
                state->ncomp = map_components(chans, nchans, state->alpha, state->clut);
                if (state->ncomp < 0) {
                    dmlprintf(state->memory, "Luratech JP2 error decoding channel definitions\n");
                    return ERRC;
                }
            }

            if_debug1m('w', state->memory, "[w]jpxd image has %d components\n", state->ncomp);

            state->bpc = 0;
            {
                const char *cspace = "unknown";
                err = JP2_Decompress_GetProp(state->handle,
                        cJP2_Prop_Extern_Colorspace, &result, -1, -1);
                if (err != cJP2_Error_OK) {
                    dmlprintf1(state->memory, "Luratech JP2 error %d decoding colorspace\n", (int)err);
                    return ERRC;
                }
                image_cs = (JP2_Colorspace)result;
                switch (result) {
                    case cJP2_Colorspace_Gray:
                        cspace = "gray";
                        state->colorspace = gs_jpx_cs_gray;
                        break;
                    case cJP2_Colorspace_RGBa:
                        cspace = "sRGB";
                        state->colorspace = gs_jpx_cs_rgb;
                        break;
                    case cJP2_Colorspace_RGB_YCCa:
                        cspace = "sRGB YCrCb"; break;
                        state->colorspace = gs_jpx_cs_rgb;
                        break;
                    case cJP2_Colorspace_CIE_LABa:
                        cspace = "CIE Lab";
                        state->colorspace = gs_jpx_cs_rgb;
                        break;
                    case cJP2_Colorspace_ICCa:
                        cspace = "ICC profile";
                        state->colorspace = gs_jpx_cs_rgb;
                        break;
                    case cJP2_Colorspace_Palette_Gray:
                        cspace = "indexed gray";
                        state->image_is_indexed = true;
                        break;
                    case cJP2_Colorspace_Palette_RGBa:
                        cspace = "indexed sRGB";
                        state->image_is_indexed = true;
                        if (state->colorspace != gs_jpx_cs_indexed)
                            state->bpc = 8;
                        break;
                    case cJP2_Colorspace_Palette_RGB_YCCa:
                        cspace = "indexed sRGB YCrCb";
                        state->image_is_indexed = true;
                        break;
                    case cJP2_Colorspace_Palette_CIE_LABa:
                        cspace = "indexed CIE Lab";
                        state->image_is_indexed = true;
                        break;
                    case cJP2_Colorspace_Palette_ICCa:
                        cspace = "indexed with ICC profile";
                        state->image_is_indexed = true;
                        break;
                    case cJP2_Colorspace_CMYKa:
                        cspace = "CMYK";
                        state->colorspace = gs_jpx_cs_cmyk;
                        break;
                    case cJP2_Colorspace_Palette_CMYKa:
                        cspace = "indexed CMYK";
                        state->image_is_indexed = true;
                        break;
                }
                if_debug1m('w', state->memory, "[w]jpxd image colorspace is %s\n", cspace);
            }

            /* the library doesn't return the overall image dimensions
               or depth, so we take the maximum of the component values */
            state->width = 0;
            state->height = 0;
            {
                int comp;
                int width, height;
                int bits, is_signed;
                for (comp = 0; comp < ncomp; comp++) {
                    err= JP2_Decompress_GetProp(state->handle,
                        cJP2_Prop_Width, &result, -1, (short)comp);
                    if (err != cJP2_Error_OK) {
                        dmlprintf2(state->memory, "Luratech JP2 error %d decoding "
                                   "width for component %d\n", (int)err, comp);
                        return ERRC;
                    }
                    width = result;
                    err= JP2_Decompress_GetProp(state->handle,
                        cJP2_Prop_Height, &result, -1, (short)comp);
                    if (err != cJP2_Error_OK) {
                        dmlprintf2(state->memory, "Luratech JP2 error %d decoding "
                                   "height for component %d\n", (int)err, comp);
                        return ERRC;
                    }
                    height = result;
                    err= JP2_Decompress_GetProp(state->handle,
                        cJP2_Prop_Bits_Per_Sample, &result, -1, (short)comp);
                    if (err != cJP2_Error_OK) {
                        dmlprintf2(state->memory, "Luratech JP2 error %d decoding "
                                   "bits per sample for component %d\n", (int)err, comp);
                        return ERRC;
                    }
                    bits = result;
                    err= JP2_Decompress_GetProp(state->handle,
                        cJP2_Prop_Signed_Samples, &result, -1, (short)comp);
                    if (err != cJP2_Error_OK) {
                        dmlprintf2(state->memory, "Luratech JP2 error %d decoding "
                                   "signedness of component %d\n", (int)err, comp);
                        return ERRC;
                    }
                    is_signed = result;
                    if_debug5m('w', state->memory,
                        "[w]jpxd image component %d has %dx%d %s %d bit samples\n",
                        comp, width, height,
                        is_signed ? "signed" : "unsigned", bits);

                    /* update image maximums */
                    if (state->width < width) state->width = width;
                    if (state->height < height) state->height = height;
                    if (state->bpc < bits) state->bpc = bits;
                }
            }
            if_debug3m('w', state->memory, "[w]jpxd decoding image at %ldx%ld"
                       " with %d bits per component\n",
                       state->width, state->height, state->bpc);
        }

        if (state->handle != (JP2_Decomp_Handle)NULL &&
                state->image == NULL) {

            /* allocate our output buffer */
            int real_bpc = state->bpc > 8 ? 16 : state->bpc;
            if (state->image_is_indexed && state->colorspace == gs_jpx_cs_indexed) {
                /* Don't expand indexed color space */
                state->stride = (state->width * real_bpc + 7) / 8;
                state->image = s_jpx_alloc(state->stride*state->height, (JP2_Callback_Param)state->memory->non_gc_memory);
            } else {
                state->stride = (state->width * max(1, state->ncomp) * real_bpc + 7) / 8;
                state->image = s_jpx_alloc(state->stride*state->height, (JP2_Callback_Param)state->memory->non_gc_memory);
            }
            if (state->image == NULL)
                return ERRC;
            if (state->ncomp == 0) /* make fully opaque mask */
                memset(state->image, 255, state->stride*state->height);

            /* attach our output callback */
            err = JP2_Decompress_SetProp(state->handle,
                cJP2_Prop_Output_Parameter, (JP2_Property_Value)state);
            if (err != cJP2_Error_OK) {
                dmlprintf1(state->memory, "Luratech JP2 error %d setting output parameter\n", (int)err);
                return ERRC;
            }
            err = JP2_Decompress_SetProp(state->handle,
                cJP2_Prop_Output_Function,
                (JP2_Property_Value)s_jpxd_write_data);
            if (err != cJP2_Error_OK) {
                dmlprintf1(state->memory, "Luratech JP2 error %d setting output function\n", (int)err);
                return ERRC;
            }

            /* decompress the image */
            err = JP2_Decompress_Image(state->handle);
            if (err != cJP2_Error_OK) {
                dmlprintf1(state->memory, "Luratech JP2 error %d decoding image data\n", (int)err);
                return ERRC; /* parsing error */
            }

            if (image_cs == cJP2_Colorspace_RGB_YCCa) {
                s_jpxd_ycc_to_rgb(state);
            }
        }

        /* copy out available data */
        if (state->image != NULL && out_size > 0) {
            /* copy some output data */
            long available = min(out_size,
                state->stride*state->height - state->offset);
            memcpy(pw->ptr + 1, state->image + state->offset, available);
            state->offset += available;
            pw->ptr += available;
            /* more output to deliver? */
            if (state->offset == state->stride*state->height)
                return EOFC;
            else
                return 1;
        }
    }

    /* ask for more data */
    return 0;
}

/* stream release.
   free all our decoder state.
 */
static void
s_jpxd_release(stream_state *ss)
{
    stream_jpxd_state *const state = (stream_jpxd_state *) ss;

    if (state) {
        JP2_Decompress_End(state->handle);
        if (state->inbuf)
        	gs_free_object(state->memory->non_gc_memory, state->inbuf, "s_jpxd_release.1");
        if (state->image)
    	    gs_free_object(state->memory->non_gc_memory, state->image, "s_jpxd_release.2");
        if (state->clut)
    	    gs_free_object(state->memory->non_gc_memory, state->clut, "s_jpxd_release.3");
    }
}

/* stream template */
const stream_template s_jpxd_template = {
    &st_jpxd_state,
    s_jpxd_init,
    s_jpxd_process,
    1024, 1024,   /* min in and out buffer sizes we can handle
                     should be ~32k,64k for efficiency? */
    s_jpxd_release,
    s_jpxd_set_defaults,
    0
};

/*** encode support **/

/* we provide a C-only encode filter for generating JPX image data
   for embedding in PDF. */

/* create a gc object for our state, defined in sjpx_luratech.h */
private_st_jpxe_state();

/* callback for uncompressed data input */
static JP2_Error JP2_Callback_Conv
s_jpxe_read(unsigned char *buffer, short component,
                unsigned long row, unsigned long start,
                unsigned long num, JP2_Callback_Param param)
{
    stream_jpxe_state *state = (stream_jpxe_state *)param;
    unsigned long available, sentinel;
    unsigned char *p;
    int i;

    if (component < 0 || component >= state->components) {
        dmlprintf2(state->memory,
                   "Luratech JP2 requested image data for unknown component %d of %u\n",
                   (int)component, state->components);
        return cJP2_Error_Invalid_Component_Index;
    }

    /* todo: handle subsampled components and bpc != 8 */

    /* clip to array bounds */
    sentinel = row*state->stride + (start + num)*state->components;
    available = min(sentinel, state->infill);
    num = min(num, available / state->components);

    p = state->inbuf + state->stride*row + state->components*start;
    if (state->components == 1)
        memcpy(buffer, p, num);
    else for (i = 0; i < num; i++) {
        buffer[i] = p[component];
        p += state->components;
    }

    if (available < sentinel) return cJP2_Error_Failure_Read;
    else return cJP2_Error_OK;
}

/* callback for compressed data output */
static JP2_Error JP2_Callback_Conv
s_jpxe_write(unsigned char *buffer,
                unsigned long pos, unsigned long size,
                JP2_Callback_Param param)
{
    stream_jpxe_state *state = (stream_jpxe_state *)param;

    /* verify state */
    if (state == NULL) return cJP2_Error_Invalid_Pointer;

    /* allocate the output buffer if necessary */
    if (state->outbuf == NULL) {
        state->outbuf = s_jpx_alloc(JPX_BUFFER_SIZE, (JP2_Callback_Param)state->memory->non_gc_memory);
        if (state->outbuf == NULL) {
            dmprintf(state->memory, "jpx encode: failed to allocate output buffer.\n");
            return cJP2_Error_Failure_Malloc;
        }
        state->outsize = JPX_BUFFER_SIZE;
    }

    /* grow the output buffer if necessary */
    while (pos+size > state->outsize) {
        unsigned char *new = gs_resize_object(state->memory->non_gc_memory, state->outbuf, state->outsize*2, "s_jpxe_write");

        if (new == NULL) {
            dmprintf1(state->memory, "jpx encode: failed to resize output buffer"
                " beyond %lu bytes.\n", state->outsize);
            return cJP2_Error_Failure_Malloc;
        }
        state->outbuf = new;
        state->outsize *= 2;
        if_debug1m('s', state->memory, "[s] jpxe output buffer resized to %lu bytes\n",
                   state->outsize);
    }

    /* copy data into our buffer; we've assured there is enough room. */
    memcpy(state->outbuf + pos, buffer, size);
    /* update high water mark */
    if (state->outfill < pos + size) state->outfill = pos + size;

    return cJP2_Error_OK;
}

/* set defaults for user-configurable parameters */
static void
s_jpxe_set_defaults(stream_state *ss)
{
    stream_jpxe_state *state = (stream_jpxe_state *)ss;

    /* most common default colorspace */
    state->colorspace = gs_jpx_cs_rgb;

    /* default to lossy 60% quality */
    state->lossless = 0;
    state->quality = 60;
}

/* initialize the stream */
static int
s_jpxe_init(stream_state *ss)
{
    stream_jpxe_state *state = (stream_jpxe_state *)ss;
    unsigned long value;
    JP2_Error err;

    /* width, height, bpc and colorspace are set by the client,
       calculate the rest */
    switch (state->colorspace) {
        case gs_jpx_cs_gray: state->components = 1; break;
        case gs_jpx_cs_rgb: state->components = 3; break;
        case gs_jpx_cs_cmyk: state->components = 4; break;
        default: state->components = 0; break;
    }
    state->stride = state->width * state->components;

    if_debug3m('w', state->memory, "[w] jpxe init %lux%lu image with %d components\n",
               state->width, state->height, state->components);
    if_debug1m('w', state->memory, "[w] jpxe init image is %d bits per component\n", state->bpc);

    if (state->lossless) {
        if_debug0m('w', state->memory, "[w] jpxe image using lossless encoding\n");
        state->quality = 100; /* implies lossless */
    } else {
        if_debug1m('w', state->memory, "[w] jpxe image quality level %d\n", state->quality);
    }

    /* null the input buffer */
    state->inbuf = NULL;
    state->insize = 0;
    state->infill = 0;

    /* null the output buffer */
    state->outbuf = NULL;
    state->outsize = 0;
    state->outfill = 0;
    state->offset = 0;

    /* initialize the encoder */
    err = JP2_Compress_Start(&state->handle,
        /* memory allocator callbacks */
        s_jpx_alloc, (JP2_Callback_Param)state->memory->non_gc_memory,
        s_jpx_free,  (JP2_Callback_Param)state->memory->non_gc_memory,
        state->components);
    if (err != cJP2_Error_OK) {
        dmlprintf1(state->memory, "Luratech JP2 error %d starting compressor\n", (int)err);
        return ERRC;
    }

#if defined(JP2_LICENSE_NUM_1) && defined(JP2_LICENSE_NUM_2)
    /* set license keys if appropriate */
    err = JP2_Compress_SetLicense(state->handle,
        JP2_LICENSE_NUM_1, JP2_LICENSE_NUM_2);
    if (err != cJP2_Error_OK) {
        dmlprintf1(state->memory, "Luratech JP2 error %d setting license\n", (int)err);
        return ERRC;
    }
#endif

    /* install our callbacks */
    err = JP2_Compress_SetProp(state->handle,
        cJP2_Prop_Input_Parameter, (JP2_Property_Value)state, -1, -1);
    if (err != cJP2_Error_OK) {
        dmlprintf1(state->memory, "Luratech JP2 error %d setting input callback parameter.\n", (int)err);
        return ERRC;
    }
    err = JP2_Compress_SetProp(state->handle,
        cJP2_Prop_Input_Function, (JP2_Property_Value)s_jpxe_read, -1, -1);
    if (err != cJP2_Error_OK) {
        dmlprintf1(state->memory, "Luratech JP2 error %d setting input callback function.\n", (int)err);
        return ERRC;
    }
    err = JP2_Compress_SetProp(state->handle,
        cJP2_Prop_Write_Parameter, (JP2_Property_Value)state, -1, -1);
    if (err != cJP2_Error_OK) {
        dmlprintf1(state->memory, "Luratech JP2 error %d setting compressed output callback parameter.\n", (int)err);
        return ERRC;
    }
    err = JP2_Compress_SetProp(state->handle,
        cJP2_Prop_Write_Function, (JP2_Property_Value)s_jpxe_write, -1, -1);
    if (err != cJP2_Error_OK) {
        dmlprintf1(state->memory, "Luratech JP2 error %d setting compressed output callback function.\n", (int)err);
        return ERRC;
    }

    /* set image parameters - the same for all components */
    err = JP2_Compress_SetProp(state->handle,
        cJP2_Prop_Width, state->width, -1, -1);
    if (err != cJP2_Error_OK) {
        dmlprintf1(state->memory, "Luratech JP2 error %d setting width\n", (int)err);
        return ERRC;
    }
    err = JP2_Compress_SetProp(state->handle,
        cJP2_Prop_Height, state->height, -1, -1);
    if (err != cJP2_Error_OK) {
        dmlprintf1(state->memory, "Luratech JP2 error %d setting height\n", (int)err);
        return ERRC;
    }
    err = JP2_Compress_SetProp(state->handle,
        cJP2_Prop_Bits_Per_Sample, state->bpc, -1, -1);
    if (err != cJP2_Error_OK) {
        dmlprintf1(state->memory, "Luratech JP2 error %d setting bits per sample\n", (int)err);
        return ERRC;
    }

    switch (state->colorspace) {
        case gs_jpx_cs_gray: value = cJP2_Colorspace_Gray; break;
        case gs_jpx_cs_rgb: value = cJP2_Colorspace_RGBa; break;
        case gs_jpx_cs_cmyk: value = cJP2_Colorspace_CMYKa; break;
        default:
            dmlprintf1(state->memory, "Unknown colorspace %d initializing JP2 encoder\n",
                (int)state->colorspace);
            return ERRC;
    }
    err = JP2_Compress_SetProp(state->handle,
        cJP2_Prop_Extern_Colorspace, value, -1, -1);
    if (err != cJP2_Error_OK) {
        dmlprintf1(state->memory, "Luratech JP2 error %d setting colorspace\n", (int)err);
        return ERRC;
    }

    if (state->lossless) {
        /* the default encoding mode is lossless */
        return 0;
    }

    /* otherwise, set 9,7 wavelets and quality-target mode */
    err = JP2_Compress_SetProp(state->handle,
        cJP2_Prop_Wavelet_Filter, cJP2_Wavelet_9_7, -1, -1);
    if (err != cJP2_Error_OK) {
        dmlprintf1(state->memory, "Luratech JP2 error %d setting wavelet filter\n", (int)err);
        return ERRC;
    }
    err = JP2_Compress_SetProp(state->handle,
        cJP2_Prop_Rate_Quality, state->quality, -1, -1);
    if (err != cJP2_Error_OK) {
        dmlprintf1(state->memory, "Luratech JP2 error %d setting compression quality\n", (int)err);
        return ERRC;
    }

    /* we use the encoder's defaults for all other parameters */

    return 0;
}

/* process input and return any encoded data.
   see strimpl.h for return codes. */
static int
s_jpxe_process(stream_state *ss, stream_cursor_read *pr,
                stream_cursor_write *pw, bool last)
{
    stream_jpxe_state *state = (stream_jpxe_state *)ss;
    long in_size = pr->limit - pr->ptr;
    long out_size = pw->limit - pw->ptr;
    long available;
    JP2_Error err;

    /* HACK -- reinstall our callbacks in case the GC has moved our state structure */
    /* this should be done instead from a pointer relocation callback, or initialization
       moved entirely inside the process routine. */
    err = JP2_Compress_SetProp(state->handle,
        cJP2_Prop_Input_Parameter, (JP2_Property_Value)state, -1, -1);
    if (err != cJP2_Error_OK) {
        dmlprintf1(state->memory, "Luratech JP2 error %d setting input callback parameter.\n", (int)err);
        return ERRC;
    }
    err = JP2_Compress_SetProp(state->handle,
        cJP2_Prop_Write_Parameter, (JP2_Property_Value)state, -1, -1);
    if (err != cJP2_Error_OK) {
        dmlprintf1(state->memory, "Luratech JP2 error %d setting compressed output callback parameter.\n", (int)err);
        return ERRC;
    }

    if (in_size > 0) {
        /* allocate our input buffer if necessary */
        if (state->inbuf == NULL) {
            state->inbuf = s_jpx_alloc(JPX_BUFFER_SIZE, (JP2_Callback_Param)state->memory->non_gc_memory);
            if (state->inbuf == NULL) {
                dmprintf(state->memory, "jpx encode: failed to allocate input buffer.\n");
                return ERRC;
            }
            state->insize = JPX_BUFFER_SIZE;
        }

        /* grow our input buffer if necessary */
        while (state->infill + in_size > state->insize) {
            unsigned char *new = gs_resize_object(state->memory->non_gc_memory, state->inbuf, state->insize*2, "s_jpxe_process");
            if (new == NULL) {
                dmprintf(state->memory, "jpx encode: failed to resize input buffer.\n");
                return ERRC;
            }
            state->inbuf = new;
            state->insize *= 2;
        }

        /* copy available input */
        memcpy(state->inbuf + state->infill, pr->ptr + 1, in_size);
        state->infill += in_size;
        pr->ptr += in_size;
    }

    if (last && state->outbuf == NULL) {
        /* We have all the data; call the compressor.
           our callback will automatically allocate the output buffer */
        if_debug0m('w', state->memory, "[w] jpxe process compressing image data\n");
        err = JP2_Compress_Image(state->handle);
        if (err != cJP2_Error_OK) {
            dmlprintf1(state->memory, "Luratech JP2 error %d compressing image data.\n", (int)err);
            return ERRC;
        }
     }

     if (state->outbuf != NULL) {
        /* copy out any available output data */
        available = min(out_size, state->outfill - state->offset);
        memcpy(pw->ptr + 1, state->outbuf + state->offset, available);
        pw->ptr += available;
        state->offset += available;

        /* do we have any more data? */
        if (state->outfill - state->offset > 0) return 1;
        else return EOFC; /* all done */
    }

    /* something went wrong above */
    return last;
}

/* stream release. free all our state. */
static void
s_jpxe_release(stream_state *ss)
{
    stream_jpxe_state *state = (stream_jpxe_state *)ss;
    JP2_Error err;

    /* close the library compression context */
    err = JP2_Compress_End(state->handle);
    if (err != cJP2_Error_OK) {
        /* we can't return an error, so only print on debug builds */
        if_debug1m('w', state->memory, "[w]jpxe Luratech JP2 error %d"
                   " closing compression context", (int)err);
    }

    /* free our own storage */
    gs_free_object(state->memory->non_gc_memory, state->outbuf, "s_jpxe_release(outbuf)");
    gs_free_object(state->memory->non_gc_memory, state->inbuf, "s_jpxe_release(inbuf)");
}

int sjpxd_create(gs_memory_t *mem)
{
    return 0;
}

void sjpxd_destroy(gs_memory_t *mem)
{
}

/* encoder stream template */
const stream_template s_jpxe_template = {
    &st_jpxe_state,
    s_jpxe_init,
    s_jpxe_process,
    1024, 1024, /* min in and out buffer sizes */
    s_jpxe_release,
    s_jpxe_set_defaults
};