summaryrefslogtreecommitdiff
path: root/android/libjpeg-encoder.cpp
blob: d22a79f5fd6883894bfe378ccd0944faac9a112b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
/*
 * Copyright (c) 2007-2008 Intel Corporation. All Rights Reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sub license, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 * 
 * The above copyright notice and this permission notice (including the
 * next paragraph) shall be included in all copies or substantial portions
 * of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
 * IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR
 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * Authors:
 *    Sun, Jing <jing.a.sun@intel.com>
 */
 
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <getopt.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <pthread.h>
#include "jpeglib.h"

inline unsigned long long int current_time(/*bool fixed*/)
{
#if 0
    if (!fixed) {
        struct timeval tv;

        gettimeofday(&tv, NULL);
        return (((unsigned long long)tv.tv_usec+(unsigned long long)tv.tv_sec*1000000) * 1000);
    }
    else {
        unsigned a, d;

        __asm__ volatile("rdtsc" : "=a" (a), "=d" (d));
        return ((unsigned long long)a) | (((unsigned long long)d) << 32);
    }
#endif
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return (((unsigned long long)tv.tv_usec+(unsigned long long)tv.tv_sec*1000000) * 1000);
}

#define PERF_DEF(counter) unsigned long long int COUNTER_##counter=0;
#define PERF_START(counter, fixed) { COUNTER_##counter = current_time(); }
#define PERF_STOP(counter, fixed) { COUNTER_##counter = current_time() - COUNTER_##counter; }
#define PERF_SET(counter, value) { COUNTER_##counter = value; }
#define PERF_GET(counter) (COUNTER_##counter)

#define DEFAULT_THREAD_COUNT 1
#define MAX_THREAD_COUNT 8
#define MAX_WIDTH 65536
#define MAX_HEIGHT 65536
#define DEFAULT_QUALITY 80
#define NV12_SAMPLE_SIZE 1.5
#define NV12_COMPONENTS 3
#define NV12_MCU_SIZE 16
#define MAX_MCU_SIZE 1170
#define MAX_CODED_BUFFER_SIZE(width,height) ((((((width)+15)/16)*(((height)+15)/16)* MAX_MCU_SIZE/4+1024)+0xf)&~0xf)

#define HEADER_TOTAL_LEN 623
#define HEADER_SOS_LEN 14
#define HEADER_EOI_LEN 2
#define HEADER_HEIGHT_POS 163
#define HEADER_WIDTH_POS 165

typedef struct {
    struct jpeg_destination_mgr pub; /* public fields */
    JOCTET *buffer; /* start of buffer */
    size_t size; /* size of buffer */
}test_dest_mgr;

typedef struct {
    unsigned int id;
    void *source_buffer;
    int width;
    int height;
    int quality;
    int sub_height;
    int rows;
    void *sub_output_buffer;
    unsigned int sub_output_size;
}thread_parameters;

static void usage(const char* pname)
{
    fprintf(stderr,
            "\n  USAGE: %s -source [path] -width [value] -height [value] \n"
            "         -output [path] -quality [value] -thread [value] -fix\n\n"
            "  -source: declaring the source's file path (of NV12).\n"
            "  -width: declaring the source's raw data width (0, 65536].\n"
            "  -height: declaring the source's raw data height (0, 65536].\n"
            "  -output: specifying the output JPEG's file path (.JPG or .jpg).\n"     
            "  -quality (optional): setting image quality [0, 100].\n"
            "  -thread (optional): setting the encoding threads [1, 8].\n"
            "  -fix (optional): fixing CPU frequency for evaluating performance.\n\n"
            ,pname);
}

static bool match_key (char *arg, const char *keyword, int minchars)
{
    register int ca, ck;
    register int nmatched = 0;

    while ((ca = *arg++) != '\0') {
        if ((ck = *keyword++) == '\0')
            return false; /* arg longer than keyword, mismatch */
        if (isupper(ca)) /* force arg to lcase (assume ck is already) */
            ca = tolower(ca);
        if (ca != ck)
            return false; /* mismatch */
        nmatched++; /* count matched characters */
    }

    if (nmatched < minchars)
        return false; /* arg shorter than keyword, mismatch */
	
    return true; /* Match */
}

/*
 * Convert source samples from the interleaved NV12 format to YUV411 format
 * for Libjpeg doesn't support encoding interleaved source directly.
 */
static void NV12_color_convert(JSAMPLE *source, int width, int height, JSAMPLE *dest)
{
    int i, j;
    JSAMPLE *source_UV = NULL;
    JSAMPLE *dest_U = NULL;
    JSAMPLE *dest_V = NULL;
	
    /* Copy the luminance component directly to destination*/
    memcpy((void *)dest, (void *)source, width*height);

    /* Deinterleave then copy the chrominance components to destination*/
    source_UV = (JSAMPLE *)((unsigned int)source + width*height);
    dest_U = (JSAMPLE *)((unsigned int)dest + width*height);
    dest_V = (JSAMPLE *)((unsigned int)dest_U + (width*height)/4);
    for(i=0,j=0; i<(width*height/2); i+=2,++j) {
        dest_U[j] = source_UV[i];
        dest_V[j] = source_UV[i+1];
    }
}

/*
 * Initialize destination --- called by jpeg_start_compress
 * before any data is actually written.
 */
static void init_destination (j_compress_ptr cinfo)
{
    test_dest_mgr *dest_mgr_ptr = (test_dest_mgr *)cinfo->dest;

    dest_mgr_ptr->pub.next_output_byte = dest_mgr_ptr->buffer;
    dest_mgr_ptr->pub.free_in_buffer = dest_mgr_ptr->size;
}


/*
 * Empty the output buffer --- called whenever buffer fills up.
 */
static boolean empty_output_buffer (j_compress_ptr cinfo)
{
    test_dest_mgr *dest_mgr_ptr = (test_dest_mgr *)cinfo->dest;
    fprintf(stderr, "The coded buffer is too small (free_in_buffer: %d)!\n", dest_mgr_ptr->pub.free_in_buffer);
    return FALSE;
}


/*
 * Terminate destination --- called by jpeg_finish_compress
 * after all data has been written.  Usually needs to flush buffer.
 */
static void term_destination (j_compress_ptr cinfo)
{
    /* Need to do nothing while term */
}


/*
 * Prepare for output to a stdio stream.
 * The caller must have already opened the stream, and is responsible
 * for closing it after finishing compression.
 */
static void setup_dest_mgr (j_compress_ptr cinfo, void *buffer, unsigned int size)
{
    test_dest_mgr *dest_mgr_ptr;

    if (cinfo->dest == NULL) {	/* first time for this JPEG object? */
        cinfo->dest = (struct jpeg_destination_mgr *) 
                      (*cinfo->mem->alloc_small)((j_common_ptr)cinfo, JPOOL_PERMANENT,
                                                  sizeof(test_dest_mgr));
    }

    dest_mgr_ptr = (test_dest_mgr *)cinfo->dest;
    dest_mgr_ptr->pub.init_destination = init_destination;
    dest_mgr_ptr->pub.empty_output_buffer = empty_output_buffer;
    dest_mgr_ptr->pub.term_destination = term_destination;
    dest_mgr_ptr->buffer = (JOCTET *)buffer;
    dest_mgr_ptr->size = size;
}

void *encode_thread_fn(void *arg)
{
    int i = 0, sub_coded_size = 0;
    struct jpeg_compress_struct cinfo;
    struct jpeg_error_mgr jerr;
    JSAMPROW Y_row[NV12_MCU_SIZE],U_row[NV12_MCU_SIZE],V_row[NV12_MCU_SIZE];
    JSAMPARRAY source_array[NV12_COMPONENTS];
    int uncoded_rows = 0, current_rows = 0;
    test_dest_mgr *dest_mgr_ptr = NULL;
    void *current_Y = NULL, *current_U = NULL, *current_V = NULL;
    thread_parameters *p_para = (thread_parameters *)arg;

    source_array[0] = Y_row;
    source_array[1] = U_row;
    source_array[2] = V_row;

    uncoded_rows = p_para->rows;

    /* Initialize the JPEG compression object with default error handling. */
    cinfo.err = jpeg_std_error(&jerr);
    jpeg_create_compress(&cinfo);

    /* Initialize JPEG parameters */
    cinfo.in_color_space = JCS_YCbCr;
    cinfo.image_width = p_para->width;
    cinfo.image_height = uncoded_rows;
    cinfo.input_components = NV12_COMPONENTS;
    jpeg_set_defaults(&cinfo);
    jpeg_set_quality(&cinfo, p_para->quality, TRUE); /* TRUE for forcing baseline (8-bit sample depth) */
    cinfo.raw_data_in = TRUE;

    /* Specify data destination for compression */
    setup_dest_mgr(&cinfo, p_para->sub_output_buffer, p_para->sub_output_size);
    dest_mgr_ptr = (test_dest_mgr *)cinfo.dest;

    /* Start compressor */
    jpeg_start_compress(&cinfo, TRUE); /* TRUE for writing tables into dest */

    /* Process data */
    current_Y = (void *)((unsigned int)p_para->source_buffer +
                p_para->id*p_para->width*p_para->sub_height);
    current_U = (void *)((unsigned int)p_para->source_buffer + p_para->width*p_para->height +
                p_para->id*p_para->width*p_para->sub_height/4);
    current_V = (void *)((unsigned int)p_para->source_buffer + p_para->width*p_para->height*5/4 +
                p_para->id*p_para->width*p_para->sub_height/4);
    while (uncoded_rows > 0) {
        current_rows = (uncoded_rows > NV12_MCU_SIZE)? NV12_MCU_SIZE : uncoded_rows;
        for (i=0; i<current_rows; ++i) {
            Y_row[i] = (JSAMPROW)(current_Y);
            current_Y =(void *)((unsigned int)current_Y + p_para->width);
        }
        for (i=0; i<(current_rows/2); ++i) {
            U_row[i] = (JSAMPROW)(current_U);
            V_row[i] = (JSAMPROW)(current_V);
            current_U =(void *)((unsigned int)current_U + p_para->width/2);
            current_V =(void *)((unsigned int)current_V + p_para->width/2);
        }
        jpeg_write_raw_data(&cinfo, source_array, NV12_MCU_SIZE);
        uncoded_rows -= current_rows;
    }

    /* Finish compression */
    jpeg_finish_compress(&cinfo);

    /* Check result */
    if (jerr.num_warnings != 0) {
        fprintf(stderr, "Thread %d: Libjpeg outputs %ld warnings!\n", p_para->id, jerr.num_warnings);
        sub_coded_size = -1;
    }
    else {
        sub_coded_size = dest_mgr_ptr->size - dest_mgr_ptr->pub.free_in_buffer;
    }

    /* Release memory */
    jpeg_destroy_compress(&cinfo);

    pthread_exit((void *)sub_coded_size);
    return NULL;
}

int main(int argc, char** argv)
{
    const char *pname = argv[0];
    int argn;
    char *arg;

    int i, j;	
    char *source_name = NULL;
    char *output_name = "./output.jpg";
    //char final_output_name[128] = "\0";	
    int source_fd = -1;
    int output_fd = -1;
    int quality = DEFAULT_QUALITY;
    int width = 0, height = 0;
    int thread = DEFAULT_THREAD_COUNT;
    unsigned int source_size = 0, output_size = 0;
    unsigned int read_size = 0, write_size = 0;
    void *source_buffer = NULL, *converted_source_buffer = NULL, *output_buffer = NULL;
    unsigned char *merged_output_buffer=NULL;
    bool fix_cpu_frequency = false;

    pthread_t *encode_thread = NULL;
    thread_parameters *encode_thread_para = NULL;
    int *sub_coded_size = NULL;
    bool hasError = false;

    FILE *cpu_online_nr_fd = NULL, *cpu_available_max_fd = NULL, *cpu_available_min_fd = NULL;
    FILE *cpu_scaling_max_fd = NULL, *cpu_scaling_min_fd = NULL, *cpu_cur_fd = NULL;
    unsigned int cpu_online_nr = 0, cpu_available_max = 1000000, cpu_available_min = 0, cpu_cur = 0;

    unsigned long long int convert_time = 0;
    unsigned long long int core_encoding_time = 0;
    unsigned long long int subpictures_merging_time = 0;
    unsigned long long int total_time = 0;

    PERF_DEF(NV12_color_convert);
    PERF_DEF(core_encoding);
    PERF_DEF(subpictures_merging);

    double compression_rate = 0;

    if (1 >= argc) {
        usage(pname); /* No argument */
        return 1;
    }

    for (argn = 1; argn < argc; argn++) {
        arg = argv[argn];
        if (*arg != '-') {
            /* Every argument should begin with a '-' */
            usage(pname);
            fprintf(stderr, "Every argument should begin with a '-'!\n");
            return 1;
        }
        arg++;

        if (match_key(arg, "width", strlen("width"))) {				
            if (++argn >= argc) {
                usage(pname); /* "-width" should be followed by a specified width value*/
                fprintf(stderr, "-width should be followed by a specified width value!\n");
                return 1;
            }

            if ((1 != sscanf(argv[argn], "%d", &width)) || (width <= 0)) {
                usage(pname); /* Invalid width */
                fprintf(stderr, "Invalid width!\n");				
                return 1;
            }

            if ((width>MAX_WIDTH) || (width%2)) {
                usage(pname); /* Unsupported width */                
                fprintf(stderr, "Unsupported width: %d!\n", width);
                return 1;
            }   			

        }
        else if (match_key(arg, "height", strlen("height"))) {
	    if (++argn >= argc) {
                usage(pname); /* "-height" should be followed by a specified height value*/
                fprintf(stderr, "-height should be followed by a specified height value!\n");
                return 1;
            }
	
            if ((1 != sscanf(argv[argn], "%d", &height)) || (height <= 0)) {
                usage(pname); /* Invalid height */
                fprintf(stderr, "Invalid height!\n");				
                return 1;
            }

            if ((height>MAX_HEIGHT) || (height%2)) {
                usage(pname); /* Unsupported height */                
                fprintf(stderr, "Unsupported height: %d!\n", height);
                return 1;
            } 			
        }
        else if (match_key(arg, "source", strlen("source"))) {
            if (++argn >= argc) {
                usage(pname); /* "-source" should be followed by a specified source path */
                fprintf(stderr, "-source should be followed by a specified source path!\n");
                return 1;
            }
            source_name = argv[argn];		
        }		
        else if (match_key(arg, "output", strlen("output"))) {
            if (++argn >= argc) {
                usage(pname); /* "-output" should be followed by a specified output file path */
                fprintf(stderr, "-output should be followed by a specified output file path!\n");
                return 1;
            }
			
            output_name = argv[argn];
            if ((strlen(output_name) <= 4) ||
                (strcmp(output_name+strlen(output_name)-4, ".jpg") && 
			     strcmp(output_name+strlen(output_name)-4, ".JPG"))) {
                usage(pname); /* Invalid output file name */                
                fprintf(stderr, "Invalid output file name: %s!\n", output_name);
                return 1;					
            }
        }
        else if (match_key(arg, "quality", strlen("quality"))) {
            if (++argn >= argc) {
                usage(pname); /* "quality" should be followed by a quality value */
                fprintf(stderr, "-quality should be followed by a specified quality value!\n");
                return 1;
            }
            if ((1 != sscanf(argv[argn], "%d", &quality)) || (quality < 0) || (quality > 100)) {
                usage(pname); /* Invalid quality value */
                fprintf(stderr, "Invalid quality value!\n");
                return 1;
            }
        }
        else if (match_key(arg, "thread", strlen("thread"))) {
            if (++argn >= argc) {
                usage(pname); /* "thread" should be followed by a thread count */
                fprintf(stderr, "-thread should be followed by a specified thread count!\n");
                return 1;
            }
            if ((1 != sscanf(argv[argn], "%d", &thread)) || (thread < 1) || (thread > MAX_THREAD_COUNT)) {
                usage(pname); /* Invalid thread count */
                fprintf(stderr, "Invalid thread count!\n");
                return 1;
            }
        }
        else if (match_key(arg, "fix", strlen("fix"))) {
            fix_cpu_frequency = true;
        }
        else {
            usage(pname); /* Unsupported argument */                
            fprintf(stderr, "Unsupported argument: %s!\n", arg);
            return 1;	
        }
    }

    if ((0 == width) || (0 == height)) {
        usage(pname);
        fprintf(stderr, "Width or height unset!\n");
        return 1;
    }   

    if (height < 240) {
        printf("Height is too small to do multi-threading.\n"
               "Force to run as single thread.\n");
        thread = 1;
    }

    if (NULL == source_name) {
        usage(pname);
        fprintf(stderr, "Source file path unset!\n");
        return 1;
    }   
	
    source_fd = open(source_name, O_RDONLY, 0664);
    if (-1 == source_fd){
        fprintf(stderr, "Error opening source file: %s (%s)!\n", source_name, strerror(errno));
        return 1;
    }
	    
    source_size = width * height * NV12_SAMPLE_SIZE;	
    source_buffer = malloc(source_size);
    if (NULL == source_buffer) {
        fprintf(stderr, "Fail to allocate source buffer: %d(%s)!\n", errno, strerror(errno));
        close(source_fd);
        return 1;
    }
    memset(source_buffer, 0, source_size);
	
    read_size = read(source_fd, source_buffer, source_size);
    if (read_size != source_size) {
        fprintf(stderr, "Incorrect source file size: %d(%s)!\n", read_size, strerror(errno));
        fprintf(stderr, "The correct size should be : %d.\n", source_size);		
        close(source_fd);
        free(source_buffer);
        return 1;
    }
    close(source_fd);

    //Fix CPUs' frequency to the maximum available
    if (fix_cpu_frequency) {
        cpu_online_nr_fd = fopen("/sys/devices/system/cpu/online", "r");
        assert(cpu_online_nr_fd != NULL);
        fscanf(cpu_online_nr_fd, "0-%u", &cpu_online_nr);
        assert(cpu_online_nr != 0);
        fclose(cpu_online_nr_fd);

        cpu_available_max_fd  = fopen("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq", "r");
        if(NULL == cpu_available_max_fd) {
            unsigned char one_line[32] = {};
            unsigned char one_segment[32] = {};
            int readed = 0;

            cpu_available_max_fd  = fopen("/proc/cpuinfo", "r");
            assert(cpu_available_max_fd != 0);

            i = strlen("cpu MHz");
            j = -1;  //Haven't find the cpu MHz line
            do {
                if (fread(&one_line[0], 1, 1, cpu_available_max_fd) != 1) {
                    break;
                }
                else if ('\n' == one_line[0]) {
                    readed = fread(one_line, 1, 24, cpu_available_max_fd);
                    if ((24 == readed) && (0 == strncmp((const char *)one_line, (const char *)"cpu MHz", i))) {
                        //Find the cpu MHz line
                        j = 0;
                        break;
                    }
                    else if (readed > 0) {
                        fseek(cpu_available_max_fd, 0-readed, SEEK_CUR);
                    }
                }
            } while (1);

            if (0 == j) {
                while (one_line[i] != ':') {
                    ++i;
                }
                ++i; // The space bewteen ':' and a freq value
                while (one_line[i] != '.') {
                    one_segment[j++] = one_line[i++];
                }
                one_segment[j] = '\0';
                cpu_available_max = atoi((const char *)one_segment) * 1000; 
            }
            fclose(cpu_available_max_fd);

            if (0 == cpu_available_max) {
                cpu_available_max = 1000000;
                fprintf(stderr, "\nCan't find CPU frequecency value and we assume it to 1.0GHz.\n");
            }
        
            printf("\n%u CPU(s) online, whose unscalable frequency is: %u.\n", 
                   cpu_online_nr+1, cpu_available_max);
        }
        else {
            fscanf(cpu_available_max_fd, "%u", &cpu_available_max);
            assert(cpu_available_max != 0);
            fclose(cpu_available_max_fd);

            cpu_available_min_fd  = fopen("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq", "r");
            assert(cpu_available_min_fd != NULL);
            fscanf(cpu_available_min_fd, "%u", &cpu_available_min);
            assert(cpu_available_min != 0);
            fclose(cpu_available_min_fd);

            printf("\n%u CPU(s) online, whose MAX/MIN available frequency is: %u/%u.\n", 
                   cpu_online_nr+1, cpu_available_max, cpu_available_min);

            for (i=0; i<=(int)cpu_online_nr; ++i) {
                char fd_name[64];

                sprintf(fd_name, "/sys/devices/system/cpu/cpu%u/cpufreq/scaling_max_freq", i);
                cpu_scaling_max_fd  = fopen(fd_name, "w");
                if (0 == i) { 
                    assert(cpu_scaling_max_fd != NULL);
                }
                else if ((i>0) && (NULL==cpu_scaling_max_fd)) {
                    fprintf(stderr, "No sysfs attribute to fix cpu%u's frequency!\n", i);
                    break;
                }
                fprintf(cpu_scaling_max_fd, "%u", cpu_available_max);
                fclose(cpu_scaling_max_fd);

                sprintf(fd_name, "/sys/devices/system/cpu/cpu%u/cpufreq/scaling_min_freq", i);
                cpu_scaling_min_fd  = fopen(fd_name, "w");
                if (0 == i) {
                    assert(cpu_scaling_min_fd != NULL);
                }
                else if ((i>0) && (NULL== cpu_scaling_min_fd)) {
                    fprintf(stderr, "No sysfs attribute to fix cpu%u's frequency!\n", i);
                    break;
                }
                fprintf(cpu_scaling_min_fd, "%u", cpu_available_max);
                fclose(cpu_scaling_min_fd);

                sprintf(fd_name, "/sys/devices/system/cpu/cpu%u/cpufreq/scaling_cur_freq", i);
                cpu_cur_fd  = fopen(fd_name, "r");
                assert(cpu_cur_fd != NULL);
                fscanf(cpu_cur_fd, "%u", &cpu_cur);
                assert(cpu_cur == cpu_available_max);
                fclose(cpu_cur_fd);

                printf("cpu%u's frequency is fixed to %u.\n", i, cpu_available_max);

                cpu_scaling_max_fd = cpu_scaling_min_fd = cpu_cur_fd = NULL;
                cpu_cur = 0;
            }
        }
    }
    cpu_available_max = 1000000;
    //Fixing is done.

    printf("\n[INPUT]\n");
    printf("Source: %s\n", source_name);
    printf("Width: %d\n", width);
    printf("Height: %d\n", height);
    printf("Output: %s\n", output_name);
    printf("Quality: %d\n", quality);
    printf("Thread: %d\n", thread);
    if (true == fix_cpu_frequency)
        printf("Fix CPU frequency: true\n");
    else
        printf("Fix CPU frequency: false\n");

    printf("\n[OUTPUT]\n");

    converted_source_buffer = malloc(source_size);
    if (NULL == converted_source_buffer) {
        fprintf(stderr, "Fail to allocate converted source buffer: %d(%s)!\n", errno, strerror(errno));
        return 1;
    }
    memset(converted_source_buffer, 0, source_size);

    PERF_START(NV12_color_convert, fix_cpu_frequency);
    NV12_color_convert((JSAMPLE *)source_buffer, width, height, (JSAMPLE *)converted_source_buffer);
    PERF_STOP(NV12_color_convert, fix_cpu_frequency);
    free(source_buffer);
	
    output_size = MAX_CODED_BUFFER_SIZE(width, height);
    output_buffer = malloc(output_size);
    if (NULL == output_buffer) {
        fprintf(stderr, "Fail to allocate output buffer: %d(%s)!\n", errno, strerror(errno));
        free(converted_source_buffer);
        return 1;
    }
    memset(output_buffer, 0, output_size);

    encode_thread = (pthread_t *)malloc(sizeof(pthread_t) * thread);
    if (NULL == encode_thread) {
        fprintf(stderr, "Fail to allocate thread data: %d(%s)!\n", errno, strerror(errno));
        free(converted_source_buffer);
        free(output_buffer);
        return 1;
    }
    encode_thread_para = (thread_parameters *)malloc(sizeof(thread_parameters) * thread);
    if (NULL == encode_thread_para) {
        fprintf(stderr, "Fail to allocate thread data: %d(%s)!\n", errno, strerror(errno));
        free(converted_source_buffer);
        free(output_buffer);
        free(encode_thread);
        return 1;
    }
    sub_coded_size = (int *)malloc(sizeof(int) * thread);
    if (NULL == sub_coded_size) {
        fprintf(stderr, "Fail to allocate thread data: %d(%s)!\n", errno, strerror(errno));
        free(converted_source_buffer);
        free(output_buffer);
        free(encode_thread);
        free(encode_thread_para);
        return 1;
    }


    PERF_START(core_encoding, fix_cpu_frequency);
    /* Create encoding threads */
    for (i=0; i<thread; ++i) {
        encode_thread_para[i].id = i;
        encode_thread_para[i].width = width;
        encode_thread_para[i].height = height;
        encode_thread_para[i].quality = quality;
        encode_thread_para[i].source_buffer = converted_source_buffer;
        encode_thread_para[i].sub_height = ((height/thread+NV12_MCU_SIZE-1)
                                           /NV12_MCU_SIZE)*NV12_MCU_SIZE;
        encode_thread_para[i].rows = (i != (thread-1))?
                                     encode_thread_para[i].sub_height:
                                     (height-(encode_thread_para[i].sub_height*(thread-1)));
        encode_thread_para[i].sub_output_size = output_size/thread;
        encode_thread_para[i].sub_output_buffer = (void *)((unsigned int)output_buffer +
                                                           (output_size/thread)*i);

        pthread_create(&encode_thread[i], NULL, encode_thread_fn, (void *)&encode_thread_para[i]);
    }

    /* Wait for encoding threads' completion */
    for (i=0; i<thread; ++i) {
        pthread_join(encode_thread[i], (void **)&sub_coded_size[i]);
        if (sub_coded_size[i] <= 0) {
            hasError = true;
        }
    }
    free(converted_source_buffer);
    if (hasError) {
        free(output_buffer);
        free(encode_thread);
        free(encode_thread_para);
        free(sub_coded_size);
        return 1;
    }
    PERF_STOP(core_encoding, fix_cpu_frequency);

    /* Dump each encoding thread's result */
    for (i=0; i<thread; ++i) {
        printf("Thread %d: the coded size is %d.\n", i, sub_coded_size[i]);
    }
    printf("\n");

    /* Create the final output buffer to take merged coded data */
    merged_output_buffer = malloc(output_size);
    if (NULL == merged_output_buffer) {
        fprintf(stderr, "Fail to allocate merged output buffer: %d(%s)!\n", errno, strerror(errno));
        free(output_buffer);
        free(encode_thread);
        free(encode_thread_para);
        free(sub_coded_size);
        return 1;
    }
    memset(merged_output_buffer, 0, output_size);

    /* Merge those sub-pictures together */
    PERF_START(subpictures_merging, fix_cpu_frequency);

    /* Write the JPEG header */
    memcpy(merged_output_buffer,
           encode_thread_para[0].sub_output_buffer,
           HEADER_TOTAL_LEN-HEADER_SOS_LEN);
    output_size = HEADER_TOTAL_LEN - HEADER_SOS_LEN;

    /* Update the width and height info */
    merged_output_buffer[HEADER_HEIGHT_POS] = (height>>8) & 0xFF;
    merged_output_buffer[HEADER_HEIGHT_POS+1] = (height) & 0xFF;
    merged_output_buffer[HEADER_WIDTH_POS] = (width>>8) & 0xFF;
    merged_output_buffer[HEADER_WIDTH_POS+1] = (width) & 0xFF;

    /* Write the restarting interval */
    if (thread > 1) {
        unsigned int MCUs = (encode_thread_para[0].sub_height/NV12_MCU_SIZE) *
                            (width/NV12_MCU_SIZE);

        merged_output_buffer[output_size++] = 0xFF;
        merged_output_buffer[output_size++] = 0xDD;
        merged_output_buffer[output_size++] = 0;
        merged_output_buffer[output_size++] = 4;
        merged_output_buffer[output_size++] = (MCUs>>8) & 0xFF;
        merged_output_buffer[output_size++] = (MCUs) & 0xFF;
    }

    memcpy((void *)((unsigned int)merged_output_buffer+output_size),
           (void *)((unsigned int)encode_thread_para[0].sub_output_buffer+HEADER_TOTAL_LEN-HEADER_SOS_LEN),
           HEADER_SOS_LEN);
    output_size += HEADER_SOS_LEN;

    /* Write coded segments */
    for (i=0; i<thread; ++i) {
        memcpy((void *)((unsigned int)merged_output_buffer+output_size),
               (void *)((unsigned int)encode_thread_para[i].sub_output_buffer+HEADER_TOTAL_LEN),
               (sub_coded_size[i]-HEADER_TOTAL_LEN-HEADER_EOI_LEN));
        output_size += (sub_coded_size[i]-HEADER_TOTAL_LEN-HEADER_EOI_LEN);

        if (i != (thread-1)) {
            merged_output_buffer[output_size++] = 0xFF;
            merged_output_buffer[output_size++] = (i&0x7) | 0xD0;
        }
    }
    /* Write EOI */
    merged_output_buffer[output_size++]= 0xFF;
    merged_output_buffer[output_size++]= 0xD9;

    PERF_STOP(subpictures_merging, fix_cpu_frequency);

    free(output_buffer);
    free(encode_thread);
    free(encode_thread_para);
    free(sub_coded_size);

    output_fd = open(output_name, O_WRONLY | O_CREAT | O_TRUNC, 0664);
    if (-1 == output_fd) {
        fprintf(stderr, "Error opening output file: %s (%s)!\n", output_name, strerror(errno));
        free(merged_output_buffer);
        return 1;
    }

    write_size = write(output_fd, merged_output_buffer, output_size);
    if (write_size != output_size) {
        fprintf(stderr, "Fail to write coded data to output file: %d(%s)!\n", write_size , strerror(errno));
        close(output_fd);
        free(merged_output_buffer);
        return 1;		
    }

    free(merged_output_buffer);
    close(output_fd);
    output_fd = -1;

    convert_time = PERF_GET(NV12_color_convert);
    core_encoding_time = PERF_GET(core_encoding);
    subpictures_merging_time = PERF_GET(subpictures_merging);
    total_time = convert_time + core_encoding_time + subpictures_merging_time;
    printf("[SUM]Convert: %.3fms\n", ((double)convert_time)/cpu_available_max);
    printf("[SUM]Core encoding: %.3fms\n", ((double)core_encoding_time)/cpu_available_max);
    printf("[SUM]Sub-pictures merging: %.3fms\n", ((double)subpictures_merging_time)/cpu_available_max);
    printf("[SUM]Total: %.3fms\n", ((double)total_time)/cpu_available_max);

    compression_rate = ((double)output_size) / ((double)source_size);
    compression_rate = (1 - compression_rate) * 100;
    printf("[SUM]Compression rate: %.2f%% (%d bytes : %d bytes)\n", compression_rate, output_size, source_size);

    //Restore CPUs' frequency
    if (fix_cpu_frequency) {
        if (cpu_available_min != 0) {
            for (i=0; i<=(int)cpu_online_nr; ++i) {
                char fd_name[64];

                sprintf(fd_name, "/sys/devices/system/cpu/cpu%u/cpufreq/scaling_min_freq", i);
                cpu_scaling_min_fd  = fopen(fd_name, "w");
                if (0 == i) {
                    assert(cpu_scaling_min_fd != NULL);
                }
                else if ((i>0) && (NULL== cpu_scaling_min_fd)) {
                    fprintf(stderr, "No sysfs attribute to restore cpu%u's frequency!\n", i);
                    break;
                }

                fprintf(cpu_scaling_min_fd, "%u", cpu_available_min);
                fclose(cpu_scaling_min_fd);

                printf("cpu%u's frequency is restored.\n", i);

                cpu_scaling_min_fd = NULL;
            }
        }
    }
    //Restoring is done

    return 0;
}