This repository has been archived by the owner on Feb 14, 2023. It is now read-only.
/
jpgcoder.cc
5679 lines (5141 loc) · 216 KB
/
jpgcoder.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*-mode:c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/**
Copyright (c) 2006...2016, Matthias Stirner and HTW Aalen University
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**/
volatile int volatile1024 = 1024;
#include "../vp8/util/memory.hh"
#include "../vp8/util/debug.hh"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <fcntl.h>
#include <assert.h>
#include <ctime>
#include <memory>
#include <atomic>
#include <signal.h>
#ifndef _WIN32
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#else
#include <io.h>
#include <chrono>
#include <ctime>
#endif
#ifdef __linux__
#include <sys/sysinfo.h>
#include <linux/seccomp.h>
#include <sys/prctl.h>
#include <sys/syscall.h>
#endif
#ifndef USE_SCALAR
#include <emmintrin.h>
#include <immintrin.h>
#endif
#include "jpgcoder.hh"
#include "recoder.hh"
#include "bitops.hh"
#include "htables.hh"
#include "component_info.hh"
#include "uncompressed_components.hh"
#include "vp8_decoder.hh"
#include "vp8_encoder.hh"
#include "simple_decoder.hh"
#include "simple_encoder.hh"
#include "fork_serve.hh"
#include "socket_serve.hh"
#include "validation.hh"
#include "../io/ZlibCompression.hh"
#include "../io/BrotliCompression.hh"
#include "../io/MemReadWriter.hh"
#include "../io/BufferedIO.hh"
#include "../io/Zlib0.hh"
#include "../io/Seccomp.hh"
#include "../vp8/encoder/vpx_bool_writer.hh"
#include "generic_compress.hh"
#ifdef EMSCRIPTEN
#include <emscripten.h>
#endif
unsigned char g_zlib_0_writer[sizeof(Sirikata::Zlib0Writer)];
void * uninit_g_zlib_0_writer = &g_zlib_0_writer[0];
unsigned char EOI[ 2 ] = { 0xFF, 0xD9 }; // EOI segment
extern int r_bitcount;
int g_argc = 0;
const char** g_argv = NULL;
#ifndef GIT_REVISION
#include "version.hh"
#ifndef GIT_REVISION
#define GIT_REVISION "unknown"
#endif
#endif
bool g_permissive = false;
bool fast_exit = true;
#ifdef SKIP_VALIDATION
bool g_skip_validation = true;
#else
bool g_skip_validation = false;
#endif
#define QUANT(cmp,bpos) ( cmpnfo[cmp].qtable[ bpos ] )
#define MAX_V(cmp,bpos) ( ( freqmax[bpos] + QUANT(cmp,bpos) - 1 ) / QUANT(cmp,bpos) )
#define ENVLI(s,v) ( ( v > 0 ) ? v : ( v - 1 ) + ( 1 << s ) )
#define DEVLI(s,n) ((s) == 0 ? (n) : ( ( (n) >= ( 1 << ((s) - 1) ) ) ? (n) : (n) + 1 - ( 1 << (s) ) ))
#define E_ENVLI(s,v) ( v - ( 1 << s ) )
#define E_DEVLI(s,n) ( n + ( 1 << s ) )
#define COS_DCT(l,s,n) ( cos( ( ( 2 * l + 1 ) * s * M_PI ) / ( 2 * n ) ) )
#define C_DCT(n) ( ( n == 0 ) ? ( 1 ) : ( sqrt( 2 ) ) )
#define DCT_SCALE sqrt( 8 )
#define ABS(v1) ( (v1 < 0) ? -v1 : v1 )
#define ABSDIFF(v1,v2) ( (v1 > v2) ? (v1 - v2) : (v2 - v1) )
#define IPOS(w,v,h) ( ( v * w ) + h )
#define NPOS(n1,n2,p) ( ( ( p / n1 ) * n2 ) + ( p % n1 ) )
#define ROUND_F(v1) ( (v1 < 0) ? (int) (v1 - 0.5) : (int) (v1 + 0.5) )
#define B_SHORT(v1,v2) ( ( ((int) v1) << 8 ) + ((int) v2) )
#define CLAMPED(l,h,v) ( ( v < l ) ? l : ( v > h ) ? h : v )
#define MEM_ERRMSG "out of memory error"
#define FRD_ERRMSG "could not read file / file not found: %s"
#define FWR_ERRMSG "could not write file / file write-protected: %s"
size_t local_atoi(const char *data);
namespace TimingHarness {
Sirikata::Array1d<Sirikata::Array1d<uint64_t, NUM_STAGES>, MAX_NUM_THREADS> timing = {{{{0}}}};
uint64_t get_time_us(bool force) {
#ifdef _WIN32
return std::chrono::duration_cast<std::chrono::microseconds>
(std::chrono::high_resolution_clock::now().time_since_epoch()).count();
#else
if (force || !g_use_seccomp) {
struct timeval val = {0,0};
gettimeofday(&val,NULL);
uint64_t retval = val.tv_sec;
retval *= 1000000;
retval += val.tv_usec;
return retval;
}
#endif
return 0;
}
const char * stage_names[] = {FOREACH_TIMING_STAGE(GENERATE_TIMING_STRING) "EOF"};
void print_results() {
if (!g_use_seccomp) {
uint64_t earliest_time = get_time_us();
for (int i = 0; i < NUM_STAGES; ++i) {
for (unsigned int j = 0; j < MAX_NUM_THREADS && j < NUM_THREADS; ++j) {
if (timing[j][i] && timing[j][i] < earliest_time) {
earliest_time = timing[j][i];
}
}
}
for (int i = 0; i < NUM_STAGES; ++i) {
for (unsigned int j = 0; j < MAX_NUM_THREADS && j < NUM_THREADS; ++j) {
if (timing[j][i]) {
fprintf(stderr,
"%s\t(%d)\t%f\n",
stage_names[i], j,
(timing[j][i] - earliest_time) * 0.000001);
}
}
}
}
}
}
/* -----------------------------------------------
struct & enum declarations
----------------------------------------------- */
enum {
JPG_READ_BUFFER_SIZE = 1024 * 256,
ABIT_WRITER_PRELOAD = 4096 * 1024 + 1024
};
enum ACTION {
comp = 1,
forkserve = 2,
socketserve = 3,
info = 4,
lepton_concatenate = 5
};
namespace {
uint32_t LEtoUint32(const uint8_t*buffer) {
uint32_t retval = buffer[3];
retval <<=8;
retval |= buffer[2];
retval <<= 8;
retval |= buffer[1];
retval <<= 8;
retval |= buffer[0];
return retval;
}
}
void uint32toLE(uint32_t value, uint8_t *retval) {
retval[0] = uint8_t(value & 0xff);
retval[1] = uint8_t((value >> 8) & 0xff);
retval[2] = uint8_t((value >> 16) & 0xff);
retval[3] = uint8_t((value >> 24) & 0xff);
}
/* -----------------------------------------------
function declarations: main interface
----------------------------------------------- */
// returns the max size of the input file
int initialize_options( int argc, const char*const* argv );
void execute(const std::function<bool()> &);
void show_help( void );
/* -----------------------------------------------
function declarations: main functions
----------------------------------------------- */
bool check_file(int fd_in, int fd_out, uint32_t max_file_size, bool force_zlib0,
bool is_embedded_jpeg, Sirikata::Array1d<uint8_t, 2> two_byte_header,
bool is_socket);
template <class stream_reader>
bool read_jpeg(std::vector<std::pair<uint32_t,
uint32_t>> *huff_input_offset,
stream_reader *jpg_str_in,
Sirikata::Array1d<uint8_t, 2> header,
bool is_embedded_jpeg);
bool read_jpeg_wrapper(std::vector<std::pair<uint32_t,
uint32_t>> *huff_input_offset,
ibytestream *jpg_str_in,
Sirikata::Array1d<uint8_t, 2> header,
bool is_embedded_jpeg) {
return read_jpeg(huff_input_offset, jpg_str_in, header, is_embedded_jpeg);
}
bool read_jpeg_and_copy_to_side_channel(std::vector<std::pair<uint32_t,
uint32_t>> *huff_input_offset,
ibytestreamcopier *jpg_str_in,
Sirikata::Array1d<uint8_t, 2> header,
bool is_embedded_jpeg) {
return read_jpeg(huff_input_offset, jpg_str_in, header, is_embedded_jpeg);
}
struct MergeJpegProgress;
bool decode_jpeg(const std::vector<std::pair<uint32_t,
uint32_t> > &huff_input_offset,
std::vector<ThreadHandoff>*row_thread_handoffs);
bool recode_jpeg( void );
bool adapt_icos( void );
bool check_value_range( void );
bool write_ujpg(std::vector<ThreadHandoff> row_thread_handoffs,
std::vector<uint8_t, Sirikata::JpegAllocator<uint8_t> >*jpeg_file_raw_bytes);
bool read_ujpg( void );
unsigned char read_fixed_ujpg_header( void );
bool reset_buffers( void );
/* -----------------------------------------------
function declarations: jpeg-specific
----------------------------------------------- */
bool is_jpeg_header(Sirikata::Array1d<uint8_t, 2> header) {
return header[0] == 0xFF && header[1] == 0xD8;
}
// baseline single threaded decoding need only two rows of the image in memory
bool setup_imginfo_jpg(bool only_allocate_two_image_rows);
bool parse_jfif_jpg( unsigned char type, unsigned int len, uint32_t alloc_len, unsigned char* segment );
bool rebuild_header_jpg( void );
int decode_block_seq( abitreader* huffr, huffTree* dctree, huffTree* actree, short* block );
int encode_block_seq( abitwriter* huffw, huffCodes* dctbl, huffCodes* actbl, short* block );
int decode_dc_prg_fs( abitreader* huffr, huffTree* dctree, short* block );
int encode_dc_prg_fs( abitwriter* huffw, huffCodes* dctbl, short* block );
int decode_ac_prg_fs( abitreader* huffr, huffTree* actree, short* block,
unsigned int* eobrun, int from, int to );
int encode_ac_prg_fs( abitwriter* huffw, huffCodes* actbl, short* block,
unsigned int* eobrun, int from, int to );
int decode_dc_prg_sa( abitreader* huffr, short* block );
int encode_dc_prg_sa( abitwriter* huffw, short* block );
int decode_ac_prg_sa( abitreader* huffr, huffTree* actree, short* block,
unsigned int* eobrun, int from, int to );
int encode_ac_prg_sa( abitwriter* huffw, abytewriter* storw, huffCodes* actbl,
short* block, unsigned int* eobrun, int from, int to );
int decode_eobrun_sa( abitreader* huffr, short* block, unsigned int* eobrun, int from, int to );
int encode_eobrun( abitwriter* huffw, huffCodes* actbl, unsigned int* eobrun );
int encode_crbits( abitwriter* huffw, abytewriter* storw );
int next_huffcode( abitreader *huffw, huffTree *ctree , Billing min_bill, Billing max_bill);
int next_mcupos( int* mcu, int* cmp, int* csc, int* sub, int* dpos, int* rstw, int cs_cmpc);
int next_mcuposn( int* cmp, int* dpos, int* rstw );
int skip_eobrun( int* cmp, int* dpos, int* rstw, unsigned int* eobrun );
bool build_huffcodes( unsigned char *clen, uint32_t clenlen, unsigned char *cval, uint32_t cvallen,
huffCodes *hc, huffTree *ht );
/* -----------------------------------------------
function declarations: developers functions
----------------------------------------------- */
// these are developers functions, they are not needed
// in any way to compress jpg or decompress ujg
bool write_hdr( void );
bool write_huf( void );
bool write_info( void );
clock_t pre_byte = 0;
clock_t post_byte = 0;
clock_t read_done = 0;
clock_t overall_start = 0;
/* -----------------------------------------------
global variables: data storage
----------------------------------------------- */
size_t g_decompression_memory_bound = 0;
Sirikata::Array1d<Sirikata::Array1d<unsigned short, 64>, 4> qtables; // quantization tables
Sirikata::Array1d<Sirikata::Array1d<huffCodes, 4>, 2> hcodes; // huffman codes
Sirikata::Array1d<Sirikata::Array1d<huffTree, 4>, 2> htrees; // huffman decoding trees
Sirikata::Array1d<Sirikata::Array1d<unsigned char, 4>, 2> htset;// 1 if huffman table is set
bool embedded_jpeg = false;
unsigned char* grbgdata = NULL; // garbage data
unsigned char* hdrdata = NULL; // header data
unsigned char* huffdata = NULL; // huffman coded data
int hufs = 0 ; // size of huffman data
uint32_t hdrs = 0 ; // size of header
uint32_t zlib_hdrs = 0 ; // size of compressed header
size_t total_framebuffer_allocated = 0; // framebuffer allocated
int grbs = 0 ; // size of garbage
int prefix_grbs = 0; // size of prefix;
unsigned char *prefix_grbgdata = NULL; // if prefix_grb is specified, header is not prepended
std::vector<unsigned int> rstp; // restart markers positions in huffdata
std::vector<unsigned int> scnp; // scan start positions in huffdata
int rstc = 0 ; // count of restart markers
int scnc = 0 ; // count of scans
int rsti = 0 ; // restart interval
int8_t padbit = -1 ; // padbit (for huffman coding)
std::vector<unsigned char> rst_err; // number of wrong-set RST markers per scan
std::vector<unsigned int> rst_cnt;
bool rst_cnt_set = false;
int max_file_size = 0 ; // support for truncated jpegs 0 means full jpeg
size_t start_byte = 0; // support for producing a slice of jpeg
size_t jpeg_embedding_offset = 0;
unsigned int min_encode_threads = 1;
size_t max_encode_threads =
#ifdef DEFAULT_SINGLE_THREAD
1
#else
MAX_NUM_THREADS
#endif
;
UncompressedComponents colldata; // baseline sorted DCT coefficients
/* -----------------------------------------------
global variables: info about image
----------------------------------------------- */
// seperate info for each color component
Sirikata::Array1d<componentInfo, 4> cmpnfo;
int cmpc = 0; // component count
int imgwidth = 0; // width of image
int imgheight = 0; // height of image
int sfhm = 0; // max horizontal sample factor
int sfvm = 0; // max verical sample factor
int mcuv = 0; // mcus per line
unsigned int mcuh = 0; // mcus per collumn
int mcuc = 0; // count of mcus
bool early_eof_encountered = false;
int max_cmp = 0; // the maximum component in a truncated image
int max_bpos = 0; // the maximum band in a truncated image
int max_dpos[4] = {}; // the maximum dpos in a truncated image
int max_sah = 0; // the maximum bit in a truncated image
void standard_eof(abytewriter* hdrw, abytewriter* huffw) {
// get pointer for header data & size
hdrdata = hdrw->getptr_aligned();
hdrs = hdrw->getpos();
// get pointer for huffman data & size
huffdata = huffw->getptr_aligned();
hufs = huffw->getpos();
}
void early_eof(abytewriter* hdrw, abytewriter* huffw) {
early_eof_encountered = true;
standard_eof(hdrw, huffw);
}
/* -----------------------------------------------
global variables: info about current scan
----------------------------------------------- */
int cs_cmpc = 0 ; // component count in current scan
Sirikata::Array1d<int, 4> cs_cmp = {{ 0 }}; // component numbers in current scan
int cs_from = 0 ; // begin - band of current scan ( inclusive )
int cs_to = 0 ; // end - band of current scan ( inclusive )
int cs_sah = 0 ; // successive approximation bit pos high
int cs_sal = 0 ; // successive approximation bit pos low
void kill_workers(void * workers, uint64_t num_workers);
BaseDecoder* g_decoder = NULL;
GenericWorker * get_worker_threads(unsigned int num_workers) {
// in this case decoding is asymmetric to encoding, just forget the assert
if (NUM_THREADS < 2) {
return NULL;
}
GenericWorker* retval = GenericWorker::get_n_worker_threads(num_workers);
TimingHarness::timing[0][TimingHarness::TS_THREAD_STARTED] = TimingHarness::get_time_us();
return retval;
}
template <class BoolDecoder>VP8ComponentDecoder<BoolDecoder> *makeBoth(bool threaded, bool start_workers) {
VP8ComponentDecoder<BoolDecoder> *retval = new VP8ComponentDecoder<BoolDecoder>(threaded);
TimingHarness::timing[0][TimingHarness::TS_MODEL_INIT] = TimingHarness::get_time_us();
if (start_workers) {
retval->registerWorkers(get_worker_threads(
NUM_THREADS
),
NUM_THREADS
);
}
return retval;
}
template <class BoolDecoder>BaseEncoder *makeEncoder(bool threaded, bool start_workers) {
TimingHarness::timing[0][TimingHarness::TS_MODEL_INIT_BEGIN] = TimingHarness::get_time_us();
VP8ComponentEncoder<BoolDecoder> * retval = new VP8ComponentEncoder<BoolDecoder>(threaded, IsDecoderAns<BoolDecoder>::IS_ANS);
TimingHarness::timing[0][TimingHarness::TS_MODEL_INIT] = TimingHarness::get_time_us();
if (start_workers) {
retval->registerWorkers(get_worker_threads(NUM_THREADS - 1), NUM_THREADS - 1);
}
return retval;
}
BaseDecoder *makeDecoder(bool threaded, bool start_workers, bool ans) {
if (ans) {
#ifdef ENABLE_ANS_EXPERIMENTAL
return makeBoth<ANSBoolReader>(threaded, start_workers);
#else
always_assert(false && "ANS compile flag not selected");
#endif
}
return makeBoth<VPXBoolReader>(threaded, start_workers);
}
/* -----------------------------------------------
global variables: info about files
----------------------------------------------- */
int jpgfilesize; // size of JPEG file
int ujgfilesize; // size of UJG file
int jpegtype = 0; // type of JPEG coding: 0->unknown, 1->sequential, 2->progressive
F_TYPE filetype; // type of current file
F_TYPE ofiletype = LEPTON; // desired type of output file
bool g_do_preload = false;
std::unique_ptr<BaseEncoder> g_encoder;
std::unique_ptr<BaseDecoder> g_reference_to_free;
ServiceInfo g_socketserve_info;
bool g_threaded = true;
// this overrides the progressive bit in the header so that legacy progressive files may be decoded
bool g_force_progressive = false;
bool g_allow_progressive =
#ifdef DEFAULT_ALLOW_PROGRESSIVE
true
#else
false
#endif
;
bool g_unkillable = false;
uint64_t g_time_bound_ms = 0;
int g_inject_syscall_test = 0;
bool g_force_zlib0_out = false;
Sirikata::DecoderReader* str_in = NULL; // input stream
bounded_iostream* str_out = NULL; // output stream
// output stream
IOUtil::FileWriter * ujg_out = NULL;
IOUtil::FileReader * ujg_base_in = NULL;
const char** filelist = NULL; // list of files to process
int file_cnt = 0; // count of files in list (1 for input only)
int file_no = 0; // number of current file
/* -----------------------------------------------
global variables: messages
----------------------------------------------- */
std::string errormessage;
std::atomic<int> errorlevel(0);
// meaning of errorlevel:
// -1 -> wrong input
// 0 -> no error
// 1 -> warning
// 2 -> fatal error
/* -----------------------------------------------
global variables: settings
----------------------------------------------- */
int verbosity = 0; // level of verbosity
bool overwrite = false; // overwrite files yes / no
int err_tresh = 1; // error threshold ( proceed on warnings yes (2) / no (1) )
bool disc_meta = false; // discard meta-info yes / no
bool developer = false; // allow developers functions yes/no
ACTION action = comp; // what to do with JPEG/UJG files
FILE* msgout = stderr; // stream for output of messages
bool pipe_on = false; // use stdin/stdout instead of filelist
void sig_nop(int){}
/* -----------------------------------------------
global variables: info about program
----------------------------------------------- */
unsigned char ujgversion = 1;
bool g_even_thread_split = false;
uint8_t get_current_file_lepton_version() {
return ujgversion;
}
static const char* appname = "lepton";
static const unsigned char ujg_header[] = { 'U', 'J' };
static const unsigned char lepton_header[] = { 0xcf, 0x84 }; // the tau symbol for a tau lepton in utf-8
static const unsigned char zlepton_header[] = { 0xce, 0xb6 }; // the zeta symbol for a zlib compressed lepton
FILE * timing_log = NULL;
char current_operation = '\0';
#ifdef _WIN32
clock_t current_operation_begin = 0;
clock_t current_operation_first_byte = 0;
clock_t current_operation_end = 0;
#else
struct timeval current_operation_begin = {0, 0};
struct timeval current_operation_first_byte = {0, 0};
struct timeval current_operation_end = {0, 0};
#endif
void timing_operation_start( char operation ) {
#ifndef _WIN32
if (g_use_seccomp) {
return;
}
current_operation = operation;
#ifdef _WIN32
current_operation_begin = clock();
current_operation_first_byte = 0;
current_operation_end = 0;
#else
gettimeofday(¤t_operation_begin, NULL);
memset(¤t_operation_first_byte, 0, sizeof(current_operation_first_byte));
memset(¤t_operation_end, 0, sizeof(current_operation_end));
#endif
fprintf(stderr,"START ACHIEVED %ld %ld\n",
(long)current_operation_begin.tv_sec, (long)current_operation_begin.tv_usec );
#endif
}
void timing_operation_first_byte( char operation ) {
#ifndef _WIN32
if (g_use_seccomp) {
return;
}
dev_assert(current_operation == operation);
#ifdef _WIN32
if (current_operation_first_byte == 0) {
current_operation_first_byte = clock();
}
#else
if (current_operation_first_byte.tv_sec == 0 &&
current_operation_first_byte.tv_usec == 0) {
gettimeofday(¤t_operation_first_byte, NULL);
}
#endif
#endif
}
void timing_operation_complete( char operation ) {
#ifndef _WIN32
if (g_use_seccomp) {
return;
}
dev_assert(current_operation == operation);
#ifdef _WIN32
current_operation_end = clock();
if (timing_log) {
double begin_to_end = (current_operation_end - current_operation_begin) / (double)CLOCKS_PER_SEC;
double begin_to_first_byte = begin_to_end;
if (current_operation_first_byte != 0) { // if we were successful
begin_to_first_byte = (current_operation_first_byte - current_operation_begin) / (double)CLOCKS_PER_SEC;
}
fprintf(timing_log, "%c %f %f\n", current_operation, begin_to_first_byte, begin_to_end);
fflush(timing_log);
}
current_operation_end = 0;
current_operation_begin = 0;
current_operation_first_byte = 0;
#else
gettimeofday(¤t_operation_end, NULL);
if (timing_log) {
double begin = current_operation_begin.tv_sec + (double)current_operation_begin.tv_usec / 1000000.;
double end = current_operation_end.tv_sec + (double)current_operation_end.tv_usec / 1000000.;
double first_byte = current_operation_first_byte.tv_sec + (double)current_operation_first_byte.tv_usec / 1000000.;
double begin_to_end = end - begin;
double begin_to_first_byte = begin_to_end;
if (current_operation_first_byte.tv_sec != 0) { // if we were successful
begin_to_first_byte = first_byte - begin;
}
fprintf(timing_log, "%c %f %f\n", current_operation, begin_to_first_byte, begin_to_end);
fflush(timing_log);
}
memset(¤t_operation_end, 0, sizeof(current_operation_end));
memset(¤t_operation_begin, 0, sizeof(current_operation_begin));
memset(¤t_operation_first_byte, 0, sizeof(current_operation_first_byte));
#endif
#endif
}
size_t local_atoi(const char *data) {
const char * odata = data;
size_t retval = 0;
int counter = 0;
while (*data) {
if (*data >= '0' && *data <='9') {
retval *= 10;
retval += *data - '0';
++data;
++counter;
if (counter > 16) {
fprintf(stderr, "Could not allocate so much memory %s\n", odata);
exit(1);
}
} else if ('M' == *data) {
retval *= 1024 * 1024;
break;
} else if ('K' == *data) {
retval *= 1024;
break;
} else {
fprintf(stderr, "Could not allocate alphanumeric memory %s\n", odata);
exit(1);
}
}
return retval;
}
bool starts_with(const char * a, const char * b) {
while (*b) {
if (*a != *b) {
return false;
}
++a;
++b;
}
return true;
}
void compute_thread_mem(const char * arg,
size_t * mem_init,
size_t * thread_mem_init,
bool *needs_huge_pages,
bool *avx2upgrade) {
if (strcmp(arg, "-hugepages") == 0) {
*needs_huge_pages = true;
}
if ( strcmp(arg, "-avx2upgrade") == 0) {
*avx2upgrade = true;
}
if (strstr(arg, "-help")) {
show_help();
exit(0);
}
if (strcmp(arg, "-h") == 0) {
show_help();
exit(0);
}
const char mem_arg_name[]="-memory=";
const char thread_mem_arg_name[]="-threadmemory=";
if (starts_with(arg, mem_arg_name)) {
arg += strlen(mem_arg_name);
*mem_init = local_atoi(arg);
}
if (starts_with(arg, thread_mem_arg_name)) {
arg += strlen(thread_mem_arg_name);
*thread_mem_init = local_atoi(arg);
}
}
/* -----------------------------------------------
main-function
----------------------------------------------- */
#ifdef EMSCRIPTEN
const char *fake_argv[] = {
"lepton-scalar",
"-skipverify",
"-singlethread",
"-",
};
const int fake_argc = sizeof(fake_argv) / sizeof(char *);
int EMSCRIPTEN_KEEPALIVE main(void) {
const int argc = fake_argc;
const char **argv = fake_argv;
g_argc = argc;
g_argv = argv;
TimingHarness::timing[0][TimingHarness::TS_MAIN]
= TimingHarness::get_time_us(true);
size_t thread_mem_limit = 128 * 1024 * 1024;
size_t mem_limit = 1280 * 1024 * 1024 - thread_mem_limit * (MAX_NUM_THREADS - 1);
bool needs_huge_pages = false;
for (int i = 1; i < argc; ++i) {
bool avx2upgrade = false;
compute_thread_mem(argv[i],
&mem_limit,
&thread_mem_limit,
&needs_huge_pages,
&avx2upgrade);
}
// the system needs 33 megs of ram ontop of the uncompressed image buffer.
// This adds a few extra megs just to keep things real
UncompressedComponents::max_number_of_blocks = ( mem_limit / 4 ) * 3;
if (mem_limit > 48 * 1024 * 1024) {
UncompressedComponents::max_number_of_blocks = mem_limit - 36 * 1024 * 1024;
}
UncompressedComponents::max_number_of_blocks /= (sizeof(uint16_t) * 64);
int n_threads = MAX_NUM_THREADS - 1;
clock_t begin = 0, end = 1;
int error_cnt = 0;
int warn_cnt = 0;
int acc_jpgsize = 0;
int acc_ujgsize = 0;
int speed, bpms;
float cr;
errorlevel.store(0);
// read options from command line
int max_file_size = initialize_options( argc, argv );
if (action != forkserve && action != socketserve) {
// write program info to screen
fprintf( msgout, "%s v%i.0-%s\n",
appname, ujgversion, GIT_REVISION );
}
// check if user input is wrong, show help screen if it is
if ((file_cnt == 0 && action != forkserve && action != socketserve)
|| ((!developer) && ((action != comp && action != forkserve && action != socketserve)))) {
show_help();
return -1;
}
// (re)set program has to be done first
reset_buffers();
// process file(s) - this is the main function routine
begin = clock();
if (file_cnt > 2) {
show_help();
custom_exit(ExitCode::FILE_NOT_FOUND);
}
process_file(nullptr, nullptr, max_file_size, g_force_zlib0_out);
if (errorlevel.load() >= err_tresh) error_cnt++;
if (errorlevel.load() == 1 ) warn_cnt++;
if ( errorlevel.load() < err_tresh ) {
acc_jpgsize += jpgfilesize;
acc_ujgsize += ujgfilesize;
}
if (!g_use_seccomp) {
end = clock();
}
if (action != socketserve && action != forkserve) {
// show statistics
fprintf(msgout, "\n\n-> %i file(s) processed, %i error(s), %i warning(s)\n",
file_cnt, error_cnt, warn_cnt);
}
if ( ( file_cnt > error_cnt ) && ( verbosity > 0 ) )
if ( action == comp ) {
speed = (int) ( (double) (( end - begin ) * 1000) / CLOCKS_PER_SEC );
bpms = ( speed > 0 ) ? ( acc_jpgsize / speed ) : acc_jpgsize;
cr = ( acc_jpgsize > 0 ) ? ( 100.0 * acc_ujgsize / acc_jpgsize ) : 0;
fprintf( msgout, " --------------------------------- \n" );
fprintf( msgout, " time taken : %8i msec\n", speed );
fprintf( msgout, " avrg. byte per ms : %8i byte\n", bpms );
fprintf( msgout, " avrg. comp. ratio : %8.2f %%\n", cr );
fprintf( msgout, " --------------------------------- \n" );
}
return error_cnt == 0 ? 0 : 1;
}
#else
int app_main( int argc, char** argv )
{
g_argc = argc;
g_argv = (const char **)argv;
TimingHarness::timing[0][TimingHarness::TS_MAIN]
= TimingHarness::get_time_us(true);
size_t thread_mem_limit =
#ifdef HIGH_MEMORY
64 * 1024 * 1024
#else
3 * 1024 * 1024
#endif
;//8192;
size_t mem_limit =
#ifdef HIGH_MEMORY
1024 * 1024 * 1024 - thread_mem_limit * (MAX_NUM_THREADS - 1)
#else
176 * 1024 * 1024 - thread_mem_limit * (MAX_NUM_THREADS - 1)
#endif
;
bool needs_huge_pages = false;
for (int i = 1; i < argc; ++i) {
bool avx2upgrade = false;
compute_thread_mem(argv[i],
&mem_limit,
&thread_mem_limit,
&needs_huge_pages,
&avx2upgrade);
#ifndef __AVX2__
#ifndef __clang__
#ifndef _ARCH_PPC
#ifndef _WIN32
if (avx2upgrade &&
__builtin_cpu_supports("avx2")
) {
for (int j = i + 1; j < argc; ++j) {
argv[j - 1] = argv[j];
}
--argc;
argv[argc] = NULL; // since we have eliminated the upgrade arg...
size_t command_len = strlen(argv[0]);
size_t postfix_len = strlen("-avx") + 1;
char * command = (char*)malloc(postfix_len + command_len);
memcpy(command, argv[0], command_len);
memcpy(command + command_len, "-avx", postfix_len);
char * old_command = argv[0];
argv[0] = command;
execvp(command, argv);
argv[0] = old_command; // exec failed
}
#endif
#endif
#endif
#endif
}
// the system needs 33 megs of ram ontop of the uncompressed image buffer.
// This adds a few extra megs just to keep things real
UncompressedComponents::max_number_of_blocks = ( mem_limit / 4 ) * 3;
if (mem_limit > 48 * 1024 * 1024) {
UncompressedComponents::max_number_of_blocks = mem_limit - 36 * 1024 * 1024;
}
UncompressedComponents::max_number_of_blocks /= (sizeof(uint16_t) * 64);
int n_threads = MAX_NUM_THREADS;
#ifndef __linux__
n_threads += 4;
#endif
#if !defined(_WIN32) && !defined(EMSCRIPTEN)
Sirikata::memmgr_init(mem_limit,
thread_mem_limit,
n_threads,
256,
needs_huge_pages);
#endif
clock_t begin = 0, end = 1;
int error_cnt = 0;
int warn_cnt = 0;
int acc_jpgsize = 0;
int acc_ujgsize = 0;
int speed, bpms;
float cr;
errorlevel.store(0);
// read options from command line
int max_file_size = initialize_options( argc, argv );
if (action != forkserve && action != socketserve) {
// write program info to screen
fprintf( msgout, "%s v%i.0-%s\n",
appname, ujgversion, GIT_REVISION );
}
// check if user input is wrong, show help screen if it is
if ((file_cnt == 0 && action != forkserve && action != socketserve)
|| ((!developer) && ((action != lepton_concatenate && action != comp && action != forkserve && action != socketserve)))) {
show_help();
return -1;
}
// (re)set program has to be done first
reset_buffers();
// process file(s) - this is the main function routine
begin = clock();
if (file_cnt > 2 && action != lepton_concatenate) {
show_help();
custom_exit(ExitCode::FILE_NOT_FOUND);
}
if (action == forkserve) {
#ifdef _WIN32
abort(); // not implemented
#else
fork_serve();
#endif
} else if (action == socketserve) {
#ifdef _WIN32
abort(); // not implemented
#else
socket_serve(&process_file, max_file_size, g_socketserve_info);
#endif
} else {
process_file(nullptr, nullptr, max_file_size, g_force_zlib0_out);
}
if (errorlevel.load() >= err_tresh) error_cnt++;
if (errorlevel.load() == 1 ) warn_cnt++;
if ( errorlevel.load() < err_tresh ) {
acc_jpgsize += jpgfilesize;
acc_ujgsize += ujgfilesize;
}
if (!g_use_seccomp) {
end = clock();
}
if (action != socketserve && action != forkserve) {
// show statistics
fprintf(msgout, "\n\n-> %i file(s) processed, %i error(s), %i warning(s)\n",
file_cnt, error_cnt, warn_cnt);
}
if ( ( file_cnt > error_cnt ) && ( verbosity > 0 ) )
if ( action == comp ) {
speed = (int) ( (double) (( end - begin ) * 1000) / CLOCKS_PER_SEC );
bpms = ( speed > 0 ) ? ( acc_jpgsize / speed ) : acc_jpgsize;
cr = ( acc_jpgsize > 0 ) ? ( 100.0 * acc_ujgsize / acc_jpgsize ) : 0;
fprintf( msgout, " --------------------------------- \n" );
fprintf( msgout, " time taken : %8i msec\n", speed );
fprintf( msgout, " avrg. byte per ms : %8i byte\n", bpms );
fprintf( msgout, " avrg. comp. ratio : %8.2f %%\n", cr );
fprintf( msgout, " --------------------------------- \n" );
}
return error_cnt == 0 ? 0 : 1;
}
#endif
/* ----------------------- Begin of main interface functions -------------------------- */
/* -----------------------------------------------
reads in commandline arguments
----------------------------------------------- */
char g_dash[] = "-";
// returns the maximum file size
int initialize_options( int argc, const char*const * argv )
{
const char** tmp_flp;
int tmp_val;
int max_file_size = 0;
// get memory for filelist & preset with NULL
filelist = (const char**)custom_calloc(argc * sizeof(char*));
// preset temporary filelist pointer
tmp_flp = filelist;
// read in arguments
while ( --argc > 0 ) {
argv++;
// switches begin with '-'
if ( sscanf( (*argv), "-v%i", &tmp_val ) == 1 ){
verbosity = tmp_val;
verbosity = ( verbosity < 0 ) ? 0 : verbosity;
verbosity = ( verbosity > 2 ) ? 2 : verbosity;
}
else if ( strcmp((*argv), "-o" ) == 0 ) {
overwrite = true;