]> git.sesse.net Git - qscale/blob - qscale.c
Move JPEG loading into libqscale.
[qscale] / qscale.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 <stdio.h>
20 #include <malloc.h>
21 #include <math.h>
22 #include <string.h>
23 #include <stdlib.h>
24 #include "jpeglib.h"
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 0
32
33 /* Whether to use SSE for vertical scaling or not (requires only SSE1). */
34 #define USE_VERTICAL_SSE 0
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 double sinc(double x)
46 {
47         static const double cutoff = 1.220703668e-4;  /* sqrt(sqrt(eps)) */
48
49         if (abs(x) < cutoff) {
50                 /* For small |x|, use Taylor series instead */
51                 const double x2 = x * x;
52                 const double x4 = x2 * x2;
53
54                 return 1.0 - x2 / 6.0 + x4 / 120.0;
55         } else {
56                 return sin(x) / x;
57         }
58 }
59
60 double lanczos_tap(double x)
61 {
62         if (x < -3.0 || x > 3.0)
63                 return 0.0;
64         if (x < 0.0)
65                 return sinc(-x*M_PI) * sinc(-x*M_PI / 3.0);
66         else
67                 return sinc(x*M_PI) * sinc(x*M_PI / 3.0);
68 }
69
70
71 struct pix_desc {
72         unsigned start, end;
73         unsigned startcoeff;
74 };
75
76 void hscale(float *pix, unsigned char *npix, unsigned w, unsigned h, unsigned nw, unsigned sstride, unsigned dstride)
77 {
78         struct pix_desc *pd = (struct pix_desc *)malloc(nw * sizeof(struct pix_desc));
79         int size_coeffs = 8;
80         float *coeffs = (float *)malloc(size_coeffs * sizeof(float));
81         int num_coeffs = 0;
82         int x, y;
83         double sf = (double)w / (double)nw;
84         double support = (w > nw) ? (3.0 * sf) : (3.0 / sf);
85
86         /* calculate the filter */
87         for (x = 0; x < nw; ++x) {
88                 int start = ceil(x * sf - support);
89                 int end = floor(x * sf + support);
90                 int sx;
91                 double sum = 0.0;
92
93                 if (start < 0) {
94                         start = 0;
95                 }
96                 if (end > w - 1) {
97                         end = w - 1;
98                 }
99
100 #if USE_HORIZONTAL_SSE
101                 /* round up so we get a multiple of four for the SSE code */
102                 int num = (end - start + 1);
103                 if (num % 4 != 0) {
104                         /* prefer aligning it if possible */
105                         if (start % 4 != 0 && start % 4 <= num % 4) {
106                                 num += start % 4;
107                                 start -= start % 4;
108                         }
109                         if (num % 4 != 0) {
110                                 end += 4 - (num % 4);
111                         }
112                 }
113 #endif
114
115                 pd[x].start = start;
116                 pd[x].end = end;
117                 pd[x].startcoeff = num_coeffs;
118
119                 for (sx = start; sx <= end; ++sx) {
120                         double nd = (w > nw) ? (sx/sf - x) : (sx - x*sf);
121                         double f = lanczos_tap(nd);
122                         if (num_coeffs == size_coeffs) {
123                                 size_coeffs <<= 1;
124                                 coeffs = (float *)realloc(coeffs, size_coeffs * sizeof(float));
125                         }
126
127                         coeffs[num_coeffs++] = f;
128                         sum += f;
129                 }
130
131                 for (sx = start; sx <= end; ++sx) {
132                         coeffs[pd[x].startcoeff + sx - start] /= sum;
133                 }
134         }
135
136         for (y = 0; y < h; ++y) {
137                 float *sptr = pix + y*sstride;
138                 unsigned char *dptr = npix + y*dstride;
139                 unsigned char ch;
140                 for (x = 0; x < nw; ++x) {
141 #if USE_HORIZONTAL_SSE
142                         int result;
143                         float acc;
144                         long tmp;
145                         static const float low = 0.0, high = 255.0;
146                         __asm__ (
147                                 "pxor %1, %1               \n"
148                                 "xor %2, %2                \n"
149                                 "0:                        \n"
150                                 "movups (%4,%2),%%xmm1     \n"
151                                 "movups (%3,%2),%%xmm2     \n"
152                                 "mulps %%xmm2,%%xmm1       \n"
153                                 "addps %%xmm1,%1           \n"
154                                 "add $16,%2                \n"
155                                 "dec %5                    \n"
156                                 "jnz 0b                    \n"
157                                 "haddps %1,%1              \n"
158                                 "haddps %1,%1              \n"
159                                 "maxss %6,%1               \n"
160                                 "minss %7,%1               \n"
161                                 "cvtss2si %1,%0            \n"
162                                 : "=r" (result),
163                                   "=&x" (acc),
164                                   "=&r" (tmp)
165                                 : "r" (&coeffs[pd[x].startcoeff]),
166                                   "r" (&sptr[pd[x].start]),
167                                   "r" ((pd[x].end - pd[x].start + 1)/4),
168                                   "m" (low),
169                                   "m" (high)
170                                 : "memory", "xmm1", "xmm2"
171                         );
172
173                         *dptr++ = (unsigned char)result;
174 #else
175                         float acc = 0.0;
176                         float *cf = &coeffs[pd[x].startcoeff];
177                         unsigned sx;
178                         
179                         for (sx = pd[x].start; sx <= pd[x].end; ++sx) {
180                                 acc += sptr[sx] * *cf++;
181                         }
182
183                         if (acc < 0.0)
184                                 ch = 0;
185                         else if (acc > 255.0)
186                                 ch = 255;
187                         else
188                                 ch = (unsigned char)acc;
189                         *dptr++ = ch;
190 #endif
191                 }
192                 ch = dptr[-1];
193                 for ( ; x < dstride; ++x) {
194                         *dptr++ = ch;
195                 }
196         }
197 }
198
199 void vscale(unsigned char *pix, float *npix, unsigned w, unsigned h, unsigned nh, unsigned dstride)
200 {
201         struct pix_desc *pd = (struct pix_desc *)malloc(nh * sizeof(struct pix_desc));
202         int size_coeffs = 8;
203         float *coeffs = (float *)malloc(size_coeffs * sizeof(float));
204         int num_coeffs = 0;
205         int x, y, sy;
206         double sf = (double)h / (double)nh;
207         double support = (h > nh) ? (3.0 * sf) : (3.0 / sf);
208
209         /* calculate the filter */
210         for (y = 0; y < nh; ++y) {
211                 int start = ceil(y * sf - support);
212                 int end = floor(y * sf + support);
213                 double sum = 0.0;
214
215                 if (start < 0) {
216                         start = 0;
217                 }
218                 if (end > h - 1) {
219                         end = h - 1;
220                 }
221
222                 pd[y].start = start;
223                 pd[y].end = end;
224                 pd[y].startcoeff = num_coeffs;
225
226                 for (sy = start; sy <= end; ++sy) {
227                         double nd = (h > nh) ? (sy/sf - y) : (sy - y*sf);
228                         double f = lanczos_tap(nd);
229                         if (num_coeffs == size_coeffs) {
230                                 size_coeffs <<= 1;
231                                 coeffs = (float *)realloc(coeffs, size_coeffs * sizeof(float));
232                         }
233                         
234                         coeffs[num_coeffs++] = f;
235                         sum += f;
236                 }
237
238                 for (sy = start; sy <= end; ++sy) {
239                         coeffs[pd[y].startcoeff + sy - start] /= sum;
240                 }
241         }
242
243 #if CACHE_LINE_FACTOR > 1
244         for (x = 0; x < (w/CACHE_LINE_FACTOR) * CACHE_LINE_FACTOR; x += CACHE_LINE_FACTOR) {
245                 unsigned char *sptr = pix + x;
246                 float *dptr = npix + x;
247                 for (y = 0; y < nh; ++y) {
248 #if USE_VERTICAL_SSE
249                         /*
250                          * xmm0 - xmm3: acc[0..15]
251                          * xmm4: current filter coefficient
252                          * xmm5, xmm6, xmm7: scratchpad
253                          */
254                         __asm__ (
255                                 /* clear */
256                                 "pxor %%xmm0, %%xmm0          \n"
257                                 "pxor %%xmm1, %%xmm1          \n"
258                                 "pxor %%xmm2, %%xmm2          \n"
259                                 "pxor %%xmm3, %%xmm3          \n"
260
261                                 /* main loop */
262                                 "0:                           \n"
263                                 
264                                 /* a zero is useful during unpacking */
265                                 "pxor %%xmm4, %%xmm4          \n"
266                                 
267                                 /* fetch all 16 source bytes */
268                                 "movups (%0), %%xmm5          \n"
269                                 "prefetcht0 (%0,%3,4)         \n"
270
271                                 /* unpack into words (xmm5, xmm7) */
272                                 "movaps %%xmm5, %%xmm7        \n"
273                                 "punpcklbw %%xmm4, %%xmm5     \n"
274                                 "punpckhbw %%xmm4, %%xmm7     \n"
275
276                                 /* unpack xmm5 into dwords (xmm5, xmm6) */
277                                 "movaps %%xmm5, %%xmm6        \n"
278                                 "punpcklwd %%xmm4, %%xmm5     \n"
279                                 "punpckhwd %%xmm4, %%xmm6     \n"
280
281                                 /* convert xmm5, xmm6 to floats */
282                                 "cvtdq2ps %%xmm5, %%xmm5      \n"
283                                 "cvtdq2ps %%xmm6, %%xmm6      \n"
284
285                                 /* fetch the coefficient */
286                                 "movss (%2), %%xmm4           \n"
287                                 "shufps $0x0, %%xmm4, %%xmm4  \n"
288
289                                 /* do the muls for xmm5 and xmm6 */
290                                 "mulps %%xmm4, %%xmm5         \n"
291                                 "mulps %%xmm4, %%xmm6         \n"
292                                 "addps %%xmm5, %%xmm0         \n"
293                                 "addps %%xmm6, %%xmm1         \n"
294
295                                 /* get the zero back again */
296                                 "pxor %%xmm4, %%xmm4          \n"
297
298                                 /* unpack xmm7 into dwords (xmm7, xmm6) */
299                                 "movaps %%xmm7, %%xmm6        \n"
300                                 "punpcklwd %%xmm4, %%xmm7     \n"
301                                 "punpckhwd %%xmm4, %%xmm6     \n"
302
303                                 /* convert xmm7, xmm6 to floats */
304                                 "cvtdq2ps %%xmm7, %%xmm7      \n"
305                                 "cvtdq2ps %%xmm6, %%xmm6      \n"
306
307                                 /* fetch the coefficient */
308                                 "movss (%2), %%xmm4           \n"
309                                 "shufps $0x0, %%xmm4, %%xmm4  \n"
310
311                                 /* do the second set of muls */
312                                 "mulps %%xmm4, %%xmm7         \n"
313                                 "mulps %%xmm4, %%xmm6         \n"
314                                 "addps %%xmm7, %%xmm2         \n"
315                                 "addps %%xmm6, %%xmm3         \n"
316
317                                 /* move along, and loop */
318                                 "add $4, %2                   \n"
319                                 "add %3, %0                   \n"
320                                 "dec %1                       \n"
321                                 "jnz 0b                       \n"
322
323                                 /* store the values */
324                                 "movaps %%xmm0, (%4)          \n"
325                                 "movaps %%xmm1, 16(%4)        \n"
326                                 "movaps %%xmm2, 32(%4)        \n"
327                                 "movaps %%xmm3, 48(%4)        \n"
328                                 : :
329                                 "r" (&sptr[pd[y].start * w]),        /* 0: srcptr base */
330                                 "r" (pd[y].end - pd[y].start + 1),   /* 1: filter len */
331                                 "r" (&coeffs[pd[y].startcoeff]),     /* 2: coeffs base */
332                                 "r" ((long)w),                       /* 3: stride */
333                                 "r" (dptr)                           /* 4: dstptr base */
334                                 : "memory", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7"
335                         );
336 #else
337                         int i;
338                         float acc[CACHE_LINE_FACTOR];
339                         for (i = 0; i < CACHE_LINE_FACTOR; ++i)
340                                 acc[i] = 0.0;
341                         float *cf = &coeffs[pd[y].startcoeff];
342                         unsigned sy;
343                 
344                         for (sy = pd[y].start; sy <= pd[y].end; ++sy) {
345                                 for (i = 0; i < CACHE_LINE_FACTOR; ++i) {
346                                         acc[i] += sptr[sy * w + i] * *cf;
347                                 }
348                                 ++cf;
349                         }
350
351                         for (i = 0; i < CACHE_LINE_FACTOR; ++i) {
352                                 dptr[i] = acc[i];
353                         }
354 #endif
355                         dptr += dstride;
356                 }
357         }
358         for (x = (x/CACHE_LINE_FACTOR)*CACHE_LINE_FACTOR; x < w; ++x) {
359 #else
360         for (x = 0; x < w; ++x) {
361 #endif
362                 unsigned char *sptr = pix + x;
363                 float *dptr = npix + x;
364                 for (y = 0; y < nh; ++y) {
365                         float acc = 0.0;
366                         float *cf = &coeffs[pd[y].startcoeff];
367                         unsigned sy;
368                         
369                         for (sy = pd[y].start; sy <= pd[y].end; ++sy) {
370                                 acc += sptr[sy * w] * *cf++;
371                         }
372
373                         *dptr = acc;
374                         dptr += dstride;
375                 }
376         }
377 }
378
379 int main(int argc, char **argv)
380 {
381         /* user-settable parameters */
382         unsigned nominal_w = atoi(argv[1]);
383         unsigned nominal_h = atoi(argv[2]);
384         unsigned samp_h0 = 2, samp_v0 = 2;
385         unsigned samp_h1 = 1, samp_v1 = 1;
386         unsigned samp_h2 = 1, samp_v2 = 1;
387         unsigned jpeg_quality = 85;
388         /* end */
389
390         unsigned max_samp_h, max_samp_v;
391         max_samp_h = samp_h0;
392         if (samp_h1 > max_samp_h)
393                 max_samp_h = samp_h1;
394         if (samp_h2 > max_samp_h)
395                 max_samp_h = samp_h2;
396         
397         max_samp_v = samp_v0;
398         if (samp_v1 > max_samp_v)
399                 max_samp_v = samp_v1;
400         if (samp_v2 > max_samp_v)
401                 max_samp_v = samp_v2;
402
403         unsigned nw0 = nominal_w * samp_h0 / max_samp_h, nh0 = nominal_h * samp_v0 / max_samp_v;
404         unsigned nw1 = nominal_w * samp_h1 / max_samp_h, nh1 = nominal_h * samp_v1 / max_samp_v;
405         unsigned nw2 = nominal_w * samp_h2 / max_samp_h, nh2 = nominal_h * samp_v2 / max_samp_v;
406
407         unsigned dstride0 = (nw0 + DCTSIZE-1) & ~(DCTSIZE-1);
408         unsigned dstride1 = (nw1 + DCTSIZE-1) & ~(DCTSIZE-1);
409         unsigned dstride2 = (nw2 + DCTSIZE-1) & ~(DCTSIZE-1);
410
411         qscale_img *img = qscale_load_jpeg_from_stdio(stdin);
412         unsigned sstride0 = (img->w0 + DCTSIZE-1) & ~(DCTSIZE-1);
413         unsigned sstride1 = (img->w1 + DCTSIZE-1) & ~(DCTSIZE-1);
414         unsigned sstride2 = (img->w2 + DCTSIZE-1) & ~(DCTSIZE-1);
415         
416         JSAMPLE *data_ny, *data_ncb, *data_ncr;
417
418         {
419                 float *npix = (float*)memalign(16, sstride0 * nh0 * sizeof(float));
420                 vscale(img->data_y, npix, sstride0, img->h0, nh0, sstride0);
421                 data_ny = (unsigned char *)malloc(nh0 * dstride0);
422                 hscale(npix, data_ny, img->w0, nh0, nw0, sstride0, dstride0);
423                 free(npix);
424         }
425         {
426                 float *npix = (float*)memalign(16, sstride1 * nh1 * sizeof(float));     
427                 vscale(img->data_cr, npix, sstride1, img->h1, nh1, sstride1);
428                 data_ncr = (unsigned char *)malloc(nh1 * dstride1);
429                 hscale(npix, data_ncr, img->w1, nh1, nw1, sstride1, dstride1);
430                 free(npix);
431         }
432         {
433                 float *npix = (float*)memalign(16, sstride2 * nh2 * sizeof(float));     
434                 vscale(img->data_cb, npix, sstride2, img->h2, nh2, sstride2);
435                 data_ncb = (unsigned char *)malloc(nh2 * dstride2);
436                 hscale(npix, data_ncb, img->w2, nh2, nw2, sstride2, dstride2);
437                 free(npix);
438         }
439         
440         struct jpeg_compress_struct cinfo;
441         struct jpeg_error_mgr jerr;
442         cinfo.err = jpeg_std_error(&jerr);
443         jpeg_create_compress(&cinfo);
444         jpeg_stdio_dest(&cinfo, stdout);
445         cinfo.input_components = 3;
446         jpeg_set_defaults(&cinfo);
447         jpeg_set_quality(&cinfo, jpeg_quality, FALSE);
448         cinfo.image_width = nominal_w;
449         cinfo.image_height = nominal_h;
450         cinfo.raw_data_in = TRUE;
451         jpeg_set_colorspace(&cinfo, JCS_YCbCr);
452         cinfo.comp_info[0].h_samp_factor = samp_h0;
453         cinfo.comp_info[0].v_samp_factor = samp_v0;
454         cinfo.comp_info[1].h_samp_factor = samp_h1;
455         cinfo.comp_info[1].v_samp_factor = samp_v1;
456         cinfo.comp_info[2].h_samp_factor = samp_h2;
457         cinfo.comp_info[2].v_samp_factor = samp_v2;
458         jpeg_start_compress(&cinfo, TRUE);
459
460         int total_lines = 0;
461         int blocks = 0;
462         while (total_lines < cinfo.comp_info[0].height_in_blocks * DCTSIZE) {
463                 unsigned max_lines = cinfo.max_v_samp_factor * DCTSIZE;
464
465                 JSAMPROW y_row_ptrs[max_lines];
466                 JSAMPROW cb_row_ptrs[max_lines];
467                 JSAMPROW cr_row_ptrs[max_lines];
468                 JSAMPROW* ptrs[] = { y_row_ptrs, cb_row_ptrs, cr_row_ptrs };
469                 int i;
470
471                 for (i = 0; i < max_lines; ++i) {
472                         /* simple edge extension */
473                         int yline = i + blocks*DCTSIZE*cinfo.comp_info[0].v_samp_factor;
474                         if (yline > nh0 - 1)
475                                 yline = nh0 - 1;
476
477                         int cbline = i + blocks*DCTSIZE*cinfo.comp_info[1].v_samp_factor;
478                         if (cbline > nh1 - 1)
479                                 cbline = nh1 - 1;
480
481                         int crline = i + blocks*DCTSIZE*cinfo.comp_info[2].v_samp_factor;
482                         if (crline > nh2 - 1)
483                                 crline = nh2 - 1;
484
485                         y_row_ptrs[i]  = data_ny  + yline * dstride0;
486                         cb_row_ptrs[i] = data_ncb + cbline * dstride1;
487                         cr_row_ptrs[i] = data_ncr + crline * dstride2;
488                 }
489                 
490                 total_lines += max_lines;
491                 ++blocks;
492
493                 jpeg_write_raw_data(&cinfo, ptrs, max_lines);
494         }
495         jpeg_finish_compress(&cinfo);
496         jpeg_destroy_compress(&cinfo);
497
498         qscale_destroy(img);
499
500         return 0;
501 }
502