-
Notifications
You must be signed in to change notification settings - Fork 0
/
encoder.cpp
1765 lines (1646 loc) · 59.4 KB
/
encoder.cpp
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
/* encoder.cpp -- various PostScript and PDF encoding filter implementations
* by [email protected] at Sun Mar 3 14:16:00 CET 2002
* --- Mon Mar 4 00:00:20 CET 2002
*/
/* Imp: make built-in FlateEncode DYNALLOC */
/* Imp: add lzw_codec */
/* Imp: add gzip */
/* Imp: add zlib */
#ifdef __GNUC__
#ifndef __clang__
#pragma implementation
#endif
#endif
#include "encoder.hpp"
#include "error.hpp"
#include "gensio.hpp"
#include <stdlib.h> /* getenv() */
#include <string.h>
/* --- */
/** Does output EOD (end-of-data) marker `>' */
class ASCIIHexEncode: public PSEncoder {
public:
/** @param maxcpl_: maximum # hex digits per line, should be even */
ASCIIHexEncode(GenBuffer::Writable &out_, unsigned maxcpl_);
virtual void vi_write(char const*buf, slen_t len);
protected:
unsigned maxcpl;
/** Number of hex digits already printed. */
unsigned curcpl;
GenBuffer::Writable &out;
};
/** Does output EOD (end-of-data) marker `~>' */
class ASCII85Encode: public PSEncoder {
public:
/** @param maxcpl_: maximum # hex digits per line, should be even */
ASCII85Encode(GenBuffer::Writable &out_, unsigned maxcpl_);
virtual void vi_write(char const*buf, slen_t len);
protected:
void wencoded(char const *encoded);
void wout(unsigned PTS_INT32_T buf_);
unsigned maxcpl;
/** Number of digits available in this line */
GenBuffer::Writable &out;
unsigned ascii85breaklen;
unsigned ascii85left;
unsigned PTS_INT32_T ascii85buf;
char *obuf, *obufend, *op;
char dscst; /* For converting `%%' to `% %' to avoid DSC parser errors */
};
/** Doesn't output EOD (end-of-data) marker `>' */
class RunLengthEncode: public PSEncoder {
public:
/** @param maxcpl_: maximum # hex digits per line, should be even */
RunLengthEncode(GenBuffer::Writable &out_, slen_t RecordSize_);
virtual void vi_write(char const*buf, slen_t len);
protected:
slen_t recordsize;
GenBuffer::Writable &out;
// char *obuf, *obufend, *op;
slen_t record_left;
unsigned saved_c, saved_rep;
/** size == header+buffer+EOD */
char saved[130];
};
static int gen_write(char *block, unsigned len, void *zfile);
#if USE_BUILTIN_ZIP
#include "pts_defl.h" /* Imp: because pts_defl_interface :-( */
#if OBJDEP
# warning REQUIRES: pts_defl
#endif
class FlateEncode: public PSEncoder {
#if PTS_DEFL_RIPPED_ZLIB /* Dat: defined in pts_defl.h */
public:
/** @param level: 1..9: 9==highest compression */
FlateEncode(GenBuffer::Writable &out_, unsigned level_);
virtual ~FlateEncode() { zlib_deflateEnd(&zs); } /* Dat: ==Z_OK check (for unflushed buffers) omitted */
virtual void vi_write(char const*buf, slen_t len);
protected:
/** Formerly only one instance of FlateEncode was allowed.
* It exists <=> loced==true
*/
// static bool locked;
/** Writable that this filter writes to */
GenBuffer::Writable &out;
char workspace[ZLIB_DEFLATE_WORKSPACESIZE_MIN]; /* big, about 270k */
char obuf[4096];
/*struct*/ z_stream zs;
#else /* old, ripped from Info-ZIP 2.2 */
public:
/** @param level: 1..9: 9==highest compression */
FlateEncode(GenBuffer::Writable &out_, unsigned level_);
virtual ~FlateEncode() { if (fs!=NULLP) fs->delete2(fs); }
virtual void vi_write(char const*buf, slen_t len);
static void *gen_malloc(unsigned n);
static void gen_free(void *p);
protected:
/** Formerly only one instance of FlateEncode was allowed.
* It exists <=> loced==true
*/
// static bool locked;
/** Writable that this filter writes to */
GenBuffer::Writable &out;
#if SIZEOF_INT>2
typedef unsigned s_t;
#else
typedef unsigned short s_t;
#endif
/** Adler32 checksum */
s_t s1, s2;
bool had_header;
struct pts_defl_interface* fs;
#endif /* else PTS_DEFL_RIPPED_ZLIB */
};
#endif
/** Just store the data in Flate (ZLIB) format, no real compression. Adds
* about 3 bytes of overhead per 65535 bytes (compression ratio:
* 100.004578%)
*/
class FlateStoreEncode: public PSEncoder {
public:
/** @param level: 1..9: 9==highest compression */
FlateStoreEncode(GenBuffer::Writable &out_);
inline virtual ~FlateStoreEncode() {}
virtual void vi_write(char const*buf, slen_t len);
protected:
GenBuffer::Writable &out;
#if SIZEOF_INT>2
typedef unsigned s_t;
#else
typedef unsigned short s_t;
#endif
/** Adler32 checksum */
s_t s1, s2;
bool had_header;
/** Number of bytes already in buf */
unsigned abuflen;
/** Max: 65535 */
#if HAVE_STATIC_CONST
static const unsigned ABUFSIZE=65535;
#else
#define ABUFSIZE 65535
#endif
/** Should really not allocate a FlateStoreEncode on the stack. */
char abuf[ABUFSIZE+5];
};
#if USE_BUILTIN_FAXE
#include "pts_fax.h"
#if OBJDEP
# warning REQUIRES: pts_faxe
#endif
class CCITTFaxEncode: public PSEncoder {
public:
CCITTFaxEncode(GenBuffer::Writable &out_, slendiff_t K, slen_t Columns, bool EndOfLine, bool BlackIs1);
virtual void vi_write(char const*buf, slen_t len);
protected:
GenBuffer::Writable &out;
stream_CFE_state sCFEs;
unsigned char rbuf[4096];
unsigned char wbuf[4096];
stream_cursor_read r;
stream_cursor_write w;
unsigned char *hard, *rlimit;
static void*gen_xalloc(unsigned n);
static void gen_free(void *ptr);
static void gen_memset(void *s, int c, unsigned n);
static void gen_memcpy(void *dest, const void *src, unsigned n);
};
#endif
#if USE_BUILTIN_LZW
#include "pts_lzw.h" /* Imp: because pts_lzw_state :-( */
#if OBJDEP
# warning REQUIRES: pts_lzw
#endif
class LZWEncode: public PSEncoder {
public:
LZWEncode(GenBuffer::Writable &out_);
virtual void vi_write(char const*buf, slen_t len);
protected:
GenBuffer::Writable &out;
struct pts_lzw_state fs;
};
#endif
/**
* Reporting of GS errors is somewhat dump: the actual message isn't reported,
* only the fact that something went wrong.
* Imp: force a no-error trailer output by gs, and check that
*/
class GSEncode: public PSEncoder {
public:
/** @param filter_psname is a full-featured PostScript *Encode filter
* specification string, for example: "<</Effort 5>>/FlateEncode" or
* "0/RunLengthEncode" or "72 pop/ASCIIHexEncode"; will be surrounded as
* `currentfile ... filter'
*/
GSEncode(GenBuffer::Writable &out_, char const*filter_psname);
inline virtual ~GSEncode() {}
/* vvv Imp: correct these */
virtual void vi_write(char const*buf, slen_t len);
protected:
class P: public Filter::PipeE {
protected: virtual void vi_check();
public: P(GenBuffer::Writable &out_, char const*filter_psname);
};
/** We need this delegator because `delete ...' won't work with multiple
* inheritance. (?? )
*/
P p;
};
class CjpegEncode: public PSEncoder {
public:
/** @param filter_psname is a full-featured PostScript *Encode filter
* specification string, for example: "<</Effort 5>>/FlateEncode" or
* "0/RunLengthEncode" or "72 pop/ASCIIHexEncode"; will be surrounded as
* `currentfile ... filter'
*/
CjpegEncode(GenBuffer::Writable &out_, char const*filter_psname, slen_t Columns, slen_t Rows, bool rgbp_, unsigned char quality);
inline virtual ~CjpegEncode() {}
virtual void vi_write(char const*buf, slen_t len);
protected:
class P: public Filter::PipeE { public:
// protected: virtual void vi_check();
P(GenBuffer::Writable &out_, slen_t Columns, slen_t Rows, bool rgbp_, unsigned char quality);
protected: /* Not needed: protected -> public: pacify VC6.0 */
virtual void vi_copy(FILE *f);
bool rgbp;
};
/** We need this delegator because `delete ...' won't work with multiple
* inheritance. (?? )
*/
P p;
};
#if !USE_BUILTIN_LZW
class Lzw_codecEncode: public PSEncoder {
public:
/** @param filter_psname is a full-featured PostScript *Encode filter
* specification string, for example: "<</Effort 5>>/FlateEncode" or
* "0/RunLengthEncode" or "72 pop/ASCIIHexEncode"; will be surrounded as
* `currentfile ... filter'
*/
Lzw_codecEncode(GenBuffer::Writable &out_, char const*filter_psname);
inline virtual ~Lzw_codecEncode() {}
virtual void vi_write(char const*buf, slen_t len);
protected:
class P: public Filter::PipeE { public:
// protected: virtual void vi_check();
P(GenBuffer::Writable &out_);
protected:
// virtual void vi_copy(FILE *f);
};
/** We need this delegator because `delete ...' won't work with multiple
* inheritance. (?? )
*/
P p;
};
#endif
class TIFFPredictor2: public Encoder {
public:
/** @param maxcpl_: maximum # hex digits per line, should be even */
TIFFPredictor2(GenBuffer::Writable &out_, unsigned char bpc_, slen_t columns_, unsigned char cpp_);
virtual void vi_write(char const*buf, slen_t len);
protected:
unsigned PTS_INT32_T h;
unsigned char *obuf, *op, bpc, cpp;
slen_t rlen;
GenBuffer::Writable &out;
};
class PNGPredictorNone: public Encoder {
public:
/** @param maxcpl_: maximum # hex digits per line, should be even */
PNGPredictorNone(GenBuffer::Writable &out_, unsigned char bpc_, slen_t columns_, unsigned char cpp_);
virtual void vi_write(char const*buf, slen_t len);
protected:
slen_t rlen, opleft;
GenBuffer::Writable &out;
};
class PNGPredictorSub: public Encoder {
public:
/** @param maxcpl_: maximum # hex digits per line, should be even */
PNGPredictorSub(GenBuffer::Writable &out_, unsigned char bpc_, slen_t columns_, unsigned char cpp_);
virtual void vi_write(char const*buf, slen_t len);
protected:
unsigned PTS_INT32_T h;
unsigned char *obuf, *op;
slen_t rlen;
GenBuffer::Writable &out;
unsigned char bpccpp;
};
class PNGPredictorUp: public Encoder {
public:
/** @param maxcpl_: maximum # hex digits per line, should be even */
PNGPredictorUp(GenBuffer::Writable &out_, unsigned char bpc_, slen_t columns_, unsigned char cpp_);
virtual void vi_write(char const*buf, slen_t len);
protected:
unsigned char *obuf, *op, *oq;
slen_t rlen;
GenBuffer::Writable &out;
};
class PNGPredictorAverage: public Encoder {
public:
/** @param maxcpl_: maximum # hex digits per line, should be even */
PNGPredictorAverage(GenBuffer::Writable &out_, unsigned char bpc_, slen_t columns_, unsigned char cpp_);
virtual void vi_write(char const*buf, slen_t len);
protected:
unsigned PTS_INT32_T h/*, g*/;
unsigned char *obuf, *op, *oq;
slen_t rlen;
GenBuffer::Writable &out;
unsigned char bpccpp;
};
class PNGPredictorPaeth: public Encoder {
public:
/** @param maxcpl_: maximum # hex digits per line, should be even */
PNGPredictorPaeth(GenBuffer::Writable &out_, unsigned char bpc_, slen_t columns_, unsigned char cpp_);
virtual void vi_write(char const*buf, slen_t len);
protected:
unsigned PTS_INT32_T h, g;
unsigned char *obuf, *op, *oq;
slen_t rlen;
GenBuffer::Writable &out;
unsigned char bpccpp;
};
/** This class implements inferior predictor autoselection heuristics.
* Please use PNGPredictorAuto instead.
* Imp: code reuse with PNGPredictorAuto
*/
class PNGPredictorAutoBadSigned: public Encoder {
public:
/** @param maxcpl_: maximum # hex digits per line, should be even */
PNGPredictorAutoBadSigned(GenBuffer::Writable &out_, unsigned char bpc_, slen_t columns_, unsigned char cpp_);
virtual void vi_write(char const*buf, slen_t len);
protected:
unsigned PTS_INT32_T h, g;
unsigned char *obuf, *o_prior, *o_0, *o_1, *o_2, *o_3, *o_4, *oo[5];
slen_t rlen;
GenBuffer::Writable &out;
unsigned char bpccpp;
slen_t opleft;
};
/** This class implements inferior predictor autoselection heuristics.
* Please use PNGPredictorAuto instead.
* Imp: code reuse with PNGPredictorAuto
*/
class PNGPredictorAutoBadUnsigned: public Encoder {
public:
/** @param maxcpl_: maximum # hex digits per line, should be even */
PNGPredictorAutoBadUnsigned(GenBuffer::Writable &out_, unsigned char bpc_, slen_t columns_, unsigned char cpp_);
virtual void vi_write(char const*buf, slen_t len);
protected:
unsigned PTS_INT32_T h, g;
unsigned char *obuf, *o_prior, *o_0, *o_1, *o_2, *o_3, *o_4, *oo[5];
slen_t rlen;
GenBuffer::Writable &out;
unsigned char bpccpp;
slen_t opleft;
};
/** This class implements to so-called ``minimum sum of absolute differences''
* predictior autoselection heuristics, the same as what pngwutil.c
* contains in function png_write_find_filter() in libpng 1.2.20. (See that
* function for a discussion of other heuristics. A summary of this heuristics:
* we find which method provides the smallest value when summing the absolute
* values of the distances from zero, using anything >= 128 as negative
* numbers.
*/
class PNGPredictorAuto: public Encoder {
public:
/** @param maxcpl_: maximum # hex digits per line, should be even */
PNGPredictorAuto(GenBuffer::Writable &out_, unsigned char bpc_, slen_t columns_, unsigned char cpp_);
virtual void vi_write(char const*buf, slen_t len);
protected:
unsigned PTS_INT32_T h, g;
unsigned char *obuf, *o_prior, *o_0, *o_1, *o_2, *o_3, *o_4, *oo[5];
slen_t rlen;
GenBuffer::Writable &out;
unsigned char bpccpp;
slen_t opleft;
};
/* --- */
FlateStoreEncode::FlateStoreEncode(GenBuffer::Writable &out_)
:out(out_)
,s1(1)
,s2(0)
,had_header(false)
,abuflen(0)
{}
#if 0
/** 0x7801: ZLIB header signaling fastest compression
* 0: 2 bits: DEFLATE block header signaling stored (uncompressed) block +
* 6 bits of padding.
*/
char FlateStoreEncode::header[3]= { 0x78, 1, 0 };
#endif
void FlateStoreEncode::vi_write(char const*buf, slen_t len) {
register s_t sold;
register char const*p=buf; char const*pend=p+len;
(void)sold;
if (len==0) { /* EOF: flush and send trailer */
/* Dat: Last block has to be written even if it's empty. */
if (!had_header) { out.vi_write("\x78\x01", 2); had_header=true; }
abuf[0]=(char)1; /* Last, stored block with padding */
abuf[1]=abuflen; abuf[2]=abuflen>>8;
abuf[3]=~(abuflen); abuf[4]=~(abuflen>>8);
out.vi_write(abuf, abuflen+5);
if (s1>=65521) s1-=65521;
if (s2>=65521) s2-=65521;
unsigned char trailer[4];
trailer[0]=s2>>8; trailer[1]=s2&255; trailer[2]=s1>>8; trailer[3]=s1&255;
out.vi_write((char const*)trailer,4);
out.vi_write(0,0); /* Signal EOF */
return;
}
/* From rfc1950.txt:
Adler-32 is composed of two sums accumulated per byte: s1 is
the sum of all bytes, s2 is the sum of all s1 values. Both sums
are done modulo 65521. s1 is initialized to 1, s2 to zero. The
Adler-32 checksum is stored as s2*65536 + s1 in most-
significant-byte first (network) order.
*/
/* Update Adler-32 checksum */
while (p!=pend) {
#if SIZEOF_INT>2
if ((s1+=*(unsigned char const*)p)>=65521) s1-=65521;
if ((s2+=s1)>=65521) s2-=65521;
#elif SIZEOF_SHORT==2
sold=s1;
if ((s1+=*(unsigned char const*)p))<sold) s1+=15; /* 15==65536-21 */
sold=s2;
s2=(s2+s1)&0xffff;
if ((s2+=s1)<sold) s2+=15;
#else
/* vvv 0xffff is needed since unsigned short may be > 0..65535 */
sold=s1;
s1=(s1+*(unsigned char const*)p)&0xffff;
if (s1<sold) s1+=15; /* 15==65536-21 */
sold=s2;
s2=(s2+s1)&0xffff;
if (s2<sold) s2+=15;
#endif
p++;
}
// fprintf(stderr, "len=%u\n", len);
unsigned abufleft;
while ((abufleft=ABUFSIZE-abuflen)<len) {
// putchar('.');
// fprintf(stderr, "ABUFSIZE=%u abuflen=%u\n", ABUFSIZE, abuflen);
memcpy(abuf+abuflen+5, buf, abufleft);
abuf[0]=0; /* Stored block with padding */
abuf[1]=(char)ABUFSIZE; abuf[2]=(char)(ABUFSIZE>>8);
abuf[3]=(char)~(ABUFSIZE); abuf[4]=(char)~(ABUFSIZE>>8);
if (!had_header) { out.vi_write("\x78\x01", 2); had_header=true; }
/* fprintf(stderr,"%02x %02x", abuf[1], abuf[2]); */
out.vi_write(abuf, ABUFSIZE+5); /* emit next stored block with header */
abuflen=0;
len-=abufleft;
buf+=abufleft;
}
// putchar('X');
memcpy(abuf+abuflen+5, buf, len);
abuflen+=len;
/* Now abuf is possibly full. That is intentional, so we will be able to
* emit a full last block instead of an empty one.
*/
}
/* --- */
ASCIIHexEncode::ASCIIHexEncode(GenBuffer::Writable &out_, unsigned maxcpl_)
:maxcpl(maxcpl_)
,curcpl(0)
,out(out_) {}
void ASCIIHexEncode::vi_write(char const*buf, slen_t len) {
/* Imp: buffering (1K etc.) */
static char const hextable []="0123456789abcdef";
char obuf[3];
obuf[0]='\n';
if (len==0) { out.vi_write(">",1); out.vi_write(0,0); }
else while (len--!=0) {
obuf[1]=hextable[(*(unsigned char const*)buf)>>4];
obuf[2]=hextable[(*(unsigned char const*)buf)&15];
if (curcpl>=maxcpl) { curcpl=2; out.vi_write(obuf, 3); }
else { curcpl+=2; out.vi_write(obuf+1, 2); }
buf++;
}
}
/* --- */
ASCII85Encode::ASCII85Encode(GenBuffer::Writable &out_, unsigned maxcpl_)
:maxcpl(maxcpl_)
,out(out_)
,ascii85breaklen(maxcpl_)
,ascii85left(4)
,dscst(1) {
obufend=(op=obuf=new char[4096])+4096;
}
void ASCII85Encode::wencoded(char const *cp) {
for (; *cp!='\0'; ) {
if (op==obufend) out.vi_write(op=obuf, obufend-obuf);
// if (*cp<='!') { fprintf(stderr, "e=%d.\n", cp-encoded); }
assert(*cp>='!');
assert(*cp<='~');
if (dscst) {
if (dscst == 1) {
dscst = (*cp == '%') ? 2 : 0;
} else { /* if (dscst == 2) { */
if (*cp == '%') {
if (--ascii85breaklen == 0) {
*op++ = '\n';
ascii85breaklen = maxcpl;
} else {
/* Add space for `% %' instead of `%%' at BOL. */
*op++ = ' ';
}
if (op==obufend) out.vi_write(op=obuf, obufend-obuf);
}
dscst = 0;
}
}
*op++=*cp++;
if (--ascii85breaklen == 0) {
if (op==obufend) out.vi_write(op=obuf, obufend-obuf);
*op++='\n';
ascii85breaklen = maxcpl;
dscst = 1;
}
} /* NEXT */
}
void ASCII85Encode::vi_write(char const*buf, slen_t len) {
if (len==0) {
char encoded[6];
assert(ascii85left<=4);
if (ascii85left!=4) {
unsigned PTS_INT32_T buf_=ascii85buf<<8*ascii85left;
unsigned PTS_INT32_T q;
unsigned w1;
q = buf_ / ((unsigned PTS_INT32_T)85*85*85*85); /* actually only a byte */
assert(q<=85);
encoded[0] = q + '!';
buf_ -= q * ((unsigned PTS_INT32_T)85*85*85*85); q = buf_ / ((unsigned PTS_INT32_T)85*85*85);
encoded[1] = q + '!';
buf_ -= q * ((unsigned PTS_INT32_T)85*85*85); q = buf_ / (85*85);
encoded[2] = q + '!';
w1 = (unsigned) (buf_ - q*(unsigned PTS_INT32_T)(85*85));
assert(w1/85<85);
encoded[3] = (w1 / 85) + '!';
encoded[4] = (w1 % 85) + '!';
encoded[5-ascii85left] = '\0';
wencoded(encoded);
} /* IF */
if (op!=obuf) out.vi_write(obuf, op-obuf); /* flush buffer cache */
out.vi_write("~>",2); out.vi_write(0,0);
delete [] obuf;
obuf=(char*)NULLP;
} else {
assert(obuf!=NULLP);
register unsigned PTS_INT32_T abuf=ascii85buf;
register unsigned aleft=ascii85left;
assert(aleft>=1 && aleft<=4);
do {
while (len!=0 && aleft!=0) {
abuf=(abuf<<8)+*(unsigned char const*)buf++; len--; aleft--;
}
if (aleft!=0) break;
wout(abuf);
aleft=4;
} while (len!=0);
ascii85buf=abuf; ascii85left=aleft;
}
}
void ASCII85Encode::wout(unsigned PTS_INT32_T buf_) {
char encoded[6];
if (buf_ != (unsigned PTS_INT32_T)0) {
unsigned PTS_INT32_T q;
unsigned w1;
q = buf_ / ((unsigned PTS_INT32_T)85*85*85*85); /* actually only a byte */
encoded[0] = q + '!';
buf_ -= q * ((unsigned PTS_INT32_T)85*85*85*85); q = buf_ / ((unsigned PTS_INT32_T)85*85*85);
encoded[1] = q + '!';
buf_ -= q * ((unsigned PTS_INT32_T)85*85*85); q = buf_ / (85*85);
encoded[2] = q + '!';
w1 = (unsigned) (buf_ - q*(unsigned PTS_INT32_T)(85*85));
encoded[3] = (w1 / 85) + '!';
encoded[4] = (w1 % 85) + '!';
encoded[5] = '\0';
} else {
encoded[0] = 'z', encoded[1] = '\0';
}
wencoded(encoded);
}
/* --- */
RunLengthEncode::RunLengthEncode(GenBuffer::Writable &out_, slen_t RecordSize_)
:recordsize(RecordSize_==0?(slen_t)-1:RecordSize_)
,out(out_) {
record_left=recordsize;
// obufend=(op=obuf=new char[4096])+4096; /* Imp: implement write buffering */
saved_c=saved_rep=0;
}
void RunLengthEncode::vi_write(char const*buf, slen_t len) {
unsigned j, umax;
char b;
if (len==0) { /* handle EOF */
if (saved_rep!=0) {
assert(saved_rep>=2);
(saved+1)[-1]=257-saved_rep;
(saved+1)[1]=(char)128; /* EOD */
out.vi_write((saved+1)-1,3);
// fprintf(stderr,"rd=%u\n",saved_rep);
} else if (saved_c!=0) {
(saved+1)[-1]=saved_c-1;
(saved+1)[saved_c]=(char)128; /* EOD */
out.vi_write((saved+1)-1, saved_c+2);
// fprintf(stderr,"re=%u\n",saved_c);
} else {
(saved+1)[-1]=(char)128;
out.vi_write((saved+1)-1, 1);
}
out.vi_write(0,0); /* propagate EOF */
record_left=0; /* signal that no further data will be accepted */
return;
}
again:
assert(record_left>=1);
assert(len>=1);
/* Imp: locally cache vars saved* */
j=0;
if (saved_c==0) {
saved_rep=0; saved_c=1; b=(saved+1)[0]=*buf++; len--;
if (0==--record_left) goto put_norep;
if (0==len) return;
goto yes;
}
if (saved_c==1 && saved_rep==0) { yes:
if (*buf++==(saved+1)[0]) {
saved_rep=2; len--;
if (0==--record_left) goto put_rep;
} else {
(saved+1)[1]=buf[-1]; saved_c=2; len--;
if (0==--record_left) goto put_norep;
}
if (0==len) return;
}
assert(record_left>=1);
assert(len>=1);
assert((saved_rep==0 && saved_c>=2) || (saved_rep>=2 && saved_c==1));
if (saved_rep!=0) { /* Try to increase the repeating sequence */
assert(saved_rep>=2);
assert(saved_c==1);
assert(len>=1);
b=(saved+1)[0];
umax=len>128?128:len; if (umax>record_left) umax=record_left;
/* fprintf(stderr,"um1=%u\n", umax); */
if (umax>128-saved_rep) umax=128-saved_rep;
assert(umax>=1);
j=0; while (j!=umax && buf[j]==b) { j++; saved_rep++; }
if (j!=len || saved_rep==128) {
put_rep: /* Found a maximal repeat width */
(saved+1)[-1]=257-saved_rep;
out.vi_write((saved+1)-1,2);
/* fprintf(stderr,"ra=%u\n",saved_rep); */
if ((record_left-=j)==0) record_left=recordsize;
buf+=j;
saved_c=saved_rep=0;
if (0==(len-=j)) return;
goto again;
} /* Current repeat width can be further increased */
} else { /* Try to increase the non-repeating sequence */
assert(saved_c>=2);
if (buf[0]==(saved+1)[saved_c-1]) { /* this decision might be sub-optimal */
saved_c--;
/* Now: saved_c: non-repeat length, >=1 */
(saved+1)[-1]=saved_c-1;
out.vi_write((saved+1)-1, saved_c+1);
/* fprintf(stderr,"rb=%u\n",saved_c); */
// record_left++; /* because of saved_c--; but we would increase it later anyway */
// buf+=saved_c;
(saved+1)[0]=buf[0]; /* first matching char-pair data */
saved_c=1; saved_rep=2; /* make the new block a >=2 repeat */
record_left--; buf++;
if (0==--len) return;
goto again;
}
(saved+1)[saved_c++]=buf[0];
//record_left--;
//buf++;
//len--;
//if (saved_c==128) goto put_norep;
//if (0==len) return;
umax=len>128?128:len; if (umax>record_left) umax=record_left;
if (umax>128-saved_c) umax=128-saved_c;
/* fprintf(stderr,"um2=%u\n", umax); */
assert(umax>=1);
j=1; while (j!=umax && buf[j]!=buf[j-1]) (saved+1)[saved_c++]=buf[j++];
if (j!=len || saved_c==128) {
put_norep: /* Found a maximal non-repeat width */
(saved+1)[-1]=saved_c-1;
out.vi_write((saved+1)-1, saved_c+1);
/* fprintf(stderr,"rc=%u\n",saved_c); */
if ((record_left-=j)==0) record_left=recordsize;
buf+=j;
saved_c=saved_rep=0;
if (0==(len-=j)) return;
goto again;
} /* Current non-repeat width can be further increased */
}
assert(j==len);
record_left-=j;
assert(saved_rep<128);
assert(saved_c<128);
}
/* --- */
#if USE_BUILTIN_ZIP
// bool FlateEncode::locked=false;
#if PTS_DEFL_RIPPED_ZLIB
FlateEncode::FlateEncode(GenBuffer::Writable &out_, unsigned level_)
:out(out_) {
// assert(!locked); locked /* locking is not necessary anymore */
// pts_deflate_init(&fs); /* obsolete */
zs.total_in=0;
zs.total_out=0;
zs.workspace=workspace;
zs.msg=(char*)0;
zs.state=(struct zlib_internal_state*)0;
zs.data_type=Z_UNKNOWN; /* Imp: do we have to initialize it? */
assert(zlib_deflate_workspacesize()+(unsigned)0<sizeof(workspace) && "Flate workspace too small");
if (Z_OK!=zlib_deflateInit(&zs, level_))
Error::sev(Error::EERROR) << "Flate init error (out of memory?)" << (Error*)0;
}
void FlateEncode::vi_write(char const*buf, slen_t len) {
slen_t got, zgot;
/* fprintf(stderr,"wcall\n"); */
zs.next_in=(unsigned char*)const_cast<char*>(buf); zs.avail_in=len;
if (len==0) { /* flush all output */
do { /* SUXX: C compiler should emit a warning: while (1) { ... } while(...); */
zs.next_out=(unsigned char*)obuf; zs.avail_out=sizeof(obuf);
/* fprintf(stderr,"wdone zai=%d zao=%d\n", zs.avail_in, zs.avail_out); */
if (Z_STREAM_END!=(zgot=zlib_deflate(&zs, Z_FINISH)) && Z_OK!=zgot)
Error::sev(Error::EERROR) << "Flate close error: " << zs.msg << (Error*)0;
got=sizeof(obuf)-zs.avail_out;
/* fprintf(stderr, "got=%u zgot=%d Z_OK=%d\n", got, zgot, Z_OK); */
if (got>0) out.vi_write(obuf, got);
} while (zgot==Z_OK);
/* Dat: zlib_deflateEnd() will be called in the destructur */
out.vi_write(0,0); /* Signal EOF */
/* Dat: zlib_deflate() adds RFC 1950 header and adler32 checksum automatically */
} else {
do {
/* fprintf(stderr,"writ\n"); */
zs.next_out=(unsigned char*)obuf; zs.avail_out=sizeof(obuf);
if (Z_OK!=zlib_deflate(&zs, 0))
Error::sev(Error::EERROR) << "Flate write error: " << zs.msg << (Error*)0;
if (0<(got=sizeof(obuf)-zs.avail_out)) out.vi_write(obuf, got);
} while (0!=zs.avail_in);
}
}
#else
FlateEncode::FlateEncode(GenBuffer::Writable &out_, unsigned level_)
:out(out_)
,s1(1)
,s2(0)
,had_header(false) {
// assert(!locked); locked /* locking is not necessary anymore */
// pts_deflate_init(&fs); /* obsolete */
fs=pts_defl_new(
/*zpfwrite=*/ gen_write,
/*zpfmalloc=*/ gen_malloc,
/*zpffree=*/ gen_free,
/*pack_level=*/ level_,
/*zfile=*/ (void*)&out_
);
if (fs==NULL) Error::sev(Error::EERROR) << "Flate init error (out of memory?)" << (Error*)0;
}
void *FlateEncode::gen_malloc(unsigned n) {
return operator new(n);
// return new char[n];
}
void FlateEncode::gen_free(void *p) {
/*return*/ operator delete(p);
// delete [] (char*)p;
}
void FlateEncode::vi_write(char const*buf, slen_t len) {
register s_t sold;
register char const*p=buf; char const*pend=p+len;
(void)sold;
if (!had_header) {
out.vi_write("\x78\xda",2); /* ZLIB (RFC 1950): max compression header */
had_header=true;
}
if (len==0) { /* EOF: send trailer */
fs->deflate2(0,0,fs); /* Let the compressor flush its buffers. */
if (fs->err!=0) Error::sev(Error::EERROR) << "Flate compression error" << (Error*)0;
fs->delete2(fs);
fs=(struct pts_defl_interface*)NULL;
if (s1>=65521) s1-=65521;
if (s2>=65521) s2-=65521;
unsigned char trailer[4];
trailer[0]=s2>>8; trailer[1]=s2&255; trailer[2]=s1>>8; trailer[3]=s1&255;
out.vi_write((char const*)trailer,4);
out.vi_write(0,0); /* Signal EOF */
return;
}
assert(fs!=NULL);
/* From rfc1950.txt:
Adler-32 is composed of two sums accumulated per byte: s1 is
the sum of all bytes, s2 is the sum of all s1 values. Both sums
are done modulo 65521. s1 is initialized to 1, s2 to zero. The
Adler-32 checksum is stored as s2*65536 + s1 in most-
significant-byte first (network) order.
*/
/* Update Adler-32 checksum */
while (p!=pend) {
#if SIZEOF_INT>2
if ((s1+=*(unsigned char const*)p)>=65521) s1-=65521;
if ((s2+=s1)>=65521) s2-=65521;
#elif SIZEOF_SHORT==2
sold=s1;
if ((s1+=*(unsigned char const*)p))<sold) s1+=15; /* 15==65536-21 */
sold=s2;
s2=(s2+s1)&0xffff;
if ((s2+=s1)<sold) s2+=15;
#else
/* vvv 0xffff is needed since unsigned short may be > 0..65535 */
sold=s1;
s1=(s1+*(unsigned char const*)p)&0xffff;
if (s1<sold) s1+=15; /* 15==65536-21 */
sold=s2;
s2=(s2+s1)&0xffff;
if (s2<sold) s2+=15;
#endif
p++;
}
while (len>=0x8000) { fs->deflate2(const_cast<char*>(buf),0x8000, fs); len-=0x8000; buf+=0x8000; }
if (len!=0) fs->deflate2(const_cast<char*>(buf),len, fs);
}
#endif /* PTS_DEFL_RIPPED_ZLIB */
#endif /* USE_BUILTIN_ZIP */
int /*FlateEncode::*/gen_write(char *block, unsigned len, void *zfile) {
static_cast<GenBuffer::Writable*>(zfile)->vi_write(block, len);
return 0;
}
/* --- */
#if USE_BUILTIN_FAXE
void* CCITTFaxEncode::gen_xalloc(unsigned n) {
return operator new(n);
// void *ret; if ((ret=malloc(n))==0) abort(); return ret;
}
void CCITTFaxEncode::gen_free(void *ptr) {
/*return*/ operator delete(ptr);
// free(ptr);
}
void CCITTFaxEncode::gen_memset(void *s, int c, unsigned n) {
/*return*/ memset(s,c,n);
}
void CCITTFaxEncode::gen_memcpy(void *dest, const void *src, unsigned n) {
/*return*/ memcpy(dest, src, n);
}
CCITTFaxEncode::CCITTFaxEncode(GenBuffer::Writable &out_, slendiff_t K, slen_t Columns, bool EndOfLine, bool BlackIs1): out(out_) {
sCFEs.memset_=gen_memset;
sCFEs.xalloc_=gen_xalloc;
sCFEs.free_=gen_free;
sCFEs.memcpy_=gen_memcpy;
s_CFE_template.set_defaults((stream_state*)&sCFEs);
sCFEs.K=K;
sCFEs.Columns=Columns;
sCFEs.EndOfLine=EndOfLine;
sCFEs.BlackIs1=BlackIs1;
const int cf_max_height=(unsigned)-1/2-100; /* Dat: was slen_t */
if (sCFEs.K < -cf_max_height || sCFEs.K > cf_max_height /* Dat: .K is an int */
|| sCFEs.Columns < 0 || sCFEs.Columns > cfe_max_width /* Dat: .Columns is an int */
|| sCFEs.Rows < 0 || sCFEs.Rows > cf_max_height /* Dat: .Rows is an int */
|| sCFEs.DamagedRowsBeforeError < 0
|| sCFEs.DamagedRowsBeforeError > cf_max_height /* Dat: .DamagedRowsBeforeError is an int */
|| sCFEs.DecodedByteAlign < 1 || sCFEs.DecodedByteAlign > 16
|| (sCFEs.DecodedByteAlign & (sCFEs.DecodedByteAlign - 1)) != 0
) Error::sev(Error::EERROR) << "pts_fax: invalid params" << (Error*)0;
if (0!=s_CFE_template.init((stream_state*)&sCFEs))
Error::sev(Error::EERROR) << "pts_fax: init failed" << (Error*)0;
#if __CHECKER__
memset(&r, 0, sizeof(r));
memset(&w, 0, sizeof(w));
#endif
r.ptr=rlimit=rbuf-1;
hard=rbuf+sizeof(rbuf)-1;
assert(hard-r.ptr>=(int)s_CFE_template.min_in_size);
}
void CCITTFaxEncode::vi_write(char const*buf, slen_t len) {
int pog;
// unsigned char *save_wptr;
if (len==0) {
r.limit=rlimit;
do {
w.ptr=wbuf-1;
w.limit=wbuf+sizeof(wbuf)-1;
assert(w.limit-w.ptr>=(int)s_CFE_template.min_out_size);
pog=s_CFE_template.process((stream_state*)&sCFEs, &r, &w, /*last:*/ true);
// fprintf(stderr, "pog=%d write=%d last=%d\n", pog, w.ptr-(wbuf-1), true);
assert(pog!=PTSFAX_ERRC); /* /CCITTFaxEncode filter must accept any input */
assert(pog!=PTSFAX_EOFC); /* /CCITTFaxEncode filter doesn't have EOD markers */
if (w.ptr!=wbuf-1) out.vi_write((char const*)wbuf, w.ptr-(wbuf-1));
} while (pog==1);
s_CFE_template.release((stream_state*)&sCFEs);
out.vi_write(0,0); /* propagate EOF */
return;
}
while (len!=0) {
assert(r.ptr==rbuf-1);
assert(hard>rlimit);
unsigned clen=hard-rlimit;
if (clen>len) clen=len;
assert(clen>0);
// fprintf(stderr, "clen=%u\n", clen);
memcpy(rlimit+1, buf, clen);
rlimit+=clen;
buf+=clen;
len-=clen;
/* if (r.ptr==rlimit) break; */
r.limit=rlimit;
do {
w.ptr=wbuf-1;
w.limit=wbuf+sizeof(wbuf)-1;
assert(w.limit-w.ptr>=(int)s_CFE_template.min_out_size);
pog=s_CFE_template.process((stream_state*)&sCFEs, &r, &w, /*last:*/ false);
// fprintf(stderr, "len=%d pog=%d write=%d last=%d\n", len, pog, w.ptr-(wbuf-1), false);
assert(pog!=PTSFAX_ERRC); /* /CCITTFaxEncode filter must accept any input */
assert(pog!=PTSFAX_EOFC); /* /CCITTFaxEncode filter doesn't have EOD markers */
if (w.ptr!=wbuf-1) out.vi_write((char const*)wbuf, w.ptr-(wbuf-1));
} while (pog==1);
// assert(pog!=1); /* not true: output space is enough (sizeof(wbuf)>min_out_size) */
assert(pog==0); /* more input is needed */
if (r.ptr!=rbuf-1) {
// fprintf(stderr, "limit=%d\n", rlimit-r.ptr);
memmove(rbuf, r.ptr+1, rlimit-r.ptr);
rlimit=rbuf-1+(rlimit-r.ptr);
r.ptr=rbuf-1;
}
}
// fprintf(stderr, "done\n");
}
#endif /* USE_BUILTIN_FAXE */
/* --- */