]> git.sesse.net Git - qscale/blob - libqscale.c
Support progressive mode in JPEGs.
[qscale] / libqscale.c
1 /*
2  * qscale: Quick, high-quality JPEG-to-JPEG scaler.
3  * Copyright (C) 2008 Steinar H. Gunderson <sgunderson@bigfoot.com>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, version 2 of the License.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
17  */
18
19 #include <math.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <malloc.h>
24
25 #include "libqscale.h"
26
27 /* The number of pixels to process at a time when scaling vertically. */
28 #define CACHE_LINE_FACTOR 16
29
30 /* Whether to use SSE for horizontal scaling or not (requires SSE3). */
31 #define USE_HORIZONTAL_SSE 1
32
33 /* Whether to use SSE for vertical scaling or not (requires only SSE1). */
34 #define USE_VERTICAL_SSE 1
35
36 #if USE_VERTICAL_SSE
37 #undef CACHE_LINE_FACTOR
38 #define CACHE_LINE_FACTOR 16
39 #endif
40
41 #ifndef M_PI
42 #define M_PI 3.14159265358979323846264
43 #endif
44
45 qscale_img *qscale_load_jpeg(const char *filename)
46 {
47         FILE *file = fopen(filename, "rb");
48         qscale_img *img;
49         if (file == NULL) {
50                 return NULL;
51         }
52
53         img = qscale_load_jpeg_from_stdio(file);
54
55         fclose(file);
56         return img;
57 }
58
59 qscale_img *qscale_load_jpeg_from_stdio(FILE *file)
60 {
61         qscale_img *img = (qscale_img *)malloc(sizeof(qscale_img));
62         if (img == NULL) {
63                 return NULL;
64         }
65
66         img->data_y = img->data_cb = img->data_cr = NULL;
67
68         /* FIXME: Better error handling here (ie., return NULL). */
69         struct jpeg_decompress_struct dinfo;
70         struct jpeg_error_mgr jerr;
71         dinfo.err = jpeg_std_error(&jerr);
72         jpeg_create_decompress(&dinfo);
73         jpeg_stdio_src(&dinfo, file);
74         jpeg_read_header(&dinfo, TRUE);
75         dinfo.raw_data_out = TRUE;
76         jpeg_start_decompress(&dinfo);
77         
78         /* We do not handle anything but YCbCr images (yet?). */
79         if (dinfo.num_components != 3) {
80                 qscale_destroy(img);
81                 return NULL;
82         }
83
84         img->width = dinfo.image_width;
85         img->height = dinfo.image_height;
86
87         img->w0 = dinfo.image_width * dinfo.comp_info[0].h_samp_factor / dinfo.max_h_samp_factor;
88         img->h0 = dinfo.image_height * dinfo.comp_info[0].v_samp_factor / dinfo.max_v_samp_factor;
89
90         img->w1 = dinfo.image_width * dinfo.comp_info[1].h_samp_factor / dinfo.max_h_samp_factor;
91         img->h1 = dinfo.image_height * dinfo.comp_info[1].v_samp_factor / dinfo.max_v_samp_factor;
92
93         img->w2 = dinfo.image_width * dinfo.comp_info[2].h_samp_factor / dinfo.max_h_samp_factor;
94         img->h2 = dinfo.image_height * dinfo.comp_info[2].v_samp_factor / dinfo.max_v_samp_factor;
95
96         img->samp_h0 = dinfo.comp_info[0].h_samp_factor;
97         img->samp_v0 = dinfo.comp_info[0].v_samp_factor;
98
99         img->samp_h1 = dinfo.comp_info[1].h_samp_factor;
100         img->samp_v1 = dinfo.comp_info[1].v_samp_factor;
101
102         img->samp_h2 = dinfo.comp_info[2].h_samp_factor;
103         img->samp_v2 = dinfo.comp_info[2].v_samp_factor;
104
105         img->data_y  = (JSAMPLE*)memalign(16, dinfo.comp_info[0].height_in_blocks * dinfo.comp_info[0].width_in_blocks * DCTSIZE * DCTSIZE);
106         img->data_cb = (JSAMPLE*)memalign(16, dinfo.comp_info[1].height_in_blocks * dinfo.comp_info[1].width_in_blocks * DCTSIZE * DCTSIZE);
107         img->data_cr = (JSAMPLE*)memalign(16, dinfo.comp_info[2].height_in_blocks * dinfo.comp_info[2].width_in_blocks * DCTSIZE * DCTSIZE);
108
109         if (img->data_y == NULL || img->data_cb == NULL || img->data_cr == NULL) {
110                 qscale_destroy(img);
111                 return NULL;
112         }
113
114         int total_lines = 0, blocks = 0;
115         while (total_lines < dinfo.comp_info[0].height_in_blocks * DCTSIZE) {
116                 unsigned max_lines = dinfo.max_v_samp_factor * DCTSIZE;
117
118                 JSAMPROW y_row_ptrs[max_lines];
119                 JSAMPROW cb_row_ptrs[max_lines];
120                 JSAMPROW cr_row_ptrs[max_lines];
121                 JSAMPROW* ptrs[] = { y_row_ptrs, cb_row_ptrs, cr_row_ptrs };
122
123                 int i;
124                 for (i = 0; i < max_lines; ++i) {
125                         y_row_ptrs[i]  = img->data_y  + (i+blocks*DCTSIZE*dinfo.comp_info[0].v_samp_factor) * dinfo.comp_info[0].width_in_blocks * DCTSIZE;
126                         cb_row_ptrs[i] = img->data_cb + (i+blocks*DCTSIZE*dinfo.comp_info[1].v_samp_factor) * dinfo.comp_info[1].width_in_blocks * DCTSIZE;
127                         cr_row_ptrs[i] = img->data_cr + (i+blocks*DCTSIZE*dinfo.comp_info[2].v_samp_factor) * dinfo.comp_info[2].width_in_blocks * DCTSIZE;
128                 }
129
130                 total_lines += max_lines;
131                 ++blocks;
132
133                 if (jpeg_read_raw_data(&dinfo, ptrs, max_lines) == 0)
134                         break;
135         }
136
137         jpeg_destroy_decompress(&dinfo);
138         return img;
139 }
140
141 void qscale_destroy(qscale_img *img)
142 {
143         free(img->data_y);
144         free(img->data_cb);
145         free(img->data_cr);
146         free(img);
147 }
148
149
150 static double sinc(double x)
151 {
152         static const double cutoff = 1.220703668e-4;  /* sqrt(sqrt(eps)) */
153
154         if (abs(x) < cutoff) {
155                 /* For small |x|, use Taylor series instead */
156                 const double x2 = x * x;
157                 const double x4 = x2 * x2;
158
159                 return 1.0 - x2 / 6.0 + x4 / 120.0;
160         } else {
161                 return sin(x) / x;
162         }
163 }
164
165 static double lanczos_tap(double x)
166 {
167         if (x < -3.0 || x > 3.0)
168                 return 0.0;
169         if (x < 0.0)
170                 return sinc(-x*M_PI) * sinc(-x*M_PI / 3.0);
171         else
172                 return sinc(x*M_PI) * sinc(x*M_PI / 3.0);
173 }
174
175 struct pix_desc {
176         unsigned start, end;
177         unsigned startcoeff;
178 };
179
180 static void hscale(float *pix, unsigned char *npix, unsigned w, unsigned h, unsigned nw, unsigned sstride, unsigned dstride)
181 {
182         struct pix_desc *pd = (struct pix_desc *)malloc(nw * sizeof(struct pix_desc));
183         int size_coeffs = 8;
184         float *coeffs = (float *)malloc(size_coeffs * sizeof(float));
185         int num_coeffs = 0;
186         int x, y;
187         double sf = (double)w / (double)nw;
188         double support = (w > nw) ? (3.0 * sf) : (3.0 / sf);
189
190         /* calculate the filter */
191         for (x = 0; x < nw; ++x) {
192                 int start = ceil(x * sf - support);
193                 int end = floor(x * sf + support);
194                 int sx;
195                 double sum = 0.0;
196
197                 if (start < 0) {
198                         start = 0;
199                 }
200                 if (end > w - 1) {
201                         end = w - 1;
202                 }
203
204 #if USE_HORIZONTAL_SSE
205                 /* round up so we get a multiple of four for the SSE code */
206                 int num = (end - start + 1);
207                 if (num % 4 != 0) {
208                         /* prefer aligning it if possible */
209                         if (start % 4 != 0 && start % 4 <= num % 4) {
210                                 num += start % 4;
211                                 start -= start % 4;
212                         }
213                         if (num % 4 != 0) {
214                                 end += 4 - (num % 4);
215                         }
216                 }
217 #endif
218
219                 pd[x].start = start;
220                 pd[x].end = end;
221                 pd[x].startcoeff = num_coeffs;
222
223                 for (sx = start; sx <= end; ++sx) {
224                         double nd = (w > nw) ? (sx/sf - x) : (sx - x*sf);
225                         double f = lanczos_tap(nd);
226                         if (num_coeffs == size_coeffs) {
227                                 size_coeffs <<= 1;
228                                 coeffs = (float *)realloc(coeffs, size_coeffs * sizeof(float));
229                         }
230
231                         coeffs[num_coeffs++] = f;
232                         sum += f;
233                 }
234
235                 for (sx = start; sx <= end; ++sx) {
236                         coeffs[pd[x].startcoeff + sx - start] /= sum;
237                 }
238         }
239
240         for (y = 0; y < h; ++y) {
241                 float *sptr = pix + y*sstride;
242                 unsigned char *dptr = npix + y*dstride;
243                 unsigned char ch;
244                 for (x = 0; x < nw; ++x) {
245 #if USE_HORIZONTAL_SSE
246                         int result;
247                         float acc;
248                         long tmp;
249                         static const float low = 0.0, high = 255.0;
250                         __asm__ (
251                                 "pxor %1, %1               \n"
252                                 "xor %2, %2                \n"
253                                 "0:                        \n"
254                                 "movups (%4,%2),%%xmm1     \n"
255                                 "movups (%3,%2),%%xmm2     \n"
256                                 "mulps %%xmm2,%%xmm1       \n"
257                                 "addps %%xmm1,%1           \n"
258                                 "add $16,%2                \n"
259                                 "dec %5                    \n"
260                                 "jnz 0b                    \n"
261                                 "haddps %1,%1              \n"
262                                 "haddps %1,%1              \n"
263                                 "maxss %6,%1               \n"
264                                 "minss %7,%1               \n"
265                                 "cvtss2si %1,%0            \n"
266                                 : "=r" (result),
267                                   "=&x" (acc),
268                                   "=&r" (tmp)
269                                 : "r" (&coeffs[pd[x].startcoeff]),
270                                   "r" (&sptr[pd[x].start]),
271                                   "r" ((pd[x].end - pd[x].start + 1)/4),
272                                   "m" (low),
273                                   "m" (high)
274                                 : "memory", "xmm1", "xmm2"
275                         );
276
277                         *dptr++ = (unsigned char)result;
278 #else
279                         float acc = 0.0;
280                         float *cf = &coeffs[pd[x].startcoeff];
281                         unsigned sx;
282                         
283                         for (sx = pd[x].start; sx <= pd[x].end; ++sx) {
284                                 acc += sptr[sx] * *cf++;
285                         }
286
287                         if (acc < 0.0)
288                                 ch = 0;
289                         else if (acc > 255.0)
290                                 ch = 255;
291                         else
292                                 ch = (unsigned char)acc;
293                         *dptr++ = ch;
294 #endif
295                 }
296                 ch = dptr[-1];
297                 for ( ; x < dstride; ++x) {
298                         *dptr++ = ch;
299                 }
300         }
301 }
302
303 static void vscale(unsigned char *pix, float *npix, unsigned w, unsigned h, unsigned nh, unsigned dstride)
304 {
305         struct pix_desc *pd = (struct pix_desc *)malloc(nh * sizeof(struct pix_desc));
306         int size_coeffs = 8;
307         float *coeffs = (float *)malloc(size_coeffs * sizeof(float));
308         int num_coeffs = 0;
309         int x, y, sy;
310         double sf = (double)h / (double)nh;
311         double support = (h > nh) ? (3.0 * sf) : (3.0 / sf);
312
313         /* calculate the filter */
314         for (y = 0; y < nh; ++y) {
315                 int start = ceil(y * sf - support);
316                 int end = floor(y * sf + support);
317                 double sum = 0.0;
318
319                 if (start < 0) {
320                         start = 0;
321                 }
322                 if (end > h - 1) {
323                         end = h - 1;
324                 }
325
326                 pd[y].start = start;
327                 pd[y].end = end;
328                 pd[y].startcoeff = num_coeffs;
329
330                 for (sy = start; sy <= end; ++sy) {
331                         double nd = (h > nh) ? (sy/sf - y) : (sy - y*sf);
332                         double f = lanczos_tap(nd);
333                         if (num_coeffs == size_coeffs) {
334                                 size_coeffs <<= 1;
335                                 coeffs = (float *)realloc(coeffs, size_coeffs * sizeof(float));
336                         }
337                         
338                         coeffs[num_coeffs++] = f;
339                         sum += f;
340                 }
341
342                 for (sy = start; sy <= end; ++sy) {
343                         coeffs[pd[y].startcoeff + sy - start] /= sum;
344                 }
345         }
346
347 #if CACHE_LINE_FACTOR > 1
348         for (x = 0; x < (w/CACHE_LINE_FACTOR) * CACHE_LINE_FACTOR; x += CACHE_LINE_FACTOR) {
349                 unsigned char *sptr = pix + x;
350                 float *dptr = npix + x;
351                 for (y = 0; y < nh; ++y) {
352 #if USE_VERTICAL_SSE
353                         /*
354                          * xmm0 - xmm3: acc[0..15]
355                          * xmm4: current filter coefficient
356                          * xmm5, xmm6, xmm7: scratchpad
357                          */
358                         __asm__ (
359                                 /* clear */
360                                 "pxor %%xmm0, %%xmm0          \n"
361                                 "pxor %%xmm1, %%xmm1          \n"
362                                 "pxor %%xmm2, %%xmm2          \n"
363                                 "pxor %%xmm3, %%xmm3          \n"
364
365                                 /* main loop */
366                                 "0:                           \n"
367                                 
368                                 /* a zero is useful during unpacking */
369                                 "pxor %%xmm4, %%xmm4          \n"
370                                 
371                                 /* fetch all 16 source bytes */
372                                 "movups (%0), %%xmm5          \n"
373                                 "prefetcht0 (%0,%3,4)         \n"
374
375                                 /* unpack into words (xmm5, xmm7) */
376                                 "movaps %%xmm5, %%xmm7        \n"
377                                 "punpcklbw %%xmm4, %%xmm5     \n"
378                                 "punpckhbw %%xmm4, %%xmm7     \n"
379
380                                 /* unpack xmm5 into dwords (xmm5, xmm6) */
381                                 "movaps %%xmm5, %%xmm6        \n"
382                                 "punpcklwd %%xmm4, %%xmm5     \n"
383                                 "punpckhwd %%xmm4, %%xmm6     \n"
384
385                                 /* convert xmm5, xmm6 to floats */
386                                 "cvtdq2ps %%xmm5, %%xmm5      \n"
387                                 "cvtdq2ps %%xmm6, %%xmm6      \n"
388
389                                 /* fetch the coefficient */
390                                 "movss (%2), %%xmm4           \n"
391                                 "shufps $0x0, %%xmm4, %%xmm4  \n"
392
393                                 /* do the muls for xmm5 and xmm6 */
394                                 "mulps %%xmm4, %%xmm5         \n"
395                                 "mulps %%xmm4, %%xmm6         \n"
396                                 "addps %%xmm5, %%xmm0         \n"
397                                 "addps %%xmm6, %%xmm1         \n"
398
399                                 /* get the zero back again */
400                                 "pxor %%xmm4, %%xmm4          \n"
401
402                                 /* unpack xmm7 into dwords (xmm7, xmm6) */
403                                 "movaps %%xmm7, %%xmm6        \n"
404                                 "punpcklwd %%xmm4, %%xmm7     \n"
405                                 "punpckhwd %%xmm4, %%xmm6     \n"
406
407                                 /* convert xmm7, xmm6 to floats */
408                                 "cvtdq2ps %%xmm7, %%xmm7      \n"
409                                 "cvtdq2ps %%xmm6, %%xmm6      \n"
410
411                                 /* fetch the coefficient */
412                                 "movss (%2), %%xmm4           \n"
413                                 "shufps $0x0, %%xmm4, %%xmm4  \n"
414
415                                 /* do the second set of muls */
416                                 "mulps %%xmm4, %%xmm7         \n"
417                                 "mulps %%xmm4, %%xmm6         \n"
418                                 "addps %%xmm7, %%xmm2         \n"
419                                 "addps %%xmm6, %%xmm3         \n"
420
421                                 /* move along, and loop */
422                                 "add $4, %2                   \n"
423                                 "add %3, %0                   \n"
424                                 "dec %1                       \n"
425                                 "jnz 0b                       \n"
426
427                                 /* store the values */
428                                 "movaps %%xmm0, (%4)          \n"
429                                 "movaps %%xmm1, 16(%4)        \n"
430                                 "movaps %%xmm2, 32(%4)        \n"
431                                 "movaps %%xmm3, 48(%4)        \n"
432                                 : :
433                                 "r" (&sptr[pd[y].start * w]),        /* 0: srcptr base */
434                                 "r" (pd[y].end - pd[y].start + 1),   /* 1: filter len */
435                                 "r" (&coeffs[pd[y].startcoeff]),     /* 2: coeffs base */
436                                 "r" ((long)w),                       /* 3: stride */
437                                 "r" (dptr)                           /* 4: dstptr base */
438                                 : "memory", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7"
439                         );
440 #else
441                         int i;
442                         float acc[CACHE_LINE_FACTOR];
443                         for (i = 0; i < CACHE_LINE_FACTOR; ++i)
444                                 acc[i] = 0.0;
445                         float *cf = &coeffs[pd[y].startcoeff];
446                         unsigned sy;
447                 
448                         for (sy = pd[y].start; sy <= pd[y].end; ++sy) {
449                                 for (i = 0; i < CACHE_LINE_FACTOR; ++i) {
450                                         acc[i] += sptr[sy * w + i] * *cf;
451                                 }
452                                 ++cf;
453                         }
454
455                         for (i = 0; i < CACHE_LINE_FACTOR; ++i) {
456                                 dptr[i] = acc[i];
457                         }
458 #endif
459                         dptr += dstride;
460                 }
461         }
462         for (x = (x/CACHE_LINE_FACTOR)*CACHE_LINE_FACTOR; x < w; ++x) {
463 #else
464         for (x = 0; x < w; ++x) {
465 #endif
466                 unsigned char *sptr = pix + x;
467                 float *dptr = npix + x;
468                 for (y = 0; y < nh; ++y) {
469                         float acc = 0.0;
470                         float *cf = &coeffs[pd[y].startcoeff];
471                         unsigned sy;
472                         
473                         for (sy = pd[y].start; sy <= pd[y].end; ++sy) {
474                                 acc += sptr[sy * w] * *cf++;
475                         }
476
477                         *dptr = acc;
478                         dptr += dstride;
479                 }
480         }
481 }
482
483 qscale_img *qscale_clone(const qscale_img *img)
484 {
485         qscale_img *dst = (qscale_img *)malloc(sizeof(qscale_img));
486         if (dst == NULL) {
487                 return NULL;
488         }
489
490         *dst = *img;
491
492         unsigned dstride0 = (dst->w0 + DCTSIZE-1) & ~(DCTSIZE-1);
493         unsigned dstride1 = (dst->w1 + DCTSIZE-1) & ~(DCTSIZE-1);
494         unsigned dstride2 = (dst->w2 + DCTSIZE-1) & ~(DCTSIZE-1);
495
496         /* FIXME: handle out-of-memory gracefully */
497         {
498                 dst->data_y = (unsigned char *)malloc(dst->h0 * dstride0);
499                 memcpy(dst->data_y, img->data_y, dst->h0 * dstride0);
500         }
501         {
502                 dst->data_cb = (unsigned char *)malloc(dst->h1 * dstride1);
503                 memcpy(dst->data_cb, img->data_cb, dst->h0 * dstride0);
504         }
505         {
506                 dst->data_cr = (unsigned char *)malloc(dst->h1 * dstride1);
507                 memcpy(dst->data_cr, img->data_cr, dst->h0 * dstride0);
508         }
509
510         return dst;
511 }
512
513 qscale_img *qscale_scale(qscale_img *src, unsigned width, unsigned height, unsigned samp_h0, unsigned samp_v0, unsigned samp_h1, unsigned samp_v1, unsigned samp_h2, unsigned samp_v2, enum qscale_scaling_filter scaling_filter)
514 {
515         qscale_img *dst = (qscale_img *)malloc(sizeof(qscale_img));
516         if (dst == NULL) {
517                 return NULL;
518         }
519
520         dst->width = width;
521         dst->height = height;
522
523         unsigned max_samp_h, max_samp_v;
524         max_samp_h = samp_h0;
525         if (samp_h1 > max_samp_h)
526                 max_samp_h = samp_h1;
527         if (samp_h2 > max_samp_h)
528                 max_samp_h = samp_h2;
529
530         max_samp_v = samp_v0;
531         if (samp_v1 > max_samp_v)
532                 max_samp_v = samp_v1;
533         if (samp_v2 > max_samp_v)
534                 max_samp_v = samp_v2;
535
536         dst->w0 = width * samp_h0 / max_samp_h;
537         dst->h0 = height * samp_v0 / max_samp_v;
538
539         dst->w1 = width * samp_h1 / max_samp_h;
540         dst->h1 = height * samp_v1 / max_samp_v;
541
542         dst->w2 = width * samp_h2 / max_samp_h;
543         dst->h2 = height * samp_v2 / max_samp_v;
544
545         dst->samp_h0 = samp_h0;
546         dst->samp_v0 = samp_v0;
547
548         dst->samp_h1 = samp_h1;
549         dst->samp_v1 = samp_v1;
550
551         dst->samp_h2 = samp_h2;
552         dst->samp_v2 = samp_v2;
553
554         unsigned dstride0 = (dst->w0 + DCTSIZE-1) & ~(DCTSIZE-1);
555         unsigned dstride1 = (dst->w1 + DCTSIZE-1) & ~(DCTSIZE-1);
556         unsigned dstride2 = (dst->w2 + DCTSIZE-1) & ~(DCTSIZE-1);
557
558         unsigned sstride0 = (src->w0 + DCTSIZE-1) & ~(DCTSIZE-1);
559         unsigned sstride1 = (src->w1 + DCTSIZE-1) & ~(DCTSIZE-1);
560         unsigned sstride2 = (src->w2 + DCTSIZE-1) & ~(DCTSIZE-1);
561
562         /* FIXME: handle out-of-memory gracefully */
563         {
564                 float *npix = (float*)memalign(16, sstride0 * dst->h0 * sizeof(float));
565                 vscale(src->data_y, npix, sstride0, src->h0, dst->h0, sstride0);
566                 dst->data_y = (unsigned char *)malloc(dst->h0 * dstride0);
567                 hscale(npix, dst->data_y, src->w0, dst->h0, dst->w0, sstride0, dstride0);
568                 free(npix);
569         }
570         {
571                 float *npix = (float*)memalign(16, sstride1 * dst->h1 * sizeof(float));
572                 vscale(src->data_cr, npix, sstride1, src->h1, dst->h1, sstride1);
573                 dst->data_cr = (unsigned char *)malloc(dst->h1 * dstride1);
574                 hscale(npix, dst->data_cr, src->w1, dst->h1, dst->w1, sstride1, dstride1);
575                 free(npix);
576         }
577         {
578                 float *npix = (float*)memalign(16, sstride2 * dst->h2 * sizeof(float));
579                 vscale(src->data_cb, npix, sstride2, src->h2, dst->h2, sstride2);
580                 dst->data_cb = (unsigned char *)malloc(dst->h2 * dstride2);
581                 hscale(npix, dst->data_cb, src->w2, dst->h2, dst->w2, sstride2, dstride2);
582                 free(npix);
583         }
584
585         return dst;
586 }
587
588 int qscale_save_jpeg(const qscale_img *img, const char *filename, unsigned jpeg_quality, enum qscale_jpeg_mode jpeg_mode)
589 {
590         FILE *file = fopen(filename, "wb");
591         if (file == NULL) {
592                 return -1;
593         }
594
595         int err = qscale_save_jpeg_to_stdio(img, file, jpeg_quality, jpeg_mode);
596
597         fclose(file);
598         return err;
599 }
600
601 int qscale_save_jpeg_to_stdio(const qscale_img *img, FILE *file, unsigned jpeg_quality, enum qscale_jpeg_mode jpeg_mode)
602 {
603         struct jpeg_compress_struct cinfo;
604         struct jpeg_error_mgr jerr;
605         cinfo.err = jpeg_std_error(&jerr);
606         jpeg_create_compress(&cinfo);
607         jpeg_stdio_dest(&cinfo, file);
608         cinfo.input_components = 3;
609         jpeg_set_defaults(&cinfo);
610         jpeg_set_quality(&cinfo, jpeg_quality, FALSE);
611
612         if (jpeg_mode == PROGRESSIVE) {
613                 jpeg_simple_progression(&cinfo);
614         }
615
616         cinfo.image_width = img->width;
617         cinfo.image_height = img->height;
618         cinfo.raw_data_in = TRUE;
619         jpeg_set_colorspace(&cinfo, JCS_YCbCr);
620         cinfo.comp_info[0].h_samp_factor = img->samp_h0;
621         cinfo.comp_info[0].v_samp_factor = img->samp_v0;
622         cinfo.comp_info[1].h_samp_factor = img->samp_h1;
623         cinfo.comp_info[1].v_samp_factor = img->samp_v1;
624         cinfo.comp_info[2].h_samp_factor = img->samp_h2;
625         cinfo.comp_info[2].v_samp_factor = img->samp_v2;
626         jpeg_start_compress(&cinfo, TRUE);
627
628         unsigned dstride0 = (img->w0 + DCTSIZE-1) & ~(DCTSIZE-1);
629         unsigned dstride1 = (img->w1 + DCTSIZE-1) & ~(DCTSIZE-1);
630         unsigned dstride2 = (img->w2 + DCTSIZE-1) & ~(DCTSIZE-1);
631
632         int total_lines = 0;
633         int blocks = 0;
634         while (total_lines < cinfo.comp_info[0].height_in_blocks * DCTSIZE) {
635                 unsigned max_lines = cinfo.max_v_samp_factor * DCTSIZE;
636
637                 JSAMPROW y_row_ptrs[max_lines];
638                 JSAMPROW cb_row_ptrs[max_lines];
639                 JSAMPROW cr_row_ptrs[max_lines];
640                 JSAMPROW* ptrs[] = { y_row_ptrs, cb_row_ptrs, cr_row_ptrs };
641                 int i;
642
643                 for (i = 0; i < max_lines; ++i) {
644                         /* simple edge extension */
645                         int yline = i + blocks*DCTSIZE*cinfo.comp_info[0].v_samp_factor;
646                         if (yline > img->h0 - 1)
647                                 yline = img->h0 - 1;
648
649                         int cbline = i + blocks*DCTSIZE*cinfo.comp_info[1].v_samp_factor;
650                         if (cbline > img->h1 - 1)
651                                 cbline = img->h1 - 1;
652
653                         int crline = i + blocks*DCTSIZE*cinfo.comp_info[2].v_samp_factor;
654                         if (crline > img->h2 - 1)
655                                 crline = img->h2 - 1;
656
657                         y_row_ptrs[i]  = img->data_y  + yline * dstride0;
658                         cb_row_ptrs[i] = img->data_cb + cbline * dstride1;
659                         cr_row_ptrs[i] = img->data_cr + crline * dstride2;
660                 }
661
662                 total_lines += max_lines;
663                 ++blocks;
664
665                 jpeg_write_raw_data(&cinfo, ptrs, max_lines);
666         }
667         jpeg_finish_compress(&cinfo);
668         jpeg_destroy_compress(&cinfo);
669
670         return 0;
671 }