]> git.sesse.net Git - qscale/blob - libqscale.c
47b6fe8959c8d0db09545c0f3448a012658d6dde
[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         if (dinfo.num_components != 1 && dinfo.num_components != 3) {
79                 qscale_destroy(img);
80                 return NULL;
81         }
82         img->num_components = dinfo.num_components;
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         if (img->num_components == 3) {
91                 img->w1 = dinfo.image_width * dinfo.comp_info[1].h_samp_factor / dinfo.max_h_samp_factor;
92                 img->h1 = dinfo.image_height * dinfo.comp_info[1].v_samp_factor / dinfo.max_v_samp_factor;
93
94                 img->w2 = dinfo.image_width * dinfo.comp_info[2].h_samp_factor / dinfo.max_h_samp_factor;
95                 img->h2 = dinfo.image_height * dinfo.comp_info[2].v_samp_factor / dinfo.max_v_samp_factor;
96         }
97
98         img->samp_h0 = dinfo.comp_info[0].h_samp_factor;
99         img->samp_v0 = dinfo.comp_info[0].v_samp_factor;
100
101         if (img->num_components == 3) {
102                 img->samp_h1 = dinfo.comp_info[1].h_samp_factor;
103                 img->samp_v1 = dinfo.comp_info[1].v_samp_factor;
104
105                 img->samp_h2 = dinfo.comp_info[2].h_samp_factor;
106                 img->samp_v2 = dinfo.comp_info[2].v_samp_factor;
107         }
108
109         img->data_y  = (JSAMPLE*)memalign(16, dinfo.comp_info[0].height_in_blocks * dinfo.comp_info[0].width_in_blocks * DCTSIZE * DCTSIZE);
110         if (img->data_y == NULL) {
111                 qscale_destroy(img);
112                 return NULL;
113         }
114
115         if (img->num_components == 3) {
116                 img->data_cb = (JSAMPLE*)memalign(16, dinfo.comp_info[1].height_in_blocks * dinfo.comp_info[1].width_in_blocks * DCTSIZE * DCTSIZE);
117                 img->data_cr = (JSAMPLE*)memalign(16, dinfo.comp_info[2].height_in_blocks * dinfo.comp_info[2].width_in_blocks * DCTSIZE * DCTSIZE);
118                 if (img->data_cb == NULL || img->data_cr == NULL) {
119                         qscale_destroy(img);
120                         return NULL;
121                 }
122         }
123
124         int total_lines = 0, blocks = 0;
125         while (total_lines < dinfo.comp_info[0].height_in_blocks * DCTSIZE) {
126                 unsigned max_lines = dinfo.max_v_samp_factor * DCTSIZE;
127
128                 JSAMPROW y_row_ptrs[max_lines];
129                 JSAMPROW cb_row_ptrs[max_lines];
130                 JSAMPROW cr_row_ptrs[max_lines];
131                 JSAMPROW* ptrs[] = { y_row_ptrs, cb_row_ptrs, cr_row_ptrs };
132
133                 int i;
134                 for (i = 0; i < max_lines; ++i) {
135                         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;
136                         if (img->num_components == 3) {
137                                 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;
138                                 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;
139                         }
140                 }
141
142                 total_lines += max_lines;
143                 ++blocks;
144
145                 if (jpeg_read_raw_data(&dinfo, ptrs, max_lines) == 0)
146                         break;
147         }
148
149         jpeg_destroy_decompress(&dinfo);
150         return img;
151 }
152
153 void qscale_destroy(qscale_img *img)
154 {
155         free(img->data_y);
156         free(img->data_cb);
157         free(img->data_cr);
158         free(img);
159 }
160
161
162 static double sinc(double x)
163 {
164         static const double cutoff = 1.220703668e-4;  /* sqrt(sqrt(eps)) */
165
166         if (abs(x) < cutoff) {
167                 /* For small |x|, use Taylor series instead */
168                 const double x2 = x * x;
169                 const double x4 = x2 * x2;
170
171                 return 1.0 - x2 / 6.0 + x4 / 120.0;
172         } else {
173                 return sin(x) / x;
174         }
175 }
176
177 static double lanczos_tap(double x)
178 {
179         if (x < -3.0 || x > 3.0)
180                 return 0.0;
181         if (x < 0.0)
182                 return sinc(-x*M_PI) * sinc(-x*M_PI / 3.0);
183         else
184                 return sinc(x*M_PI) * sinc(x*M_PI / 3.0);
185 }
186
187 static double mitchell_tap(double x)
188 {
189         const double b = 1.0 / 3.0;
190         const double c = 1.0 / 3.0;
191         const double p0 = (  6.0 -  2.0*b         ) / 6.0;
192         const double p2 = (-18.0 + 12.0*b +  6.0*c) / 6.0;
193         const double p3 = ( 12.0 -  9.0*b -  6.0*c) / 6.0;
194         const double q0 = (         8.0*b + 24.0*c) / 6.0;
195         const double q1 = (      - 12.0*b - 48.0*c) / 6.0;
196         const double q2 = (         6.0*b + 30.0*c) / 6.0;
197         const double q3 = (      -      b -  6.0*c) / 6.0;
198
199         if (x < -2.0) {
200                 return 0.0;
201         } else if (x < -1.0) {
202                 return q0 - x * (q1 - x * (q2 - x * q3));
203         } else if (x < 0.0) {
204                 return p0 + x * x * (p2 - x * p3);
205         } else if (x < 1.0) {
206                 return p0 + x * x * (p2 + x * p3);
207         } else if (x < 2.0) {
208                 return q0 + x * (q1 + x * (q2 + x * q3));
209         } else {
210                 return 0.0;
211         }
212 }
213
214 struct pix_desc {
215         unsigned start, end;
216         unsigned startcoeff;
217 };
218
219 static void hscale(float *pix, unsigned char *npix, unsigned w, unsigned h, unsigned nw, unsigned sstride, unsigned dstride, enum qscale_scaling_filter scaling_filter)
220 {
221         struct pix_desc *pd = (struct pix_desc *)malloc(nw * sizeof(struct pix_desc));
222         int size_coeffs = 8;
223         float *coeffs = (float *)malloc(size_coeffs * sizeof(float));
224         int num_coeffs = 0;
225         int x, y;
226         double sf = (double)w / (double)nw;
227         double support;
228         
229         if (scaling_filter == LANCZOS) {
230                 support = (w > nw) ? (3.0 * sf) : (3.0 / sf);
231         } else {  /* Mitchell */
232                 support = (w > nw) ? (2.0 * sf) : (2.0 / sf);
233         }
234
235         /* calculate the filter */
236         for (x = 0; x < nw; ++x) {
237                 int start = ceil(x * sf - support);
238                 int end = floor(x * sf + support);
239                 int sx;
240                 double sum = 0.0;
241
242                 if (start < 0) {
243                         start = 0;
244                 }
245                 if (end > w - 1) {
246                         end = w - 1;
247                 }
248
249 #if USE_HORIZONTAL_SSE
250                 /* round up so we get a multiple of four for the SSE code */
251                 int num = (end - start + 1);
252                 if (num % 4 != 0) {
253                         /* prefer aligning it if possible */
254                         if (start % 4 != 0 && start % 4 <= num % 4) {
255                                 num += start % 4;
256                                 start -= start % 4;
257                         }
258                         if (num % 4 != 0) {
259                                 end += 4 - (num % 4);
260                         }
261                 }
262 #endif
263
264                 pd[x].start = start;
265                 pd[x].end = end;
266                 pd[x].startcoeff = num_coeffs;
267
268                 for (sx = start; sx <= end; ++sx) {
269                         double nd = (w > nw) ? (sx/sf - x) : (sx - x*sf);
270                         double f;
271                         if (scaling_filter == LANCZOS) {
272                                 f = lanczos_tap(nd);
273                         } else {  /* Mitchell */
274                                 f = mitchell_tap(nd);
275                         }
276                         if (num_coeffs == size_coeffs) {
277                                 size_coeffs <<= 1;
278                                 coeffs = (float *)realloc(coeffs, size_coeffs * sizeof(float));
279                         }
280
281                         coeffs[num_coeffs++] = f;
282                         sum += f;
283                 }
284
285                 for (sx = start; sx <= end; ++sx) {
286                         coeffs[pd[x].startcoeff + sx - start] /= sum;
287                 }
288         }
289
290         for (y = 0; y < h; ++y) {
291                 float *sptr = pix + y*sstride;
292                 unsigned char *dptr = npix + y*dstride;
293                 unsigned char ch;
294                 for (x = 0; x < nw; ++x) {
295 #if USE_HORIZONTAL_SSE
296                         int result;
297                         float acc;
298                         long tmp;
299                         static const float low = 0.0, high = 255.0;
300                         __asm__ (
301                                 "pxor %1, %1               \n"
302                                 "xor %2, %2                \n"
303                                 "0:                        \n"
304                                 "movups (%4,%2),%%xmm1     \n"
305                                 "movups (%3,%2),%%xmm2     \n"
306                                 "mulps %%xmm2,%%xmm1       \n"
307                                 "addps %%xmm1,%1           \n"
308                                 "add $16,%2                \n"
309                                 "dec %5                    \n"
310                                 "jnz 0b                    \n"
311                                 "haddps %1,%1              \n"
312                                 "haddps %1,%1              \n"
313                                 "maxss %6,%1               \n"
314                                 "minss %7,%1               \n"
315                                 "cvtss2si %1,%0            \n"
316                                 : "=r" (result),
317                                   "=&x" (acc),
318                                   "=&r" (tmp)
319                                 : "r" (&coeffs[pd[x].startcoeff]),
320                                   "r" (&sptr[pd[x].start]),
321                                   "r" ((pd[x].end - pd[x].start + 1)/4),
322                                   "m" (low),
323                                   "m" (high)
324                                 : "memory", "xmm1", "xmm2"
325                         );
326
327                         *dptr++ = (unsigned char)result;
328 #else
329                         float acc = 0.0;
330                         float *cf = &coeffs[pd[x].startcoeff];
331                         unsigned sx;
332                         
333                         for (sx = pd[x].start; sx <= pd[x].end; ++sx) {
334                                 acc += sptr[sx] * *cf++;
335                         }
336
337                         if (acc < 0.0)
338                                 ch = 0;
339                         else if (acc > 255.0)
340                                 ch = 255;
341                         else
342                                 ch = (unsigned char)acc;
343                         *dptr++ = ch;
344 #endif
345                 }
346                 ch = dptr[-1];
347                 for ( ; x < dstride; ++x) {
348                         *dptr++ = ch;
349                 }
350         }
351 }
352
353 static void vscale(unsigned char *pix, float *npix, unsigned w, unsigned h, unsigned nh, unsigned dstride, enum qscale_scaling_filter scaling_filter)
354 {
355         struct pix_desc *pd = (struct pix_desc *)malloc(nh * sizeof(struct pix_desc));
356         int size_coeffs = 8;
357         float *coeffs = (float *)malloc(size_coeffs * sizeof(float));
358         int num_coeffs = 0;
359         int x, y, sy;
360         double sf = (double)h / (double)nh;
361         double support;
362         
363         if (scaling_filter == LANCZOS) {
364                 support = (h > nh) ? (3.0 * sf) : (3.0 / sf);
365         } else {  /* Mitchell */
366                 support = (h > nh) ? (2.0 * sf) : (2.0 / sf);
367         }
368
369         /* calculate the filter */
370         for (y = 0; y < nh; ++y) {
371                 int start = ceil(y * sf - support);
372                 int end = floor(y * sf + support);
373                 double sum = 0.0;
374
375                 if (start < 0) {
376                         start = 0;
377                 }
378                 if (end > h - 1) {
379                         end = h - 1;
380                 }
381
382                 pd[y].start = start;
383                 pd[y].end = end;
384                 pd[y].startcoeff = num_coeffs;
385
386                 for (sy = start; sy <= end; ++sy) {
387                         double nd = (h > nh) ? (sy/sf - y) : (sy - y*sf);
388                         double f;
389                         if (scaling_filter == LANCZOS) {
390                                 f = lanczos_tap(nd);
391                         } else {  /* Mitchell */
392                                 f = mitchell_tap(nd);
393                         }
394                         if (num_coeffs == size_coeffs) {
395                                 size_coeffs <<= 1;
396                                 coeffs = (float *)realloc(coeffs, size_coeffs * sizeof(float));
397                         }
398                         
399                         coeffs[num_coeffs++] = f;
400                         sum += f;
401                 }
402
403                 for (sy = start; sy <= end; ++sy) {
404                         coeffs[pd[y].startcoeff + sy - start] /= sum;
405                 }
406         }
407
408 #if CACHE_LINE_FACTOR > 1
409         for (x = 0; x < (w/CACHE_LINE_FACTOR) * CACHE_LINE_FACTOR; x += CACHE_LINE_FACTOR) {
410                 unsigned char *sptr = pix + x;
411                 float *dptr = npix + x;
412                 for (y = 0; y < nh; ++y) {
413 #if USE_VERTICAL_SSE
414                         /*
415                          * xmm0 - xmm3: acc[0..15]
416                          * xmm4: current filter coefficient
417                          * xmm5, xmm6, xmm7: scratchpad
418                          */
419                         __asm__ (
420                                 /* clear */
421                                 "pxor %%xmm0, %%xmm0          \n"
422                                 "pxor %%xmm1, %%xmm1          \n"
423                                 "pxor %%xmm2, %%xmm2          \n"
424                                 "pxor %%xmm3, %%xmm3          \n"
425
426                                 /* main loop */
427                                 "0:                           \n"
428                                 
429                                 /* a zero is useful during unpacking */
430                                 "pxor %%xmm4, %%xmm4          \n"
431                                 
432                                 /* fetch all 16 source bytes */
433                                 "movups (%0), %%xmm5          \n"
434                                 "prefetcht0 (%0,%3,4)         \n"
435
436                                 /* unpack into words (xmm5, xmm7) */
437                                 "movaps %%xmm5, %%xmm7        \n"
438                                 "punpcklbw %%xmm4, %%xmm5     \n"
439                                 "punpckhbw %%xmm4, %%xmm7     \n"
440
441                                 /* unpack xmm5 into dwords (xmm5, xmm6) */
442                                 "movaps %%xmm5, %%xmm6        \n"
443                                 "punpcklwd %%xmm4, %%xmm5     \n"
444                                 "punpckhwd %%xmm4, %%xmm6     \n"
445
446                                 /* convert xmm5, xmm6 to floats */
447                                 "cvtdq2ps %%xmm5, %%xmm5      \n"
448                                 "cvtdq2ps %%xmm6, %%xmm6      \n"
449
450                                 /* fetch the coefficient */
451                                 "movss (%2), %%xmm4           \n"
452                                 "shufps $0x0, %%xmm4, %%xmm4  \n"
453
454                                 /* do the muls for xmm5 and xmm6 */
455                                 "mulps %%xmm4, %%xmm5         \n"
456                                 "mulps %%xmm4, %%xmm6         \n"
457                                 "addps %%xmm5, %%xmm0         \n"
458                                 "addps %%xmm6, %%xmm1         \n"
459
460                                 /* get the zero back again */
461                                 "pxor %%xmm4, %%xmm4          \n"
462
463                                 /* unpack xmm7 into dwords (xmm7, xmm6) */
464                                 "movaps %%xmm7, %%xmm6        \n"
465                                 "punpcklwd %%xmm4, %%xmm7     \n"
466                                 "punpckhwd %%xmm4, %%xmm6     \n"
467
468                                 /* convert xmm7, xmm6 to floats */
469                                 "cvtdq2ps %%xmm7, %%xmm7      \n"
470                                 "cvtdq2ps %%xmm6, %%xmm6      \n"
471
472                                 /* fetch the coefficient */
473                                 "movss (%2), %%xmm4           \n"
474                                 "shufps $0x0, %%xmm4, %%xmm4  \n"
475
476                                 /* do the second set of muls */
477                                 "mulps %%xmm4, %%xmm7         \n"
478                                 "mulps %%xmm4, %%xmm6         \n"
479                                 "addps %%xmm7, %%xmm2         \n"
480                                 "addps %%xmm6, %%xmm3         \n"
481
482                                 /* move along, and loop */
483                                 "add $4, %2                   \n"
484                                 "add %3, %0                   \n"
485                                 "dec %1                       \n"
486                                 "jnz 0b                       \n"
487
488                                 /* store the values */
489                                 "movaps %%xmm0, (%4)          \n"
490                                 "movaps %%xmm1, 16(%4)        \n"
491                                 "movaps %%xmm2, 32(%4)        \n"
492                                 "movaps %%xmm3, 48(%4)        \n"
493                                 : :
494                                 "r" (&sptr[pd[y].start * w]),        /* 0: srcptr base */
495                                 "r" (pd[y].end - pd[y].start + 1),   /* 1: filter len */
496                                 "r" (&coeffs[pd[y].startcoeff]),     /* 2: coeffs base */
497                                 "r" ((long)w),                       /* 3: stride */
498                                 "r" (dptr)                           /* 4: dstptr base */
499                                 : "memory", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7"
500                         );
501 #else
502                         int i;
503                         float acc[CACHE_LINE_FACTOR];
504                         for (i = 0; i < CACHE_LINE_FACTOR; ++i)
505                                 acc[i] = 0.0;
506                         float *cf = &coeffs[pd[y].startcoeff];
507                         unsigned sy;
508                 
509                         for (sy = pd[y].start; sy <= pd[y].end; ++sy) {
510                                 for (i = 0; i < CACHE_LINE_FACTOR; ++i) {
511                                         acc[i] += sptr[sy * w + i] * *cf;
512                                 }
513                                 ++cf;
514                         }
515
516                         for (i = 0; i < CACHE_LINE_FACTOR; ++i) {
517                                 dptr[i] = acc[i];
518                         }
519 #endif
520                         dptr += dstride;
521                 }
522         }
523         for (x = (x/CACHE_LINE_FACTOR)*CACHE_LINE_FACTOR; x < w; ++x) {
524 #else
525         for (x = 0; x < w; ++x) {
526 #endif
527                 unsigned char *sptr = pix + x;
528                 float *dptr = npix + x;
529                 for (y = 0; y < nh; ++y) {
530                         float acc = 0.0;
531                         float *cf = &coeffs[pd[y].startcoeff];
532                         unsigned sy;
533                         
534                         for (sy = pd[y].start; sy <= pd[y].end; ++sy) {
535                                 acc += sptr[sy * w] * *cf++;
536                         }
537
538                         *dptr = acc;
539                         dptr += dstride;
540                 }
541         }
542 }
543
544 qscale_img *qscale_clone(const qscale_img *img)
545 {
546         qscale_img *dst = (qscale_img *)malloc(sizeof(qscale_img));
547         if (dst == NULL) {
548                 return NULL;
549         }
550
551         *dst = *img;
552
553         unsigned dstride0 = (dst->w0 + DCTSIZE-1) & ~(DCTSIZE-1);
554         unsigned dstride1 = (dst->w1 + DCTSIZE-1) & ~(DCTSIZE-1);
555         unsigned dstride2 = (dst->w2 + DCTSIZE-1) & ~(DCTSIZE-1);
556
557         /* FIXME: handle out-of-memory gracefully */
558         {
559                 dst->data_y = (unsigned char *)malloc(dst->h0 * dstride0);
560                 memcpy(dst->data_y, img->data_y, dst->h0 * dstride0);
561         }
562         {
563                 dst->data_cb = (unsigned char *)malloc(dst->h1 * dstride1);
564                 memcpy(dst->data_cb, img->data_cb, dst->h1 * dstride1);
565         }
566         {
567                 dst->data_cr = (unsigned char *)malloc(dst->h2 * dstride2);
568                 memcpy(dst->data_cr, img->data_cr, dst->h2 * dstride2);
569         }
570
571         return dst;
572 }
573
574 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)
575 {
576         qscale_img *dst = (qscale_img *)malloc(sizeof(qscale_img));
577         if (dst == NULL) {
578                 return NULL;
579         }
580
581         dst->width = width;
582         dst->height = height;
583         dst->num_components = src->num_components;
584
585         unsigned max_samp_h, max_samp_v;
586         max_samp_h = samp_h0;
587         if (src->num_components == 3) {
588                 if (samp_h1 > max_samp_h)
589                         max_samp_h = samp_h1;
590                 if (samp_h2 > max_samp_h)
591                         max_samp_h = samp_h2;
592         }
593
594         max_samp_v = samp_v0;
595         if (src->num_components == 3) {
596                 if (samp_v1 > max_samp_v)
597                         max_samp_v = samp_v1;
598                 if (samp_v2 > max_samp_v)
599                         max_samp_v = samp_v2;
600         }
601
602         dst->w0 = width * samp_h0 / max_samp_h;
603         dst->h0 = height * samp_v0 / max_samp_v;
604
605         if (src->num_components == 3) {
606                 dst->w1 = width * samp_h1 / max_samp_h;
607                 dst->h1 = height * samp_v1 / max_samp_v;
608
609                 dst->w2 = width * samp_h2 / max_samp_h;
610                 dst->h2 = height * samp_v2 / max_samp_v;
611         }
612
613         dst->samp_h0 = samp_h0;
614         dst->samp_v0 = samp_v0;
615
616         if (src->num_components == 3) {
617                 dst->samp_h1 = samp_h1;
618                 dst->samp_v1 = samp_v1;
619
620                 dst->samp_h2 = samp_h2;
621                 dst->samp_v2 = samp_v2;
622         }
623
624         unsigned dstride0 = (dst->w0 + DCTSIZE-1) & ~(DCTSIZE-1);
625         unsigned dstride1 = (dst->w1 + DCTSIZE-1) & ~(DCTSIZE-1);
626         unsigned dstride2 = (dst->w2 + DCTSIZE-1) & ~(DCTSIZE-1);
627
628         unsigned sstride0 = (src->w0 + DCTSIZE-1) & ~(DCTSIZE-1);
629         unsigned sstride1 = (src->w1 + DCTSIZE-1) & ~(DCTSIZE-1);
630         unsigned sstride2 = (src->w2 + DCTSIZE-1) & ~(DCTSIZE-1);
631
632         /* FIXME: handle out-of-memory gracefully */
633         {
634                 float *npix = (float*)memalign(16, sstride0 * dst->h0 * sizeof(float));
635                 vscale(src->data_y, npix, sstride0, src->h0, dst->h0, sstride0, scaling_filter);
636                 dst->data_y = (unsigned char *)malloc(dst->h0 * dstride0);
637                 hscale(npix, dst->data_y, src->w0, dst->h0, dst->w0, sstride0, dstride0, scaling_filter);
638                 free(npix);
639         }
640         if (src->num_components == 3) {
641                 {
642                         float *npix = (float*)memalign(16, sstride1 * dst->h1 * sizeof(float));
643                         vscale(src->data_cr, npix, sstride1, src->h1, dst->h1, sstride1, scaling_filter);
644                         dst->data_cr = (unsigned char *)malloc(dst->h1 * dstride1);
645                         hscale(npix, dst->data_cr, src->w1, dst->h1, dst->w1, sstride1, dstride1, scaling_filter);
646                         free(npix);
647                 }
648                 {
649                         float *npix = (float*)memalign(16, sstride2 * dst->h2 * sizeof(float));
650                         vscale(src->data_cb, npix, sstride2, src->h2, dst->h2, sstride2, scaling_filter);
651                         dst->data_cb = (unsigned char *)malloc(dst->h2 * dstride2);
652                         hscale(npix, dst->data_cb, src->w2, dst->h2, dst->w2, sstride2, dstride2, scaling_filter);
653                         free(npix);
654                 }
655         }
656
657         return dst;
658 }
659
660 int qscale_save_jpeg(const qscale_img *img, const char *filename, unsigned jpeg_quality, enum qscale_jpeg_mode jpeg_mode)
661 {
662         FILE *file = fopen(filename, "wb");
663         if (file == NULL) {
664                 return -1;
665         }
666
667         int err = qscale_save_jpeg_to_stdio(img, file, jpeg_quality, jpeg_mode);
668
669         fclose(file);
670         return err;
671 }
672
673 int qscale_save_jpeg_to_stdio(const qscale_img *img, FILE *file, unsigned jpeg_quality, enum qscale_jpeg_mode jpeg_mode)
674 {
675         struct jpeg_compress_struct cinfo;
676         struct jpeg_error_mgr jerr;
677         cinfo.err = jpeg_std_error(&jerr);
678         jpeg_create_compress(&cinfo);
679         jpeg_stdio_dest(&cinfo, file);
680         cinfo.input_components = img->num_components;
681         jpeg_set_defaults(&cinfo);
682         jpeg_set_quality(&cinfo, jpeg_quality, FALSE);
683
684         if (jpeg_mode == PROGRESSIVE) {
685                 jpeg_simple_progression(&cinfo);
686         }
687
688         cinfo.image_width = img->width;
689         cinfo.image_height = img->height;
690         cinfo.raw_data_in = TRUE;
691         if (img->num_components == 3) {
692                 jpeg_set_colorspace(&cinfo, JCS_YCbCr);
693         } else {
694                 jpeg_set_colorspace(&cinfo, JCS_GRAYSCALE);
695         }
696         cinfo.comp_info[0].h_samp_factor = img->samp_h0;
697         cinfo.comp_info[0].v_samp_factor = img->samp_v0;
698         if (img->num_components == 3) {
699                 cinfo.comp_info[1].h_samp_factor = img->samp_h1;
700                 cinfo.comp_info[1].v_samp_factor = img->samp_v1;
701                 cinfo.comp_info[2].h_samp_factor = img->samp_h2;
702                 cinfo.comp_info[2].v_samp_factor = img->samp_v2;
703         }
704         jpeg_start_compress(&cinfo, TRUE);
705
706         unsigned dstride0 = (img->w0 + DCTSIZE-1) & ~(DCTSIZE-1);
707         unsigned dstride1 = (img->w1 + DCTSIZE-1) & ~(DCTSIZE-1);
708         unsigned dstride2 = (img->w2 + DCTSIZE-1) & ~(DCTSIZE-1);
709
710         int total_lines = 0;
711         int blocks = 0;
712         while (total_lines < cinfo.comp_info[0].height_in_blocks * DCTSIZE) {
713                 unsigned max_lines = cinfo.max_v_samp_factor * DCTSIZE;
714
715                 JSAMPROW y_row_ptrs[max_lines];
716                 JSAMPROW cb_row_ptrs[max_lines];
717                 JSAMPROW cr_row_ptrs[max_lines];
718                 JSAMPROW* ptrs[] = { y_row_ptrs, cb_row_ptrs, cr_row_ptrs };
719                 int i;
720
721                 for (i = 0; i < max_lines; ++i) {
722                         /* simple edge extension */
723                         int yline = i + blocks*DCTSIZE*cinfo.comp_info[0].v_samp_factor;
724                         if (yline > img->h0 - 1)
725                                 yline = img->h0 - 1;
726
727                         y_row_ptrs[i]  = img->data_y  + yline * dstride0;
728
729                         if (img->num_components == 3) {
730                                 int cbline = i + blocks*DCTSIZE*cinfo.comp_info[1].v_samp_factor;
731                                 if (cbline > img->h1 - 1)
732                                         cbline = img->h1 - 1;
733
734                                 int crline = i + blocks*DCTSIZE*cinfo.comp_info[2].v_samp_factor;
735                                 if (crline > img->h2 - 1)
736                                         crline = img->h2 - 1;
737
738                                 cb_row_ptrs[i] = img->data_cb + cbline * dstride1;
739                                 cr_row_ptrs[i] = img->data_cr + crline * dstride2;
740                         }
741                 }
742
743                 total_lines += max_lines;
744                 ++blocks;
745
746                 jpeg_write_raw_data(&cinfo, ptrs, max_lines);
747         }
748         jpeg_finish_compress(&cinfo);
749         jpeg_destroy_compress(&cinfo);
750
751         return 0;
752 }