-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencode.c
1587 lines (1333 loc) · 40.7 KB
/
encode.c
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
// *************************************************************************************
//
// encode.c
//
// version 1.0
// 01/23/2016
// Written by Matthias Grün
//
// IceJPEG is open source and may be used freely, as long as the original author
// of the code is mentioned.
//
// You may redistribute it freely as long as no fees are charged and this information
// is included.
//
// If modifications are made to the code that alter its behavior and the modified code
// is made available to others or used in other products, the author is to receive
// a copy of the modified code.
//
// This code is provided as is and I do not and cannot guarantee the absence of bugs.
// Use of this code is at your own risk and I cannot be held liable for any
// damage that is caused by its use.
//
// *************************************************************************************
//
// This file constitutes the encoder part of my IceJPEG library, which was
// written mainly because I wanted to understand the inner workings of the
// JPEG format.
// Thus far it can only generate baseline compressed JPEGs.
// Grayscale images with one component as well as RGB images with 3 color
// channels are supported.
// Subsampling of each component is supported as well, both horizontally
// and vertically. The sampling factors are all configurable from the
// outside.
// The quantization tables used are the ones specified in the JPEG standard.
// Configuration of the compression quality is possible by passing a value
// between 1 and 100 in the quality field of the settings struct. This corresponds
// with the quality factor outlined in the JPEG standard.
// Huffman tables, however, are generated on-the-fly for each image.
// For RGB images, 6 Huffman tables are generated: 3 for the DC value of each
// component and 3 for the AC values of each component.
//
// Restart markers are supported as well. The restart interval cannot currently
// be set from the outside and, if restart is enabled, a restart marker will
// be output after each line of MCUs.
//
// The code that performs the DCT was taken from jpeglib which slight modifications.
//
// *************************************************************************************
#include "encode.h"
#include "common.h"
#include "DCT.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
//#define _JPEG_ENCODER_DEBUG
#define _JPEG_ENCODER_STATS
#define UPSCALE(x) ((x) << PRECISION)
#define DESCALE(x) (((x) + (1 << (PRECISION - 1))) >> PRECISION)
#define YR 77
#define YG 150
#define YB 29
#define CBR -43
#define CBG -85
#define CBB 128
#define CRR 128
#define CRG -107
#define CRB -21
const byte jpeg_qtbl_luminance[] = {
16, 11, 10, 16, 124, 140, 151, 161,
12, 12, 14, 19, 126, 158, 160, 155,
14, 13, 16, 24, 140, 157, 169, 156,
14, 17, 22, 29, 151, 187, 180, 162,
18, 22, 37, 56, 168, 109, 103, 177,
24, 35, 55, 64, 181, 104, 113, 192,
49, 64, 78, 87, 103, 121, 120, 101,
72, 92, 95, 98, 112, 100, 103, 199
};
const byte jpeg_qtbl_chrominance[] = {
17, 18, 24, 47, 99, 99, 99, 99,
18, 21, 26, 66, 99, 99, 99, 99,
24, 26, 56, 99, 99, 99, 99, 99,
47, 66, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99
};
const byte* jpeg_qtbl_selector[] = {
jpeg_qtbl_luminance, jpeg_qtbl_chrominance, jpeg_qtbl_chrominance
};
struct jpeg_bit_string {
byte length;
int bits;
};
struct jpeg_zrlc {
byte info; // bit 7-4: number of zeros, bit 3-0: category
struct jpeg_bit_string value;
};
struct __ice_env
{
char outfile[40];
int *image;
int width, height;
int num_components;
int max_sx, max_sy;
int num_mcu_x, num_mcu_y;
int mcu_width, mcu_height;
int cur_mcu_x, cur_mcu_y;
int block[64];
struct jpeg_huffman_code dc_huff[3][16];
struct jpeg_huffman_code ac_huff[3][256];
int dc_huff_numcodes[3];
int ac_huff_numcodes[3];
byte* scan_buffer;
int buf_pos;
unsigned char bits_remaining;
int scan_buf_size;
byte quality;
int quality_scale_factor;
// Restart markers related stuff
byte cur_rst_marker;
int use_rst_markers;
int restart_interval, rst_interval_counter;
} iceenv;
struct jpeg_encode_component
{
byte id_dht;
int width, height;
int stride;
int sx, sy;
byte qt_table;
int *pixels;
int prev_dc;
struct jpeg_zrlc **rlc;
int rlc_size;
int rlc_index;
int dc_code_count[17];
int ac_code_count[257];
// Which code has what length?
byte dc_code_lengths[17];
byte ac_code_lengths[257];
// Number of codes of each length
byte dc_code_length_count[33];
byte ac_code_length_count[33];
// sorted list of symbols to be encoded
byte dc_huffval[16];
byte ac_huffval[256];
// DHT segment informatiom
struct jpeg_dht dc_dht;
struct jpeg_dht ac_dht;
long rlc_count;
//int rlc_indices[40][40];
};
struct jpeg_encode_component icecomp[3];
#ifdef _JPEG_ENCODER_STATS
struct jpeg_encoder_stats icestats;
#endif
static int write_to_file();
static void print_block(int block[64])
{
int x, y;
for (y = 0; y < 8; y++)
{
for (x = 0; x < 8; x++)
{
printf("%d ", block[(y * 8) + x]);
}
printf("\n");
}
printf("\n");
}
// Find the number of bits necessary to represent an int value
inline static byte find_category(int num)
{
byte category = 0;
while ((num < ((-1 << category) + 1)) || (num > (1 << category) - 1))
category++;
return category;
}
// Get the bit coding of an int value
inline static int get_bit_coding(int num, byte category)
{
register int code = num & ((1 << category) - 1);
if (num < 0)
code--;
return code;
}
static void downsample()
{
int i = 0;
int *tmpimage = 0;
int *outpixels = 0;
for (i = 0; i < iceenv.num_components; i++)
{
icecomp[i].pixels = (int*)malloc(icecomp[i].stride * iceenv.height * sizeof(int));
int x, y;
// Go to correct start component
tmpimage = iceenv.image + i;
outpixels = icecomp[i].pixels;
// Do the rows first
for (y = 0; y < iceenv.height; y++)
{
//outpixels = icecomp[i].pixels + (y * icecomp[i].stride);
int* start_index = outpixels;
int step_x = iceenv.max_sx / icecomp[i].sx;
int start_x = 0;
int end_x = iceenv.width;
int modulo = iceenv.width % step_x;
if (modulo)
{
start_x -= DESCALE(UPSCALE(modulo) / 2);
end_x -= DESCALE(UPSCALE(modulo) / 2);
}
// Have to start past the edge of the image so we don't get chroma shift!
for (x = start_x; x < end_x; x += step_x)
{
register int pixel_avg = 0;
int x2;
for (x2 = 0; x2 < step_x; x2++)
{
if (x + x2 < iceenv.width)
pixel_avg += *tmpimage;
else
pixel_avg += *(tmpimage - iceenv.num_components);
// Check if we're already inside the image => only then do we advance the pointer
// If we're not, we just replicate the edge pixel
if (x + x2 >= 0 && x + x2 < iceenv.width)
tmpimage += iceenv.num_components;
}
pixel_avg /= step_x;
*outpixels++ = pixel_avg;
}
int last_val = *(outpixels - 1);
// fill rest of the buffer with value of rightmost pixel
while (outpixels < start_index + icecomp[i].stride)
{
*outpixels++ = last_val;
}
}
int *srcimage2 = icecomp[i].pixels;
int new_height = ((icecomp[i].sy << 3) * iceenv.num_mcu_y);
icecomp[i].pixels = (int*)malloc(icecomp[i].stride * new_height * sizeof(int));
outpixels = icecomp[i].pixels;
int *cur_srcimage = 0;
#ifdef _JPEG_ENCODER_STATS
icestats.color_extrema[i].min_val = INT_MAX;
icestats.color_extrema[i].max_val = INT_MIN;
#endif
// ... and now the columns
int step_y = iceenv.max_sy / icecomp[i].sy;
for (x = 0; x < icecomp[i].width; x++)
{
cur_srcimage = srcimage2 + x;
outpixels = icecomp[i].pixels + x;
int* start_index = outpixels;
int start_y = 0;
int end_y = icecomp[i].height;
int modulo = icecomp[i].height % step_y;
if (modulo)
{
start_y -= DESCALE(UPSCALE(modulo) / 2);
end_y -= DESCALE(UPSCALE(modulo) / 2);
}
// Have to start past the edge of the image so we don't get chroma shift!
for (y = start_y; y < end_y; y += step_y)
{
register int pixel_avg = 0;
int y2;
for (y2 = 0; y2 < step_y; y2++)
{
if (y + y2 < icecomp[i].height)
pixel_avg += *cur_srcimage;
else
pixel_avg += *(cur_srcimage - icecomp[i].stride);
// Check if we're already inside the image => only then do we advance the pointer
// If we're not, we just replicate the edge pixel
if (y + y2 >= 0 && y + y2 < icecomp[i].height)
cur_srcimage += icecomp[i].stride;
}
pixel_avg /= step_y;
// Level shift here!
*outpixels = pixel_avg - 128;
#ifdef _JPEG_ENCODER_STATS
if (pixel_avg < icestats.color_extrema[i].min_val)
icestats.color_extrema[i].min_val = pixel_avg;
if (pixel_avg > icestats.color_extrema[i].max_val)
icestats.color_extrema[i].max_val = pixel_avg;
#endif
outpixels += icecomp[i].stride;
}
int last_val = *(outpixels - icecomp[i].stride);
// fill rest of the buffer with value of bottommost pixel
while (outpixels < start_index + (icecomp[i].stride * (new_height - 0 /*1*/)))
{
*outpixels = last_val;
outpixels += icecomp[i].stride;
}
}
icecomp[i].height = new_height;
free(srcimage2);
}
free(iceenv.image);
iceenv.image = 0;
}
// The last parameter is only for the EOB code
// Normally category == bit_length
static int add_rlc(int comp, int zeros, int category, int bits, int bit_length)
{
// Allocate memory
icecomp[comp].rlc[icecomp[comp].rlc_index] = (struct jpeg_zrlc*) malloc(sizeof(struct jpeg_zrlc));
icecomp[comp].rlc[icecomp[comp].rlc_index]->info = zeros << 4;
icecomp[comp].rlc[icecomp[comp].rlc_index]->info |= category;
icecomp[comp].rlc[icecomp[comp].rlc_index]->value.length = bit_length;
icecomp[comp].rlc[icecomp[comp].rlc_index]->value.bits = bits;
icecomp[comp].rlc_index++;
if (icecomp[comp].rlc_index == icecomp[comp].rlc_size)
{
icecomp[comp].rlc = (struct jpeg_zrlc**) realloc(icecomp[comp].rlc, (icecomp[comp].rlc_size + 0xFFFF) * sizeof(struct jpeg_zrlc*));
if (!icecomp[comp].rlc)
return ERR_OUT_OF_MEMORY;
memset(icecomp[comp].rlc + icecomp[comp].rlc_size, 0, 0xFFFF * sizeof(struct jpeg_zrlc*));
icecomp[comp].rlc_size += 0xFFFF;
}
return ERR_OK;
}
//#define _JPEG_OUTPUT_DC
static int encode_du(int comp, int du_x, int du_y)
{
int *buffer = 0;
long duOriginIndex = ((iceenv.cur_mcu_y * (icecomp[comp].sy << 3) + (du_y << 3)) * icecomp[comp].stride) + (iceenv.cur_mcu_x * (icecomp[comp].sx << 3) + (du_x << 3));
// #ifdef _JPEG_ENCODER_DEBUG
// if (iceenv.cur_mcu_x == 1)
// printf("MCU (%d,%d), DU (%d, %d) starts at index %d\n", iceenv.cur_mcu_x, iceenv.cur_mcu_y, du_x, du_y, duOriginIndex);
// #endif
// Create 8x8 block
int x, y;
for (y = 0; y < 8; y++)
{
buffer = &icecomp[comp].pixels[duOriginIndex + (icecomp[comp].stride * y)];
memcpy(&iceenv.block[y * 8], buffer, 8 * sizeof(int));
}
// Perform DCT
fdct(iceenv.block);
// Quantization
for (y = 0; y < 8; y++)
{
for (x = 0; x < 8; x++)
{
register int value = iceenv.block[(y * 8) + x];
register int quant_factor = CLAMPQNT((iceenv.quality_scale_factor * jpeg_qtbl_selector[comp][(y * 8) + x] + 50) / 100);
// Right-shift rounds towards negative infinity, so we're gonna do our
// computations with positive numbers and then put the sign back
// after we're done
int sign = value < 0 ? -1 : 1;
if (sign < 0)
value *= sign;
value = UPSCALE(value);
value /= quant_factor;
iceenv.block[(y * 8) + x] = sign * DESCALE(value);
}
}
// Zigzag reordering
int *block = (int*)malloc(64 * sizeof(int));
for (x = 0; x < 64; x++)
block[jpeg_zzleft[x]] = iceenv.block[x];
memcpy(iceenv.block, block, 64 * sizeof(int));
free(block);
block = 0;
#ifdef _JPEG_OUTPUT_DC
if (!iceenv.cur_mcu_x && !iceenv.cur_mcu_y)
printf("%d\n", iceenv.block[0]);
#endif
iceenv.block[0] -= icecomp[comp].prev_dc;
icecomp[comp].prev_dc += iceenv.block[0];
//print_block(iceenv.block);
// Write DC
byte category = find_category(iceenv.block[0]);
add_rlc(comp, 0, category, get_bit_coding(iceenv.block[0], category), category);
int* end_pointer = iceenv.block + 64;
// WE HAVE TO STOP ONE BEFORE THE BEGINNING OF THE BLOCK
// THE DC COEFFICIENT HAS TO BE WRITTEN SEPARATELY, EVEN IF THE WHOLE
// BLOCK IS ALL 0s
while (!end_pointer[-1] && end_pointer > iceenv.block+1)
end_pointer--;
// Start with first AC component
block = iceenv.block + 1;
// Do Zero Run Length Coding for this block
// After all MCUs have been processed, the Huffman tables will be
// generated based on these values
int start_rlc_index = icecomp[comp].rlc_index;
while (block < end_pointer)
{
byte zeros = 0;
// count contiguous zeros, but stop at 16 because
// that's the most consecutive zeros than can be encoded
while (!(*block) && zeros < 15)
{
zeros++;
block++;
}
register int value = *block;
byte category = find_category(value);
add_rlc(comp, zeros, category, get_bit_coding(value, category), category);
block++;
};
// Only put an EOB if we don't have a zero run at the end
if (block < iceenv.block + 64)
{
#ifdef _JPEG_ENCODER_DEBUG
//printf("Block prematurely terminated after %d entries.\n", end_pointer - iceenv.block);
#endif
add_rlc(comp, 0, 0, 0, 0xFF);
}
#ifdef _JPEG_ENCODER_DEBUG
// if (icecomp[comp].rlc_index - start_rlc_index > 10)
// printf("MCU: (%d,%d)[%d](%d,%d): %d indices added.\n", iceenv.cur_mcu_x, iceenv.cur_mcu_y, comp, du_x, du_y, icecomp[comp].rlc_index - start_rlc_index);
// icecomp[comp].rlc_count += icecomp[comp].rlc_index - start_rlc_index;
#endif
return ERR_OK;
}
static void get_code_stats(void)
{
int i ;
// Gather statistics about code occurrences
for (i = 0; i < iceenv.num_components; i++)
{
struct jpeg_encode_component *c = &icecomp[i];
int count = c->rlc_index;
int j;
int is_dc = 1;
int du_index = 0;
memset(c->dc_code_count, 0, 17 * sizeof(int));
memset(c->ac_code_count, 0, 257 * sizeof(int));
for (j = 0; j < count; j++)
{
if (is_dc)
{
c->dc_code_count[c->rlc[j]->info]++;
is_dc = 0;
}
else
c->ac_code_count[c->rlc[j]->info]++;
du_index += UPR4(c->rlc[j]->info);
du_index++;
// Reset index if we've processed all 64 samples OR encountered an EOB
if (du_index == 64 || c->rlc[j]->value.length == 0xFF)
{
du_index = 0;
is_dc = 1;
}
}
// For Huffman code generation purposes
// Will be removed later on in the process
c->dc_code_count[16] = 1;
c->ac_code_count[256] = 1;
#ifdef _JPEG_ENCODER_DEBUG
if (i == 0)
{
printf("DC Stats comp #%d\n\n", i);
for (j = 0; j < 16; j++)
{
if (c->dc_code_count[j] > 0)
printf("Code 0x%X: %d occurrences\n", j, c->dc_code_count[j]);
}
printf("\n");
printf("Final count: %ld\n\n", c->rlc_count);
}
#endif
}
}
static void find_code_lengths(void)
{
byte dc_codelengths[17];
byte ac_codelengths[257];
int dc_others[17], ac_others[257];
// Gather statistics about code occurrences
get_code_stats();
struct
{
int code;
int freq;
} v[2];
int i;
for (i = 0; i < iceenv.num_components; i++)
{
int dcac = 0;
// pointers to current array
byte *codelengths = 0;
int *others = 0;
int *codecount = 0;
// Do DC and AC
for (dcac = 0; dcac < 2; dcac++)
{
struct jpeg_encode_component *c = &icecomp[i];
codelengths = !dcac ? dc_codelengths : ac_codelengths;
others = !dcac ? dc_others : ac_others;
codecount = !dcac ? c->dc_code_count : c->ac_code_count;
int numcodes = !dcac ? 17 : 257;
memset(codelengths, 0, numcodes);
memset(others, -1, sizeof(int) * numcodes);
// Proceed according to JPEG Standard Annex K, Figure K.1
do
{
int j;
// Find least FREQ(V1) and FREQ(V2)
for (j = 0; j < 2; j++)
{
// Find rarest code in DC frequency count table
v[j].code = -1;
v[j].freq = INT_MAX;
int code_index = 0;
for (code_index = 0; code_index < numcodes; code_index++)
{
if (j == 1 && code_index == v[0].code)
continue;
if (codecount[code_index] && codecount[code_index] <= v[j].freq && code_index > v[j].code)
{
v[j].code = code_index;
v[j].freq = codecount[code_index];
}
}
}
// No V2? Break
if (v[1].freq == INT_MAX)
break;
codecount[v[0].code] += codecount[v[1].code];
codecount[v[1].code] = 0;
while (1)
{
codelengths[v[0].code] += 1;
if (others[v[0].code] == -1)
break;
v[0].code = others[v[0].code];
}
others[v[0].code] = v[1].code;
while (1)
{
codelengths[v[1].code] += 1;
if (others[v[1].code] == -1)
break;
v[1].code = others[v[1].code];
}
} while (others[v[1].code] == -1);
// AT THIS POINT WE HAVE THE CODE LENGTH FOR EACH SYMBOL STORED IN codelengths
memcpy(!dcac ? c->dc_code_lengths : c->ac_code_lengths, codelengths, numcodes);
// NOW WE COUNT THE NUMBER OF CODES OF EACH LENGTH
// WE CAN POTENTIALLY HAVE CODES OF UP TO 32 BITS AT THIS POINT
byte num_codes_of_each_length[33];
memset(num_codes_of_each_length, 0, sizeof(num_codes_of_each_length));
int j = 0;
for (j = 0; j < numcodes; j++)
{
if (codelengths[j])
num_codes_of_each_length[codelengths[j]]++;
}
memcpy(!dcac ? c->dc_code_length_count : c->ac_code_length_count, num_codes_of_each_length, sizeof(num_codes_of_each_length));
#ifdef _JPEG_ENCODER_DEBUG
// if (i == 0 && dcac == 0)
// {
// printf("Component %d, dcac=%d\n", i, dcac);
//
// for (j = 0; j < numcodes; j++)
// {
// printf("Code size of symbol %X = %d\n", j, !dcac ? c->dc_code_lengths[j] : c->ac_code_lengths[j]);
// }
// printf("\n");
// for (j = 0; j < 33; j++)
// {
// printf("Number of codes of length %d : %d\n", j, num_codes_of_each_length[j]);
// }
// }
#endif
}
}
}
static void limit_code_lengths()
{
int ncomp = 0;
for (ncomp = 0; ncomp < iceenv.num_components; ncomp++)
{
struct jpeg_encode_component *c = &icecomp[ncomp];
byte *code_length_count = 0;
int dcac = 0;
for (dcac = 0; dcac < 2; dcac++)
{
code_length_count = !dcac ? c->dc_code_length_count : c->ac_code_length_count;
int i = 32, j;
while (1)
{
if (!code_length_count[i])
{
i--;
if (i == 16)
{
// Below 16 we work our way down until we find a code length that is used
while (!code_length_count[i])
i--;
// This will be the maximum code length in use
// One must be subtracted from it because the "fake" code
// added during
// c->dc_code_count[16] = 1;
// c->ac_code_count[256] = 1;
// must be removed from the count
code_length_count[i]--;
break;
}
else
{
continue;
}
}
j = i - 1;
j--;
while (!code_length_count[j])
j--;
code_length_count[i] -= 2;
code_length_count[i - 1]++;
code_length_count[j + 1] += 2;
code_length_count[j]--;
}
#ifdef _JPEG_ENCODER_DEBUG
// if (ncomp == 0 && dcac == 0)
// {
// int dbg = 0;
// for (dbg = 0; dbg < 32; dbg++)
// {
// printf("Number of codes of length %d : %d\n", dbg, code_length_count[dbg]);
// }
// }
#endif
}
}
}
// static void sort_codes()
//
// Here we generate a sorted list of symbols
// sort criterion is the symbol's VLC code length
static void sort_codes()
{
byte dc_huffval[16];
byte ac_huffval[256];
int ncomp = 0;
for (ncomp = 0; ncomp < iceenv.num_components; ncomp++)
{
struct jpeg_encode_component *c = &icecomp[ncomp];
byte *codelengths = 0;
byte *huffval = 0;
int dcac = 0;
int numcodes = 0;
for (dcac = 0; dcac < 2; dcac++)
{
codelengths = !dcac ? c->dc_code_lengths : c->ac_code_lengths;
huffval = !dcac ? dc_huffval : ac_huffval;
numcodes = !dcac ? 16 : 256;
memset(huffval, 0, sizeof(byte) * numcodes);
int i = 1, j, k = 0;
while (i < 33)
{
j = 0;
while (j < numcodes)
{
if (codelengths[j] == i)
huffval[k++] = j;
j++;
}
i++;
}
memcpy(!dcac ? c->dc_huffval : c->ac_huffval, huffval, sizeof(byte) * numcodes);
#ifdef _JPEG_ENCODER_DEBUG
// if (ncomp == 0 && dcac == 0)
// {
for (j = 0; j < numcodes; j++)
{
printf("Position %d -> Code %d\n", j, huffval[j]);
}
printf("\n");
// }
#endif
}
}
}
// Here we create the JPEG style DHT data
// which can be used by the function get_huffman_tables() from the
// decoder to generate out bitstrings
static void gen_DHT(void)
{
int ncomp = 0;
for (ncomp = 0; ncomp < iceenv.num_components; ncomp++)
{
struct jpeg_encode_component *c = &icecomp[ncomp];
int dcac = 0;
int numcodes = 0;
struct jpeg_dht *dht = 0;
byte *codelength_count = 0;
for (dcac = 0; dcac < 2; dcac++)
{
dht = !dcac ? &c->dc_dht : &c->ac_dht;
codelength_count = !dcac ? c->dc_code_length_count : c->ac_code_length_count;
numcodes = !dcac ? 16 : 256;
byte codes_total = 0;
int i = 0;
for (i = 0; i < 16; i++)
{
dht->num_codes[i] = codelength_count[i+1];
codes_total += dht->num_codes[i];
}
dht->codes = (byte*) malloc(codes_total);
memcpy(dht->codes, !dcac ? c->dc_huffval : c->ac_huffval, codes_total);
if (!dcac)
iceenv.dc_huff_numcodes[ncomp] = codes_total;
else
iceenv.ac_huff_numcodes[ncomp] = codes_total;
}
}
}
// Here we finally create the 2 global DC Huffman tables and 2 AC Huffman tables
// which can be used for encoding
static int gen_huffman_tables(void)
{
int i, j, k;
struct jpeg_dht* cur_src_table = 0;
struct jpeg_huffman_code* cur_dst_table = 0;
// Loop over all 2 tables
for (i = 0; i < 3 + 3; i++)
{
if (i >= 0 && i < 3)
{
cur_src_table = &icecomp[i].dc_dht;
}
else
{
cur_src_table = &icecomp[i - 3].ac_dht;
}
if (!cur_src_table)
continue;
word cur_bitstring = 0;
byte cur_length = 0;
if (i >= 0 && i < 3)
{
cur_dst_table = iceenv.dc_huff[i];
}
else
{
cur_dst_table = iceenv.ac_huff[i - 3];
}
byte *symbols = cur_src_table->codes;
// Loop over all 16 code lengths
for (j = 0; j < 16; j++)
{
cur_length = j + 1;
#ifdef _JPEG_ENCODER_DEBUG
printf("Codes of length %d bits:\n", cur_length);
#endif
// Loop over all codes of length j
for (k = 0; k < cur_src_table->num_codes[j]; k++)
{
cur_dst_table[*symbols].length = cur_length;
cur_dst_table[*symbols].code = cur_bitstring;
#ifdef _JPEG_ENCODER_DEBUG
printf("\t");
int l;
for (l = cur_length - 1; l >= 0; l--)
{
printf("%d", (cur_bitstring & (1 << l)) >> l);
}
printf(" -> %X\n", *symbols);
#endif
symbols++;
cur_bitstring++;
}
cur_bitstring <<= 1;
}
#ifdef _JPEG_ENCODER_DEBUG
printf("\n");
#endif
}
return ERR_OK;
}
static inline int advance_scan_buffer(void)
{
iceenv.buf_pos++;
if (iceenv.buf_pos >= iceenv.scan_buf_size)
{
iceenv.scan_buffer = (byte*) realloc(iceenv.scan_buffer, iceenv.scan_buf_size + 0xFFFF);
if (!iceenv.scan_buffer)
return ERR_OUT_OF_MEMORY;
memset(iceenv.scan_buffer + iceenv.scan_buf_size, 0, 0xFFFF);
iceenv.scan_buf_size += 0xFFFF;
}
return ERR_OK;
}
// Writes a bit string of a give length to the bit stream
static inline int write_bits(unsigned short value, unsigned char length)
{
if (length == 0xFF)
return ERR_OK;
if (length > 16)
return ERR_INVALID_LENGTH;
while (length)
{
unsigned char bits_from_byte = min(length, iceenv.bits_remaining);
// The right-shift aligns bit strings longer than what our current byte can hold
// The left-shift aligns bit strings shorter than what our current byte can hold
iceenv.scan_buffer[iceenv.buf_pos] |= (value >> max(0, length - iceenv.bits_remaining)) << max(0, iceenv.bits_remaining - length);
iceenv.bits_remaining -= bits_from_byte;
length -= bits_from_byte;
if (!iceenv.bits_remaining)
{
iceenv.bits_remaining = 8;
// Insert stuff byte if necessary
if (iceenv.scan_buffer[iceenv.buf_pos] == 0xFF)
advance_scan_buffer();
advance_scan_buffer();
}
}
return ERR_OK;
}
inline static void fill_current_byte(void)
{
if (iceenv.bits_remaining < 8)
{
write_bits((1 << iceenv.bits_remaining) - 1, iceenv.bits_remaining);
}
}
inline static void write_rst_marker(void)
{
fill_current_byte();
iceenv.scan_buffer[iceenv.buf_pos] = 0xFF;
advance_scan_buffer();
iceenv.scan_buffer[iceenv.buf_pos] = 0xD0 | iceenv.cur_rst_marker;
advance_scan_buffer();
iceenv.cur_rst_marker = (iceenv.cur_rst_marker + 1) & 7;
}
static int create_bitstream()
{
int i;
iceenv.scan_buf_size = 0xFFFF;
iceenv.scan_buffer = (byte*) malloc(iceenv.scan_buf_size);
memset(iceenv.scan_buffer, 0, 0xFFFF);
iceenv.cur_mcu_x = iceenv.cur_mcu_y = 0;
iceenv.rst_interval_counter = 0;
for (i = 0; i < iceenv.num_components; i++)
icecomp[i].rlc_index = 0;
// Encode every MCU
for (;;)
{
for (i = 0; i < iceenv.num_components; i++)
{
struct jpeg_encode_component *c = &icecomp[i];
int is_dc = 1;
int du_index = 0;
int num_du_per_mcu = c->sx * c->sy;
struct jpeg_huffman_code *huff_table = 0;
int err;