-
Notifications
You must be signed in to change notification settings - Fork 256
/
Copy pathencoding.go
2269 lines (1949 loc) · 63.1 KB
/
encoding.go
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
/*
* This file is subject to the terms and conditions defined in
* file 'LICENSE.md', which is part of this source code package.
*/
package core
// Implement encoders for PDF. Currently supported:
// - Raw (Identity)
// - FlateDecode
// - LZW
// - DCT Decode (JPEG)
// - RunLength
// - ASCII Hex
// - ASCII85
// - CCITT Fax (dummy)
// - JBIG2 (dummy)
// - JPX (dummy)
import (
"bytes"
"compress/zlib"
"encoding/hex"
"errors"
"fmt"
goimage "image"
gocolor "image/color"
"image/jpeg"
"io"
// Need two slightly different implementations of LZW (EarlyChange parameter).
lzw0 "compress/lzw"
lzw1 "golang.org/x/image/tiff/lzw"
"github.com/unidoc/unipdf/v3/common"
"github.com/unidoc/unipdf/v3/internal/ccittfax"
)
// Stream encoding filter names.
const (
StreamEncodingFilterNameFlate = "FlateDecode"
StreamEncodingFilterNameLZW = "LZWDecode"
StreamEncodingFilterNameDCT = "DCTDecode"
StreamEncodingFilterNameRunLength = "RunLengthDecode"
StreamEncodingFilterNameASCIIHex = "ASCIIHexDecode"
StreamEncodingFilterNameASCII85 = "ASCII85Decode"
StreamEncodingFilterNameCCITTFax = "CCITTFaxDecode"
StreamEncodingFilterNameJBIG2 = "JBIG2Decode"
StreamEncodingFilterNameJPX = "JPXDecode"
StreamEncodingFilterNameRaw = "Raw"
)
const (
// DefaultJPEGQuality is the default quality produced by JPEG encoders.
DefaultJPEGQuality = 75
)
// StreamEncoder represents the interface for all PDF stream encoders.
type StreamEncoder interface {
GetFilterName() string
MakeDecodeParams() PdfObject
MakeStreamDict() *PdfObjectDictionary
UpdateParams(params *PdfObjectDictionary)
EncodeBytes(data []byte) ([]byte, error)
DecodeBytes(encoded []byte) ([]byte, error)
DecodeStream(streamObj *PdfObjectStream) ([]byte, error)
}
// FlateEncoder represents Flate encoding.
type FlateEncoder struct {
Predictor int
BitsPerComponent int
// For predictors
Columns int
Colors int
}
// NewFlateEncoder makes a new flate encoder with default parameters, predictor 1 and bits per component 8.
func NewFlateEncoder() *FlateEncoder {
encoder := &FlateEncoder{}
// Default (No prediction)
encoder.Predictor = 1
// Currently only supporting 8.
encoder.BitsPerComponent = 8
encoder.Colors = 1
encoder.Columns = 1
return encoder
}
// SetPredictor sets the predictor function. Specify the number of columns per row.
// The columns indicates the number of samples per row.
// Used for grouping data together for compression.
func (enc *FlateEncoder) SetPredictor(columns int) {
// Only supporting PNG sub predictor for encoding.
enc.Predictor = 11
enc.Columns = columns
}
// GetFilterName returns the name of the encoding filter.
func (enc *FlateEncoder) GetFilterName() string {
return StreamEncodingFilterNameFlate
}
// MakeDecodeParams makes a new instance of an encoding dictionary based on
// the current encoder settings.
func (enc *FlateEncoder) MakeDecodeParams() PdfObject {
if enc.Predictor > 1 {
decodeParams := MakeDict()
decodeParams.Set("Predictor", MakeInteger(int64(enc.Predictor)))
// Only add if not default option.
if enc.BitsPerComponent != 8 {
decodeParams.Set("BitsPerComponent", MakeInteger(int64(enc.BitsPerComponent)))
}
if enc.Columns != 1 {
decodeParams.Set("Columns", MakeInteger(int64(enc.Columns)))
}
if enc.Colors != 1 {
decodeParams.Set("Colors", MakeInteger(int64(enc.Colors)))
}
return decodeParams
}
return nil
}
// MakeStreamDict makes a new instance of an encoding dictionary for a stream object.
// Has the Filter set and the DecodeParms.
func (enc *FlateEncoder) MakeStreamDict() *PdfObjectDictionary {
dict := MakeDict()
dict.Set("Filter", MakeName(enc.GetFilterName()))
decodeParams := enc.MakeDecodeParams()
if decodeParams != nil {
dict.Set("DecodeParms", decodeParams)
}
return dict
}
// UpdateParams updates the parameter values of the encoder.
func (enc *FlateEncoder) UpdateParams(params *PdfObjectDictionary) {
predictor, err := GetNumberAsInt64(params.Get("Predictor"))
if err == nil {
enc.Predictor = int(predictor)
}
bpc, err := GetNumberAsInt64(params.Get("BitsPerComponent"))
if err == nil {
enc.BitsPerComponent = int(bpc)
}
columns, err := GetNumberAsInt64(params.Get("Width"))
if err == nil {
enc.Columns = int(columns)
}
colorComponents, err := GetNumberAsInt64(params.Get("ColorComponents"))
if err == nil {
enc.Colors = int(colorComponents)
}
}
// Create a new flate decoder from a stream object, getting all the encoding parameters
// from the DecodeParms stream object dictionary entry.
func newFlateEncoderFromStream(streamObj *PdfObjectStream, decodeParams *PdfObjectDictionary) (*FlateEncoder, error) {
encoder := NewFlateEncoder()
encDict := streamObj.PdfObjectDictionary
if encDict == nil {
// No encoding dictionary.
return encoder, nil
}
// If decodeParams not provided, see if we can get from the stream.
if decodeParams == nil {
obj := TraceToDirectObject(encDict.Get("DecodeParms"))
switch t := obj.(type) {
case *PdfObjectArray:
arr := t
if arr.Len() != 1 {
common.Log.Debug("Error: DecodeParms array length != 1 (%d)", arr.Len())
return nil, errors.New("range check error")
}
obj = TraceToDirectObject(arr.Get(0))
case *PdfObjectDictionary:
decodeParams = t
case *PdfObjectNull, nil:
// No decode params set.
default:
common.Log.Debug("Error: DecodeParms not a dictionary (%T)", obj)
return nil, fmt.Errorf("invalid DecodeParms")
}
}
if decodeParams == nil {
// Can safely return here if no decode params, as the following depend on the decode params.
return encoder, nil
}
common.Log.Trace("decode params: %s", decodeParams.String())
obj := decodeParams.Get("Predictor")
if obj == nil {
common.Log.Debug("Error: Predictor missing from DecodeParms - Continue with default (1)")
} else {
predictor, ok := obj.(*PdfObjectInteger)
if !ok {
common.Log.Debug("Error: Predictor specified but not numeric (%T)", obj)
return nil, fmt.Errorf("invalid Predictor")
}
encoder.Predictor = int(*predictor)
}
// Bits per component. Use default if not specified (8).
obj = decodeParams.Get("BitsPerComponent")
if obj != nil {
bpc, ok := obj.(*PdfObjectInteger)
if !ok {
common.Log.Debug("ERROR: Invalid BitsPerComponent")
return nil, fmt.Errorf("invalid BitsPerComponent")
}
encoder.BitsPerComponent = int(*bpc)
}
if encoder.Predictor > 1 {
// Columns.
encoder.Columns = 1
obj = decodeParams.Get("Columns")
if obj != nil {
columns, ok := obj.(*PdfObjectInteger)
if !ok {
return nil, fmt.Errorf("predictor column invalid")
}
encoder.Columns = int(*columns)
}
// Colors.
// Number of interleaved color components per sample (Default 1 if not specified)
encoder.Colors = 1
obj = decodeParams.Get("Colors")
if obj != nil {
colors, ok := obj.(*PdfObjectInteger)
if !ok {
return nil, fmt.Errorf("predictor colors not an integer")
}
encoder.Colors = int(*colors)
}
}
return encoder, nil
}
// DecodeBytes decodes a slice of Flate encoded bytes and returns the result.
func (enc *FlateEncoder) DecodeBytes(encoded []byte) ([]byte, error) {
common.Log.Trace("FlateDecode bytes")
if len(encoded) == 0 {
common.Log.Debug("ERROR: empty Flate encoded buffer. Returning empty byte slice.")
return []byte{}, nil
}
bufReader := bytes.NewReader(encoded)
r, err := zlib.NewReader(bufReader)
if err != nil {
common.Log.Debug("Decoding error %v\n", err)
common.Log.Debug("Stream (%d) % x", len(encoded), encoded)
return nil, err
}
defer r.Close()
var outBuf bytes.Buffer
outBuf.ReadFrom(r)
return outBuf.Bytes(), nil
}
// Prediction filters for PNG predictors.
const (
pfNone = 0 // No prediction (raw).
pfSub = 1 // Predicts same as left sample.
pfUp = 2 // Predicts same as sample above.
pfAvg = 3 // Predict based on left and above.
pfPaeth = 4 // Paeth algorithm prediction.
)
// Apply predictor to decoded `outData` to get final output data.
func (enc *FlateEncoder) postDecodePredict(outData []byte) ([]byte, error) {
if enc.Predictor > 1 {
if enc.Predictor == 2 { // TIFF encoding.
// TODO(gunnsth): Needs test cases.
common.Log.Trace("Tiff encoding")
common.Log.Trace("Colors: %d", enc.Colors)
rowLength := int(enc.Columns) * enc.Colors
if rowLength < 1 {
// No data. Return empty set.
return []byte{}, nil
}
rows := len(outData) / rowLength
if len(outData)%rowLength != 0 {
common.Log.Debug("ERROR: TIFF encoding: Invalid row length...")
return nil, fmt.Errorf("invalid row length (%d/%d)", len(outData), rowLength)
}
if rowLength%enc.Colors != 0 {
return nil, fmt.Errorf("invalid row length (%d) for colors %d", rowLength, enc.Colors)
}
if rowLength > len(outData) {
common.Log.Debug("Row length cannot be longer than data length (%d/%d)", rowLength, len(outData))
return nil, errors.New("range check error")
}
common.Log.Trace("inp outData (%d): % x", len(outData), outData)
pOutBuffer := bytes.NewBuffer(nil)
// 0-255 -255 255 ; 0-255=-255;
for i := 0; i < rows; i++ {
rowData := outData[rowLength*i : rowLength*(i+1)]
// Predicts the same as the sample to the left.
// Interleaved by colors.
for j := enc.Colors; j < rowLength; j++ {
rowData[j] += rowData[j-enc.Colors]
}
pOutBuffer.Write(rowData)
}
pOutData := pOutBuffer.Bytes()
common.Log.Trace("POutData (%d): % x", len(pOutData), pOutData)
return pOutData, nil
} else if enc.Predictor >= 10 && enc.Predictor <= 15 {
common.Log.Trace("PNG Encoding")
// Columns represents the number of samples per row; Each sample can contain multiple color
// components.
rowLength := int(enc.Columns*enc.Colors + 1) // 1 byte to specify predictor algorithms per row.
rows := len(outData) / rowLength
if len(outData)%rowLength != 0 {
return nil, fmt.Errorf("invalid row length (%d/%d)", len(outData), rowLength)
}
if rowLength > len(outData) {
common.Log.Debug("Row length cannot be longer than data length (%d/%d)", rowLength, len(outData))
return nil, errors.New("range check error")
}
pOutBuffer := bytes.NewBuffer(nil)
common.Log.Trace("Predictor columns: %d", enc.Columns)
common.Log.Trace("Length: %d / %d = %d rows", len(outData), rowLength, rows)
prevRowData := make([]byte, rowLength)
for i := 0; i < rowLength; i++ {
prevRowData[i] = 0
}
bytesPerPixel := enc.Colors // Assuming BPC = 8.
for i := 0; i < rows; i++ {
rowData := outData[rowLength*i : rowLength*(i+1)]
fb := rowData[0]
switch fb {
case pfNone:
case pfSub:
for j := 1 + bytesPerPixel; j < rowLength; j++ {
rowData[j] += rowData[j-bytesPerPixel]
}
case pfUp:
// Up: Predicts the same as the sample above
for j := 1; j < rowLength; j++ {
rowData[j] += prevRowData[j]
}
case pfAvg:
// Avg: Predicts the same as the average of the sample to the left and above.
for j := 1; j < bytesPerPixel+1; j++ {
rowData[j] += prevRowData[j] / 2
}
for j := bytesPerPixel + 1; j < rowLength; j++ {
rowData[j] += byte((int(rowData[j-bytesPerPixel]) + int(prevRowData[j])) / 2)
}
case pfPaeth:
// Paeth: a nonlinear function of the sample to the left (a), sample above (b)
// and the upper left (c).
for j := 1; j < rowLength; j++ {
var a, b, c byte
b = prevRowData[j] // above.
if j >= bytesPerPixel+1 {
a = rowData[j-bytesPerPixel]
c = prevRowData[j-bytesPerPixel]
}
rowData[j] += paeth(a, b, c)
}
default:
common.Log.Debug("ERROR: Invalid filter byte (%d) @row %d", fb, i)
return nil, fmt.Errorf("invalid filter byte (%d)", fb)
}
copy(prevRowData, rowData)
pOutBuffer.Write(rowData[1:])
}
pOutData := pOutBuffer.Bytes()
return pOutData, nil
} else {
common.Log.Debug("ERROR: Unsupported predictor (%d)", enc.Predictor)
return nil, fmt.Errorf("unsupported predictor (%d)", enc.Predictor)
}
}
return outData, nil
}
// DecodeStream decodes a FlateEncoded stream object and give back decoded bytes.
func (enc *FlateEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, error) {
// TODO: Handle more filter bytes and support more values of BitsPerComponent.
common.Log.Trace("FlateDecode stream")
common.Log.Trace("Predictor: %d", enc.Predictor)
if enc.BitsPerComponent != 8 {
return nil, fmt.Errorf("invalid BitsPerComponent=%d (only 8 supported)", enc.BitsPerComponent)
}
outData, err := enc.DecodeBytes(streamObj.Stream)
if err != nil {
return nil, err
}
return enc.postDecodePredict(outData)
}
// EncodeBytes encodes a bytes array and return the encoded value based on the encoder parameters.
func (enc *FlateEncoder) EncodeBytes(data []byte) ([]byte, error) {
if enc.Predictor != 1 && enc.Predictor != 11 {
common.Log.Debug("Encoding error: FlateEncoder Predictor = 1, 11 only supported")
return nil, ErrUnsupportedEncodingParameters
}
if enc.Predictor == 11 {
// The length of each output row in number of samples.
// N.B. Each output row has one extra sample as compared to the input to indicate the
// predictor type.
rowLength := int(enc.Columns)
rows := len(data) / rowLength
if len(data)%rowLength != 0 {
common.Log.Error("Invalid row length")
return nil, errors.New("invalid row length")
}
pOutBuffer := bytes.NewBuffer(nil)
tmpData := make([]byte, rowLength)
for i := 0; i < rows; i++ {
rowData := data[rowLength*i : rowLength*(i+1)]
// PNG SUB method.
// Sub: Predicts the same as the sample to the left.
tmpData[0] = rowData[0]
for j := 1; j < rowLength; j++ {
tmpData[j] = byte(int(rowData[j]-rowData[j-1]) % 256)
}
pOutBuffer.WriteByte(1) // sub method
pOutBuffer.Write(tmpData)
}
data = pOutBuffer.Bytes()
}
var b bytes.Buffer
w := zlib.NewWriter(&b)
w.Write(data)
w.Close()
return b.Bytes(), nil
}
// LZWEncoder provides LZW encoding/decoding functionality.
type LZWEncoder struct {
Predictor int
BitsPerComponent int
// For predictors
Columns int
Colors int
// LZW algorithm setting.
EarlyChange int
}
// NewLZWEncoder makes a new LZW encoder with default parameters.
func NewLZWEncoder() *LZWEncoder {
encoder := &LZWEncoder{}
// Default (No prediction)
encoder.Predictor = 1
// Currently only supporting 8.
encoder.BitsPerComponent = 8
encoder.Colors = 1
encoder.Columns = 1
encoder.EarlyChange = 1
return encoder
}
// GetFilterName returns the name of the encoding filter.
func (enc *LZWEncoder) GetFilterName() string {
return StreamEncodingFilterNameLZW
}
// MakeDecodeParams makes a new instance of an encoding dictionary based on
// the current encoder settings.
func (enc *LZWEncoder) MakeDecodeParams() PdfObject {
if enc.Predictor > 1 {
decodeParams := MakeDict()
decodeParams.Set("Predictor", MakeInteger(int64(enc.Predictor)))
// Only add if not default option.
if enc.BitsPerComponent != 8 {
decodeParams.Set("BitsPerComponent", MakeInteger(int64(enc.BitsPerComponent)))
}
if enc.Columns != 1 {
decodeParams.Set("Columns", MakeInteger(int64(enc.Columns)))
}
if enc.Colors != 1 {
decodeParams.Set("Colors", MakeInteger(int64(enc.Colors)))
}
return decodeParams
}
return nil
}
// MakeStreamDict makes a new instance of an encoding dictionary for a stream object.
// Has the Filter set and the DecodeParms.
func (enc *LZWEncoder) MakeStreamDict() *PdfObjectDictionary {
dict := MakeDict()
dict.Set("Filter", MakeName(enc.GetFilterName()))
decodeParams := enc.MakeDecodeParams()
if decodeParams != nil {
dict.Set("DecodeParms", decodeParams)
}
dict.Set("EarlyChange", MakeInteger(int64(enc.EarlyChange)))
return dict
}
// UpdateParams updates the parameter values of the encoder.
func (enc *LZWEncoder) UpdateParams(params *PdfObjectDictionary) {
predictor, err := GetNumberAsInt64(params.Get("Predictor"))
if err == nil {
enc.Predictor = int(predictor)
}
bpc, err := GetNumberAsInt64(params.Get("BitsPerComponent"))
if err == nil {
enc.BitsPerComponent = int(bpc)
}
columns, err := GetNumberAsInt64(params.Get("Width"))
if err == nil {
enc.Columns = int(columns)
}
colorComponents, err := GetNumberAsInt64(params.Get("ColorComponents"))
if err == nil {
enc.Colors = int(colorComponents)
}
earlyChange, err := GetNumberAsInt64(params.Get("EarlyChange"))
if err == nil {
enc.EarlyChange = int(earlyChange)
}
}
// Create a new LZW encoder/decoder from a stream object, getting all the encoding parameters
// from the DecodeParms stream object dictionary entry.
func newLZWEncoderFromStream(streamObj *PdfObjectStream, decodeParams *PdfObjectDictionary) (*LZWEncoder, error) {
// Start with default settings.
encoder := NewLZWEncoder()
encDict := streamObj.PdfObjectDictionary
if encDict == nil {
// No encoding dictionary.
return encoder, nil
}
// If decodeParams not provided, see if we can get from the stream.
if decodeParams == nil {
obj := TraceToDirectObject(encDict.Get("DecodeParms"))
if obj != nil {
if dp, isDict := obj.(*PdfObjectDictionary); isDict {
decodeParams = dp
} else if a, isArr := obj.(*PdfObjectArray); isArr {
if a.Len() == 1 {
if dp, isDict := GetDict(a.Get(0)); isDict {
decodeParams = dp
}
}
}
if decodeParams == nil {
common.Log.Error("DecodeParms not a dictionary %#v", obj)
return nil, fmt.Errorf("invalid DecodeParms")
}
}
}
// The EarlyChange indicates when to increase code length, as different
// implementations use a different mechanisms. Essentially this chooses
// which LZW implementation to use.
// The default is 1 (one code early)
obj := encDict.Get("EarlyChange")
if obj != nil {
earlyChange, ok := obj.(*PdfObjectInteger)
if !ok {
common.Log.Debug("Error: EarlyChange specified but not numeric (%T)", obj)
return nil, fmt.Errorf("invalid EarlyChange")
}
if *earlyChange != 0 && *earlyChange != 1 {
return nil, fmt.Errorf("invalid EarlyChange value (not 0 or 1)")
}
encoder.EarlyChange = int(*earlyChange)
} else {
encoder.EarlyChange = 1 // default
}
if decodeParams == nil {
// No decode parameters. Can safely return here if not set as the following options
// are related to the decode Params.
return encoder, nil
}
obj = decodeParams.Get("Predictor")
if obj != nil {
predictor, ok := obj.(*PdfObjectInteger)
if !ok {
common.Log.Debug("Error: Predictor specified but not numeric (%T)", obj)
return nil, fmt.Errorf("invalid Predictor")
}
encoder.Predictor = int(*predictor)
}
// Bits per component. Use default if not specified (8).
obj = decodeParams.Get("BitsPerComponent")
if obj != nil {
bpc, ok := obj.(*PdfObjectInteger)
if !ok {
common.Log.Debug("ERROR: Invalid BitsPerComponent")
return nil, fmt.Errorf("invalid BitsPerComponent")
}
encoder.BitsPerComponent = int(*bpc)
}
if encoder.Predictor > 1 {
// Columns.
encoder.Columns = 1
obj = decodeParams.Get("Columns")
if obj != nil {
columns, ok := obj.(*PdfObjectInteger)
if !ok {
return nil, fmt.Errorf("predictor column invalid")
}
encoder.Columns = int(*columns)
}
// Colors.
// Number of interleaved color components per sample (Default 1 if not specified)
encoder.Colors = 1
obj = decodeParams.Get("Colors")
if obj != nil {
colors, ok := obj.(*PdfObjectInteger)
if !ok {
return nil, fmt.Errorf("predictor colors not an integer")
}
encoder.Colors = int(*colors)
}
}
common.Log.Trace("decode params: %s", decodeParams.String())
return encoder, nil
}
// DecodeBytes decodes a slice of LZW encoded bytes and returns the result.
func (enc *LZWEncoder) DecodeBytes(encoded []byte) ([]byte, error) {
var outBuf bytes.Buffer
bufReader := bytes.NewReader(encoded)
var r io.ReadCloser
if enc.EarlyChange == 1 {
// LZW implementation with code length increases one code early (1).
r = lzw1.NewReader(bufReader, lzw1.MSB, 8)
} else {
// 0: LZW implementation with postponed code length increases (0).
r = lzw0.NewReader(bufReader, lzw0.MSB, 8)
}
defer r.Close()
_, err := outBuf.ReadFrom(r)
if err != nil {
return nil, err
}
return outBuf.Bytes(), nil
}
// DecodeStream decodes a LZW encoded stream and returns the result as a
// slice of bytes.
func (enc *LZWEncoder) DecodeStream(streamObj *PdfObjectStream) ([]byte, error) {
// Revamp this support to handle TIFF predictor (2).
// Also handle more filter bytes and check
// BitsPerComponent. Default value is 8, currently we are only
// supporting that one.
common.Log.Trace("LZW Decoding")
common.Log.Trace("Predictor: %d", enc.Predictor)
outData, err := enc.DecodeBytes(streamObj.Stream)
if err != nil {
return nil, err
}
common.Log.Trace(" IN: (%d) % x", len(streamObj.Stream), streamObj.Stream)
common.Log.Trace("OUT: (%d) % x", len(outData), outData)
if enc.Predictor > 1 {
if enc.Predictor == 2 { // TIFF encoding: Needs some tests.
common.Log.Trace("Tiff encoding")
rowLength := int(enc.Columns) * enc.Colors
if rowLength < 1 {
// No data. Return empty set.
return []byte{}, nil
}
rows := len(outData) / rowLength
if len(outData)%rowLength != 0 {
common.Log.Debug("ERROR: TIFF encoding: Invalid row length...")
return nil, fmt.Errorf("invalid row length (%d/%d)", len(outData), rowLength)
}
if rowLength%enc.Colors != 0 {
return nil, fmt.Errorf("invalid row length (%d) for colors %d", rowLength, enc.Colors)
}
if rowLength > len(outData) {
common.Log.Debug("Row length cannot be longer than data length (%d/%d)", rowLength, len(outData))
return nil, errors.New("range check error")
}
common.Log.Trace("inp outData (%d): % x", len(outData), outData)
pOutBuffer := bytes.NewBuffer(nil)
// 0-255 -255 255 ; 0-255=-255;
for i := 0; i < rows; i++ {
rowData := outData[rowLength*i : rowLength*(i+1)]
// Predicts the same as the sample to the left.
// Interleaved by colors.
for j := enc.Colors; j < rowLength; j++ {
rowData[j] = byte(int(rowData[j]+rowData[j-enc.Colors]) % 256)
}
// GH: Appears that this is not working as expected...
pOutBuffer.Write(rowData)
}
pOutData := pOutBuffer.Bytes()
common.Log.Trace("POutData (%d): % x", len(pOutData), pOutData)
return pOutData, nil
} else if enc.Predictor >= 10 && enc.Predictor <= 15 {
common.Log.Trace("PNG Encoding")
// Columns represents the number of samples per row; Each sample can contain multiple color
// components.
rowLength := int(enc.Columns*enc.Colors + 1) // 1 byte to specify predictor algorithms per row.
if rowLength < 1 {
// No data. Return empty set.
return []byte{}, nil
}
rows := len(outData) / rowLength
if len(outData)%rowLength != 0 {
return nil, fmt.Errorf("invalid row length (%d/%d)", len(outData), rowLength)
}
if rowLength > len(outData) {
common.Log.Debug("Row length cannot be longer than data length (%d/%d)", rowLength, len(outData))
return nil, errors.New("range check error")
}
pOutBuffer := bytes.NewBuffer(nil)
common.Log.Trace("Predictor columns: %d", enc.Columns)
common.Log.Trace("Length: %d / %d = %d rows", len(outData), rowLength, rows)
prevRowData := make([]byte, rowLength)
for i := 0; i < rowLength; i++ {
prevRowData[i] = 0
}
for i := 0; i < rows; i++ {
rowData := outData[rowLength*i : rowLength*(i+1)]
fb := rowData[0]
switch fb {
case 0:
// No prediction. (No operation).
case 1:
// Sub: Predicts the same as the sample to the left.
for j := 2; j < rowLength; j++ {
rowData[j] = byte(int(rowData[j]+rowData[j-1]) % 256)
}
case 2:
// Up: Predicts the same as the sample above
for j := 1; j < rowLength; j++ {
rowData[j] = byte(int(rowData[j]+prevRowData[j]) % 256)
}
default:
common.Log.Debug("ERROR: Invalid filter byte (%d)", fb)
return nil, fmt.Errorf("invalid filter byte (%d)", fb)
}
for i := 0; i < rowLength; i++ {
prevRowData[i] = rowData[i]
}
pOutBuffer.Write(rowData[1:])
}
pOutData := pOutBuffer.Bytes()
return pOutData, nil
} else {
common.Log.Debug("ERROR: Unsupported predictor (%d)", enc.Predictor)
return nil, fmt.Errorf("unsupported predictor (%d)", enc.Predictor)
}
}
return outData, nil
}
// EncodeBytes implements support for LZW encoding. Currently not supporting predictors (raw compressed data only).
// Only supports the Early change = 1 algorithm (compress/lzw) as the other implementation
// does not have a write method.
// TODO: Consider refactoring compress/lzw to allow both.
func (enc *LZWEncoder) EncodeBytes(data []byte) ([]byte, error) {
if enc.Predictor != 1 {
return nil, fmt.Errorf("LZW Predictor = 1 only supported yet")
}
if enc.EarlyChange == 1 {
return nil, fmt.Errorf("LZW Early Change = 0 only supported yet")
}
var b bytes.Buffer
w := lzw0.NewWriter(&b, lzw0.MSB, 8)
w.Write(data)
w.Close()
return b.Bytes(), nil
}
// DCTEncoder provides a DCT (JPG) encoding/decoding functionality for images.
type DCTEncoder struct {
ColorComponents int // 1 (gray), 3 (rgb), 4 (cmyk)
BitsPerComponent int // 8 or 16 bit
Width int
Height int
Quality int
}
// NewDCTEncoder makes a new DCT encoder with default parameters.
func NewDCTEncoder() *DCTEncoder {
encoder := &DCTEncoder{}
encoder.ColorComponents = 3
encoder.BitsPerComponent = 8
encoder.Quality = DefaultJPEGQuality
return encoder
}
// GetFilterName returns the name of the encoding filter.
func (enc *DCTEncoder) GetFilterName() string {
return StreamEncodingFilterNameDCT
}
// MakeDecodeParams makes a new instance of an encoding dictionary based on
// the current encoder settings.
func (enc *DCTEncoder) MakeDecodeParams() PdfObject {
// Does not have decode params.
return nil
}
// MakeStreamDict makes a new instance of an encoding dictionary for a stream object.
// Has the Filter set. Some other parameters are generated elsewhere.
func (enc *DCTEncoder) MakeStreamDict() *PdfObjectDictionary {
dict := MakeDict()
dict.Set("Filter", MakeName(enc.GetFilterName()))
return dict
}
// UpdateParams updates the parameter values of the encoder.
func (enc *DCTEncoder) UpdateParams(params *PdfObjectDictionary) {
colorComponents, err := GetNumberAsInt64(params.Get("ColorComponents"))
if err == nil {
enc.ColorComponents = int(colorComponents)
}
bpc, err := GetNumberAsInt64(params.Get("BitsPerComponent"))
if err == nil {
enc.BitsPerComponent = int(bpc)
}
width, err := GetNumberAsInt64(params.Get("Width"))
if err == nil {
enc.Width = int(width)
}
height, err := GetNumberAsInt64(params.Get("Height"))
if err == nil {
enc.Height = int(height)
}
quality, err := GetNumberAsInt64(params.Get("Quality"))
if err == nil {
enc.Quality = int(quality)
}
}
// Create a new DCT encoder/decoder from a stream object, getting all the encoding parameters
// from the stream object dictionary entry and the image data itself.
// TODO: Support if used with other filters [ASCII85Decode FlateDecode DCTDecode]...
// need to apply the other filters prior to this one...
func newDCTEncoderFromStream(streamObj *PdfObjectStream, multiEnc *MultiEncoder) (*DCTEncoder, error) {
// Start with default settings.
encoder := NewDCTEncoder()
encDict := streamObj.PdfObjectDictionary
if encDict == nil {
// No encoding dictionary.
return encoder, nil
}
// If using DCTDecode in combination with other filters, make sure to decode that first...
encoded := streamObj.Stream
if multiEnc != nil {
e, err := multiEnc.DecodeBytes(encoded)
if err != nil {
return nil, err
}
encoded = e
}
bufReader := bytes.NewReader(encoded)
cfg, err := jpeg.DecodeConfig(bufReader)
//img, _, err := goimage.Decode(bufReader)
if err != nil {
common.Log.Debug("Error decoding file: %s", err)
return nil, err
}
switch cfg.ColorModel {
case gocolor.RGBAModel:
encoder.BitsPerComponent = 8
encoder.ColorComponents = 3 // alpha is not included in pdf.
case gocolor.RGBA64Model:
encoder.BitsPerComponent = 16
encoder.ColorComponents = 3
case gocolor.GrayModel:
encoder.BitsPerComponent = 8
encoder.ColorComponents = 1
case gocolor.Gray16Model:
encoder.BitsPerComponent = 16
encoder.ColorComponents = 1
case gocolor.CMYKModel:
encoder.BitsPerComponent = 8
encoder.ColorComponents = 4
case gocolor.YCbCrModel:
// YCbCr is not supported by PDF, but it could be a different colorspace
// with 3 components. Would be specified by the ColorSpace entry.
encoder.BitsPerComponent = 8
encoder.ColorComponents = 3
default:
return nil, errors.New("unsupported color model")
}
encoder.Width = cfg.Width
encoder.Height = cfg.Height
common.Log.Trace("DCT Encoder: %+v", encoder)
encoder.Quality = DefaultJPEGQuality
return encoder, nil
}
// DecodeBytes decodes a slice of DCT encoded bytes and returns the result.
func (enc *DCTEncoder) DecodeBytes(encoded []byte) ([]byte, error) {
bufReader := bytes.NewReader(encoded)
//img, _, err := goimage.Decode(bufReader)
img, err := jpeg.Decode(bufReader)
if err != nil {