Debian Codegraph @

converter/other/fiasco/codec/coder.c

raw
1 /*
2 * coder.c: WFA coder toplevel functions
3 *
4 * Written by: Ullrich Hafner
5 *
6 * This file is part of FIASCO (Fractal Image And Sequence COdec)
7 * Copyright (C) 1994-2000 Ullrich Hafner
8 */
9
10 /*
11 * $Date: 2000/06/14 20:50:51 $
12 * $Author: hafner $
13 * $Revision: 5.1 $
14 * $State: Exp $
15 */
16
17 #define _DEFAULT_SOURCE 1 /* New name for SVID & BSD source defines */
18 #define _BSD_SOURCE 1 /* Make sure strdup() is in string.h */
19 #define _XOPEN_SOURCE 500 /* Make sure strdup() is in string.h */
20
21 #include <stdbool.h>
22 #include <math.h>
23 #include <ctype.h>
24
25 #include <string.h>
26
27 #include "config.h"
28 #include "pm_c_util.h"
29 #include "pnm.h"
30 #include "nstring.h"
31
32 #include "types.h"
33 #include "macros.h"
34 #include "error.h"
35
36 #include "fiasco.h"
37
38 #include "cwfa.h"
39 #include "misc.h"
40 #include "control.h"
41 #include "bintree.h"
42 #include "subdivide.h"
43 #include "read.h"
44 #include "write.h"
45 #include "image.h"
46 #include "mwfa.h"
47 #include "list.h"
48 #include "decoder.h"
49 #include "motion.h"
50 #include "wfalib.h"
51 #include "domain-pool.h"
52 #include "coeff.h"
53 #include "coder.h"
54 #include "rpf.h"
55
56 /*****************************************************************************
57
58 global variables
59
60 *****************************************************************************/
61
62 const real_t MAXCOSTS = 1e20;
63
64 /*****************************************************************************
65
66 private code
67
68 *****************************************************************************/
69
70 static const char *
71 getInputImageName(char const * const * templateP,
72 unsigned int const ithImage) {
73 /*
74 * Construct the i-th image-name using templates.
75 * If the template contains a '[' it must be of the form
76 * "prefix[start-end{+,-}step]suffix"
77 * where "{+,-}step" is optional.
78 * Leading zeros of "start" are significant.
79 *
80 * Example:
81 * "image0[12-01-1].pgm" yields image012.pgm, image011.pgm, ..., image001.pgm
82 *
83 * Return value:
84 * name of image 'ith_image' or NULL if ith_image is out of range.
85 */
86
87 unsigned int ithImageModified;
88
89 ithImageModified = ithImage;
90
91 while (*templateP)
92 {
93 const char *template = *templateP++;
94 char *s;
95
96 if (!(s = strchr (template, '['))) /* no template, just a filename */
97 {
98 if (ithImageModified == 0)
99 return pm_strdup(template);
100 else
101 --ithImageModified;
102 }
103 else /* template parser */
104 {
105 unsigned n_digits; /* # of digits in image name no. */
106 char *s2;
107 char *suffix; /* characters after template end */
108 char prefix [MAXSTRLEN]; /* chars up to the template start */
109 unsigned first; /* first image number */
110 unsigned last; /* last image number */
111 int image_num; /* current image number */
112 int increment = 1;
113 int dummy;
114
115 strcpy (prefix, template);
116 prefix [s - template] = '\0';
117
118 for (s2 = ++s, n_digits = 0; ISDIGIT (*s2); s2++, n_digits++)
119 ;
120 if (sscanf (s, "%d", &dummy) == 0 || dummy < 0)
121 error ("Input name template conversion failure.\n"
122 "Check spelling of template.");
123 first = (unsigned) dummy;
124
125 if (*s2++ != '-')
126 error ("Input name template conversion failure.\n"
127 "Check spelling of template.");
128
129 for (s = s2; ISDIGIT (*s2); s2++)
130 ;
131 if (sscanf (s, "%d", &dummy) == 0 || dummy < 0)
132 error ("Input name template conversion failure.\n"
133 "Check spelling of template.");
134 last = (unsigned) dummy;
135
136 if (*s2 == '+' || *s2 == '-')
137 {
138 for (s = s2++; ISDIGIT (*s2); s2++)
139 ;
140 if (sscanf (s, "%d", &increment) == 0)
141 error ("Input name template conversion failure.\n"
142 "Check spelling of template.");
143 }
144 if (*s2 != ']')
145 error ("Input name template conversion failure.\n"
146 "Check spelling of template.");
147 suffix = s2 + 1;
148
149 image_num = first + increment * ithImageModified;
150 if (image_num < 0)
151 error ("Input name template conversion failure.\n"
152 "Check spelling of template.");
153
154 if ((increment > 0 && (unsigned) image_num > last) ||
155 (increment <= 0 && (unsigned) image_num < last))
156 {
157 /* TODO: check this */
158 ithImageModified -= (last - first) / increment + 1;
159 }
160 else
161 {
162 char formatstr [MAXSTRLEN];
163 /* format string for image filename */
164 char image_name [MAXSTRLEN];
165 /* image file name to be composed */
166
167 strcpy (formatstr, "%s%0?d%s");
168 formatstr [4] = '0' + (char) n_digits;
169 sprintf (image_name, formatstr, prefix, image_num, suffix);
170 return pm_strdup(image_name);
171 }
172 }
173 }
174 return NULL;
175 }
176
177
178
179 static void
180 setInputImageInfo(const char * const * const inputName,
181 unsigned int const stdinWidth,
182 unsigned int const stdinHeight,
183 xelval const stdinMaxval,
184 int const stdinFormat,
185 wfa_info_t * const wiP,
186 const char ** const errorP) {
187 /*----------------------------------------------------------------------------
188 Construct the parts of *wiP that describe the input images.
189
190 'inputName' is an array listing the input file names, or "-" for
191 Standard Input.
192
193 'stdinWidth' etc. are the values from the input image on Standard Input,
194 _if_ one of the input images is from Standard Input. If all input images
195 are in named files, 'stdinWidth' etc. are meaningless.
196
197 As a side effect, we read all input files through the header except
198 for Standard Input, which we leave alone. We may do this even if we
199 fail.
200 -----------------------------------------------------------------------------*/
201 const char * fileName;
202 int width, w = 0, height, h = 0;
203 bool_t color, c = NO;
204 unsigned i;
205
206 for (i = 0, *errorP = NULL;
207 (fileName = getInputImageName(inputName, i)) && !*errorP;
208 ++i) {
209
210 xelval maxval;
211 int format;
212
213 if (streq(fileName, "-")) {
214 width = stdinWidth;
215 height = stdinHeight;
216 maxval = stdinMaxval;
217 format = stdinFormat;
218 } else {
219 FILE * ifP;
220
221 ifP = pm_openr(fileName);
222
223 pnm_readpnminit(ifP, &width, &height, &maxval, &format);
224
225 pm_close(ifP);
226 }
227 color = (PNM_FORMAT_TYPE(format) == PPM_FORMAT);
228
229 if (i > 0) {
230 if (w != width || h != height || c != color) {
231 pm_asprintf(errorP,
232 "Dimensions and format of image frame '%s' "
233 "does not match the others",
234 streq(fileName, "-") ? "<stdin>" : fileName);
235 }
236 } else {
237 w = width;
238 h = height;
239 c = color;
240 }
241 pm_strfree(fileName);
242 }
243 wiP->frames = i;
244 wiP->width = w;
245 wiP->height = h;
246 wiP->color = c;
247 }
248
249
250
251 static void
252 setMinMaxLevel(unsigned int const reqMinLevel,
253 unsigned int const reqMaxLevel,
254 unsigned int const level,
255 unsigned int const tilingExponent,
256 unsigned int * const lcMinLevelP,
257 unsigned int * const lcMaxLevelP) {
258
259 unsigned int const clippedReqMin = MAX(reqMinLevel, 3);
260 unsigned int const clippedReqMax = MIN(reqMaxLevel, level - 1);
261
262 unsigned int tilingLimitedMax;
263
264
265 assert(level > 0);
266
267 if (tilingExponent > level)
268 tilingLimitedMax = 0;
269 else {
270 tilingLimitedMax = MIN(level - tilingExponent, clippedReqMax);
271 if (tilingLimitedMax < clippedReqMax)
272 message("'max_level' reduced from %u to %u "
273 "because of image tiling level.",
274 clippedReqMax, tilingLimitedMax);
275 else
276 tilingLimitedMax = clippedReqMax;
277 }
278
279 *lcMaxLevelP = tilingLimitedMax;
280 *lcMinLevelP = MIN(*lcMaxLevelP, clippedReqMin);
281
282 assert(*lcMaxLevelP >= *lcMinLevelP);
283 assert(*lcMaxLevelP <= level - tilingExponent);
284 assert(*lcMaxLevelP < level);
285 }
286
287
288
289 static void
290 setOptions(c_options_t const reqOptions,
291 unsigned int const level,
292 unsigned int const tilingExponent,
293 c_options_t * const optionsP) {
294
295 /* Most options are just what caller requested ('reqOptions'), so we just
296 use that as an initial value, then re-set the members that are more
297 complex.
298 */
299
300 *optionsP = reqOptions; /* initial value */
301
302 setMinMaxLevel(reqOptions.lc_min_level,
303 reqOptions.lc_max_level,
304 level,
305 tilingExponent,
306 &optionsP->lc_min_level,
307 &optionsP->lc_max_level);
308
309 optionsP->images_level =
310 optionsP->lc_max_level > 1 ?
311 MIN(reqOptions.images_level,
312 optionsP->lc_max_level - 1) :
313 0;
314
315 /* On 25.04.09, the code here set optionsP->image_level to one less than
316 optionsP->lc_max_level even if the latter was zero. I don't know if
317 level zero makes any sense, but it definitely makes more sense than
318 minus 1, so I changed it to make optionsP->image_level zero in that
319 case. BJH
320 */
321 }
322
323
324
325 static void
326 setLevelStuff(const c_options_t * const optionsP,
327 coding_t * const cP,
328 wfa_info_t * const wiP) {
329
330 {
331 unsigned int const lx = (unsigned) (log2(wiP->width - 1) + 1);
332 unsigned int const ly = (unsigned) (log2(wiP->height - 1) + 1);
333
334 wiP->level = MAX(lx, ly) * 2 - ((ly == lx + 1) ? 1 : 0);
335 assert(wiP->level > 0);
336 }
337
338 cP->tiling = new_tiling(optionsP->tiling_method,
339 optionsP->tiling_exponent, wiP->level,
340 wiP->frames > 1);
341
342 setOptions(*optionsP, wiP->level, cP->tiling->exponent, &cP->options);
343
344 /*
345 * p_min_level, p_max_level min and max level for ND/MC prediction
346 * [p_min_level, p_max_level] must be a subset of [min_level, max_level] !
347 */
348 wiP->p_min_level = MAX(optionsP->p_min_level, cP->options.lc_min_level);
349 wiP->p_max_level = MIN(optionsP->p_max_level, cP->options.lc_max_level);
350 if (wiP->p_min_level > wiP->p_max_level)
351 wiP->p_min_level = wiP->p_max_level;
352
353 cP->products_level =
354 MAX(0, ((signed int) cP->options.lc_max_level
355 - (signed int) cP->options.images_level - 1));
356 cP->pixels = Calloc(size_of_level (cP->options.lc_max_level),
357 sizeof (real_t));
358 cP->images_of_state = Calloc(MAXSTATES, sizeof (real_t *));
359 cP->ip_images_state = Calloc(MAXSTATES, sizeof (real_t *));
360 cP->ip_states_state = Calloc(MAXSTATES * MAXLEVEL, sizeof (real_t *));
361
362 debug_message("Imageslevel :%d, Productslevel :%d",
363 cP->options.images_level, cP->products_level);
364 debug_message("Memory : (%d + %d + %d * 'states') * 'states' + %d",
365 size_of_tree (cP->options.images_level) * 4,
366 size_of_tree (cP->products_level) * 4,
367 (cP->options.lc_max_level - cP->options.images_level),
368 size_of_level (cP->options.lc_max_level));
369 }
370
371
372
373 static coding_t *
374 allocCoder(const char * const * const inputName,
375 const c_options_t * const optionsP,
376 wfa_info_t * const wiP,
377 unsigned int const stdinWidth,
378 unsigned int const stdinHeight,
379 xelval const stdinMaxval,
380 int const stdinFormat) {
381 /*----------------------------------------------------------------------------
382 Construct FIASCO coder object: Allocate memory for the object and set
383 default values specified by 'options'.
384
385 Return pointer to newly malloc'ed object.
386
387 'inputName' is an array of names of input files, or "-" for Standard Input.
388
389 'stdinWidth' etc. are the values from the input image on Standard Input,
390 _if_ one of the input images is from Standard Input. If all input images
391 are in named files, 'stdinWidth' etc. are meaningless.
392
393 As a side effect, we read all input files through the header except
394 for Standard Input, which we leave alone.
395 -----------------------------------------------------------------------------*/
396 coding_t * const cP = Calloc (1, sizeof (coding_t));;
397
398 const char * error;
399
400 setInputImageInfo(inputName,
401 stdinWidth, stdinHeight, stdinMaxval, stdinFormat,
402 wiP, &error);
403
404 if (error) {
405 set_error(_("Problem with input images: %s\n"), error);
406 pm_strfree(error);
407 return 0;
408 }
409
410 setLevelStuff(optionsP, cP, wiP);
411
412 /*
413 * Domain pools ...
414 */
415 cP->domain_pool = NULL;
416 cP->d_domain_pool = NULL;
417
418 /*
419 * Coefficients model ...
420 */
421 cP->coeff = NULL;
422 cP->d_coeff = NULL;
423
424 /*
425 * Max. number of states and edges
426 */
427 wiP->max_states = MAX(MIN(optionsP->max_states, MAXSTATES), 1);
428 cP->options.max_elements = MAX(MIN(optionsP->max_elements, MAXEDGES), 1);
429
430 /*
431 * Title and comment strings
432 */
433 wiP->title = strdup (optionsP->title);
434 wiP->comment = strdup (optionsP->comment);
435
436 /*
437 * Reduced precision format
438 */
439 wiP->rpf
440 = alloc_rpf (optionsP->rpf_mantissa, optionsP->rpf_range);
441 wiP->dc_rpf
442 = alloc_rpf (optionsP->dc_rpf_mantissa, optionsP->dc_rpf_range);
443 wiP->d_rpf
444 = alloc_rpf (optionsP->d_rpf_mantissa, optionsP->d_rpf_range);
445 wiP->d_dc_rpf
446 = alloc_rpf (optionsP->d_dc_rpf_mantissa, optionsP->d_dc_rpf_range);
447
448 /*
449 * Color image options ...
450 */
451 wiP->chroma_max_states = MAX(1, optionsP->chroma_max_states);
452
453 /*
454 * Set up motion compensation struct.
455 * p_min_level, p_max_level are also used for ND prediction
456 */
457 wiP->search_range = optionsP->search_range;
458 wiP->fps = optionsP->fps;
459 wiP->half_pixel = optionsP->half_pixel_prediction;
460 wiP->cross_B_search = optionsP->half_pixel_prediction;
461 wiP->B_as_past_ref = optionsP->B_as_past_ref;
462 wiP->smoothing = optionsP->smoothing;
463
464 cP->mt = alloc_motion (wiP);
465
466 return cP;
467 }
468
469
470
471 static void
472 freeCoder(coding_t *c) {
473 /*
474 * Coder struct destructor:
475 * Free memory of 'coder' struct.
476 *
477 * No return value.
478 *
479 * Side effects:
480 * structure 'coder' is discarded.
481 */
482 free_tiling (c->tiling);
483 free_motion (c->mt);
484
485 Free (c->pixels);
486 Free (c->images_of_state);
487 Free (c->ip_images_state);
488 Free (c->ip_states_state);
489 Free (c);
490 }
491
492
493
494
495 static frame_type_e
496 typeFmPattern(unsigned int const frame,
497 const char * const pattern) {
498
499 int tmp = TOUPPER (pattern [frame % strlen (pattern)]);
500 frame_type_e retval;
501
502 switch (tmp)
503 {
504 case 'I':
505 retval = I_FRAME;
506 break;
507 case 'B':
508 retval = B_FRAME;
509 break;
510 case 'P':
511 retval = P_FRAME;
512 break;
513 default:
514 error ("Frame type %c not valid. Choose one of I,B or P.", tmp);
515 }
516 return retval;
517 }
518
519
520
521 static void
522 printStatistics(char const c,
523 real_t const costs,
524 const wfa_t * const wfa,
525 const image_t * const image,
526 const range_t * const range) {
527
528 unsigned max_level, min_level, state, label, lincomb;
529
530 for (max_level = 0, min_level = MAXLEVEL, state = wfa->basis_states;
531 state < wfa->states; state++)
532 {
533 for (lincomb = 0, label = 0; label < MAXLABELS; label++)
534 lincomb += isrange(wfa->tree[state][label]) ? 1 : 0;
535
536 if (lincomb)
537 {
538 max_level = MAX(max_level,
539 (unsigned) (wfa->level_of_state [state] - 1));
540 min_level = MIN(min_level,
541 (unsigned) (wfa->level_of_state [state] - 1));
542 }
543 }
544 debug_message ("Image partitioning: maximum level %d , minimum level %d",
545 max_level, min_level);
546 debug_message ("WFA contains %d states (%d basis states).",
547 wfa->states, wfa->basis_states);
548 debug_message ("Estimated error: %.2f (RMSE: %.2f, PSNR: %.2f dB).",
549 (double) range->err,
550 sqrt (range->err / image->width / image->height),
551 10 * log ( 255.0 * 255.0 /
552 (range->err / image->width / image->height))
553 / log (10.0));
554 debug_message ("Estimated filesize: %.0f bits (%.0f bytes).",
555 (double) (range->tree_bits + range->matrix_bits
556 + range->weights_bits
557 + range->mv_tree_bits + range->mv_coord_bits
558 + range->nd_tree_bits + range->nd_weights_bits),
559 (double) (range->tree_bits + range->matrix_bits
560 + range->weights_bits + range->mv_tree_bits
561 + range->mv_coord_bits + range->nd_tree_bits
562 + range->nd_weights_bits) / 8);
563 if (c)
564 debug_message ("(%cT: %.0f, %cM: %.0f, %cW: %.0f, %cMC: %.0f, "
565 "%cMV: %.0f, %cNT: %.0f, %cNW: %.0f.)",
566 c, (double) range->tree_bits,
567 c, (double) range->matrix_bits,
568 c, (double) range->weights_bits,
569 c, (double) range->mv_tree_bits,
570 c, (double) range->mv_coord_bits,
571 c, (double) range->nd_tree_bits,
572 c, (double) range->nd_weights_bits);
573 else
574 debug_message ("(T: %.0f, M: %.0f, W: %.0f, MC: %.0f, MV: %.0f, "
575 "NT: %.0f, NW: %.0f.)",
576 (double) range->tree_bits,
577 (double) range->matrix_bits,
578 (double) range->weights_bits,
579 (double) range->mv_tree_bits,
580 (double) range->mv_coord_bits,
581 (double) range->nd_tree_bits,
582 (double) range->nd_weights_bits);
583 debug_message ("Total costs : %.2f", (double) costs);
584 }
585
586
587
588 static void
589 frameCoder(wfa_t * const wfa,
590 coding_t * const c,
591 bitfile_t * const output) {
592 /*
593 *
594 * WFA Coding of next frame. All important coding parameters are
595 * stored in 'c'. The generated 'wfa' is written to stream 'output'
596 * immediately after coding.
597 *
598 * No return value.
599 */
600 unsigned state;
601 range_t range; /* first range == the entire image */
602 real_t costs; /* total costs (minimized quantity) */
603 unsigned bits; /* number of bits written on disk */
604 clock_t ptimer;
605
606 prg_timer (&ptimer, START);
607
608 bits = bits_processed (output);
609
610 init_tree_model (&c->tree);
611 init_tree_model (&c->p_tree);
612
613 c->domain_pool
614 = alloc_domain_pool (c->options.id_domain_pool,
615 wfa->wfainfo->max_states,
616 c->options.max_elements, wfa);
617 c->d_domain_pool
618 = alloc_domain_pool ((c->options.prediction
619 || c->mt->frame_type != I_FRAME)
620 ? c->options.id_d_domain_pool : "constant",
621 wfa->wfainfo->max_states,
622 c->options.max_elements, wfa);
623
624 c->coeff = alloc_coeff_model (c->options.id_rpf_model,
625 wfa->wfainfo->rpf,
626 wfa->wfainfo->dc_rpf,
627 c->options.lc_min_level,
628 c->options.lc_max_level);
629 c->d_coeff = alloc_coeff_model (c->options.id_d_rpf_model,
630 wfa->wfainfo->d_rpf,
631 wfa->wfainfo->d_dc_rpf,
632 c->options.lc_min_level,
633 c->options.lc_max_level);
634
635 if (!c->mt->original->color) /* grayscale image */
636 {
637 memset (&range, 0, sizeof (range_t));
638 range.level = wfa->wfainfo->level;
639
640 costs = subdivide (MAXCOSTS, GRAY, RANGE, &range, wfa, c,
641 c->options.prediction || c->mt->frame_type != I_FRAME,
642 NO);
643 if (c->options.progress_meter != FIASCO_PROGRESS_NONE)
644 message ("");
645
646 if (isrange (range.tree)) /* entire image is approx. by lc? */
647 error ("No root state generated!");
648 else
649 wfa->root_state = range.tree;
650
651 printStatistics('\0', costs, wfa, c->mt->original, &range);
652 }
653 else
654 {
655 int YCb_node = -1;
656 int tree [3]; /* 3 root states of each color comp. */
657 color_e band;
658
659 /*
660 * When compressing color images, the three color components (YCbCr)
661 * are copied into a large image:
662 * [ Y Cr ]
663 * [ Cb 0 ]
664 * I.e. the color components of an image are processed in a row.
665 * After all components are compressed, virtual states are generated
666 * to describe the large image.
667 */
668 for (band = first_band (YES); band <= last_band (YES) ; band++)
669 {
670 debug_message ("Encoding color component %d", band);
671 tree [band] = RANGE;
672 if (band == Cb)
673 {
674 unsigned min_level;
675
676 c->domain_pool->chroma (wfa->wfainfo->chroma_max_states, wfa,
677 c->domain_pool->model);
678 /*
679 * Don't use a finer partitioning for the chrominancy bands
680 * than for the luminancy band.
681 */
682 for (min_level = MAXLEVEL, state = wfa->basis_states;
683 state < wfa->states; state++)
684 {
685 unsigned lincomb, label;
686
687 for (lincomb = 0, label = 0; label < MAXLABELS; label++)
688 lincomb += isrange (wfa->tree [state][label]) ? 1 : 0;
689 if (lincomb)
690 min_level = MIN(min_level,
691 (unsigned) (wfa->level_of_state [state]
692 - 1));
693 }
694 c->options.lc_min_level = min_level;
695 if (c->mt->frame_type != I_FRAME) /* subtract mc of luminance */
696 subtract_mc (c->mt->original, c->mt->past, c->mt->future,
697 wfa);
698 }
699
700 memset (&range, 0, sizeof (range_t));
701 range.level = wfa->wfainfo->level;
702
703 costs = subdivide (MAXCOSTS, band, tree [Y], &range, wfa, c,
704 c->mt->frame_type != I_FRAME && band == Y, NO);
705 if (c->options.progress_meter != FIASCO_PROGRESS_NONE)
706 message ("");
707 {
708 char colors [] = {'Y', 'B', 'R'};
709
710 printStatistics(colors [band], costs, wfa,
711 c->mt->original, &range);
712 }
713
714 if (isrange (range.tree)) /* whole image is approx. by a l.c. */
715 error ("No root state generated for color component %d!", band);
716 else
717 tree[band] = range.tree;
718
719 if (band == Cb)
720 {
721 wfa->tree [wfa->states][0] = tree[Y];
722 wfa->tree [wfa->states][1] = tree[Cb];
723 YCb_node = wfa->states;
724 append_state (YES, compute_final_distribution(wfa->states, wfa),
725 wfa->wfainfo->level + 1, wfa, c);
726 }
727 }
728 /*
729 * generate two virtual states (*)
730 *
731 * *
732 * / \
733 * + *
734 * / \ /
735 * Y CbCr
736 */
737 wfa->tree [wfa->states][0] = tree[Cr];
738 wfa->tree [wfa->states][1] = RANGE;
739 append_state (YES, compute_final_distribution (wfa->states, wfa),
740 wfa->wfainfo->level + 1, wfa, c);
741 wfa->tree[wfa->states][0] = YCb_node;
742 wfa->tree[wfa->states][1] = wfa->states - 1;
743 append_state (YES, compute_final_distribution (wfa->states, wfa),
744 wfa->wfainfo->level + 2, wfa, c);
745
746 wfa->root_state = wfa->states - 1;
747 }
748
749 for (state = wfa->basis_states; state < MAXSTATES; state++)
750 {
751 unsigned level;
752
753 if (c->images_of_state [state])
754 {
755 Free (c->images_of_state [state]);
756 c->images_of_state [state] = NULL;
757 }
758 if (c->ip_images_state [state])
759 {
760 Free (c->ip_images_state [state]);
761 c->ip_images_state [state] = NULL;
762 }
763 for (level = c->options.images_level + 1;
764 level <= c->options.lc_max_level;
765 level++)
766 if (c->ip_states_state [state][level])
767 {
768 Free (c->ip_states_state [state][level]);
769 c->ip_states_state [state][level] = NULL;
770 }
771
772 }
773
774 locate_delta_images (wfa);
775 write_next_wfa (wfa, c, output);
776
777 bits = bits_processed (output) - bits;
778 debug_message ("Total number of bits written: %d (%d bytes, %5.3f bpp)",
779 bits, bits >> 3,
780 bits / (double) (c->mt->original->height
781 * c->mt->original->width));
782 debug_message ("Total encoding time (real): %d sec",
783 prg_timer (&ptimer, STOP) / 1000);
784
785 c->domain_pool->free (c->domain_pool);
786 c->d_domain_pool->free (c->d_domain_pool);
787
788 c->coeff->free (c->coeff);
789 c->d_coeff->free (c->d_coeff);
790 }
791
792
793
794 static void
795 videoCoder(char const * const * const image_template,
796 bitfile_t * const output,
797 wfa_t * const wfa,
798 coding_t * const c,
799 unsigned int const stdinwidth,
800 unsigned int const stdinheight,
801 unsigned int const stdinmaxval,
802 unsigned int const stdinformat) {
803 /*
804 * Toplevel function to encode a sequence of video frames specified
805 * by 'image_template'. The output is written to stream 'output'.
806 * Coding options are given by 'c'.
807 *
808 * No return value.
809 */
810 unsigned display; /* picture number in display order */
811 int future_display; /* number of future reference */
812 int frame; /* current frame number */
813 const char *image_name;
814 /* image name of current frame. File name or "-" for Standard Input */
815 image_t *reconst = NULL; /* decoded reference image */
816 bool_t future_frame = NO; /* YES if last frame was in future */
817
818 debug_message ("Generating %d WFA's ...", wfa->wfainfo->frames);
819
820 future_display = -1;
821 frame = -1;
822 display = 0;
823
824 while ((image_name = getInputImageName(image_template, display)))
825 {
826 frame_type_e type; /* current frame type: I, B, P */
827
828 /*
829 * Determine type of next frame.
830 * Skip already coded frames (future reference!)
831 */
832 if (display == 0 && !c->options.reference_filename)
833 type = I_FRAME; /* Force first frame to be intra */
834 else
835 type = typeFmPattern(display, c->options.pattern);
836
837 if (type != I_FRAME && c->options.reference_filename)
838 /* Load reference from disk */
839 {
840 debug_message ("Reading reference frame `%s'.",
841 c->options.reference_filename);
842 reconst = read_image_file (c->options.reference_filename);
843 c->options.reference_filename = NULL;
844 }
845 if ((int) display == future_display)
846 {
847 /* Skip already coded future ref */
848 display++;
849 continue;
850 }
851 else if (type == B_FRAME && (int) display > future_display)
852 {
853 unsigned i = display;
854 /*
855 * Search for future reference
856 */
857 while (type == B_FRAME)
858 {
859 const char *name; /* image name of future frame */
860
861 i++;
862 name = getInputImageName(image_template, i);
863
864 if (!name) /* Force last valid frame to be 'P' */
865 {
866 future_display = i - 1;
867 type = P_FRAME;
868 }
869 else
870 {
871 future_display = i;
872 image_name = name;
873 type = typeFmPattern(i, c->options.pattern);
874 }
875 frame = future_display;
876 }
877 }
878 else
879 {
880 frame = display;
881 display++;
882 }
883
884 debug_message ("Coding \'%s\' [%c-frame].", image_name,
885 type == I_FRAME ? 'I' : (type == P_FRAME ? 'P' : 'B'));
886
887 /*
888 * Depending on current frame type update past and future frames
889 * which are needed as reference frames.
890 */
891 c->mt->frame_type = type;
892 if (type == I_FRAME)
893 {
894 if (c->mt->past) /* discard past frame */
895 free_image (c->mt->past);
896 c->mt->past = NULL;
897 if (c->mt->future) /* discard future frame */
898 free_image (c->mt->future);
899 c->mt->future = NULL;
900 if (reconst) /* discard current frame */
901 free_image (reconst);
902 reconst = NULL;
903 }
904 else if (type == P_FRAME)
905 {
906 if (c->mt->past) /* discard past frame */
907 free_image (c->mt->past);
908 c->mt->past = reconst; /* past frame <- current frame */
909 reconst = NULL;
910 if (c->mt->future) /* discard future frame */
911 free_image (c->mt->future);
912 c->mt->future = NULL;
913 }
914 else /* B_FRAME */
915 {
916 if (future_frame) /* last frame was future frame */
917 {
918 if (c->mt->future) /* discard future frame */
919 free_image (c->mt->future);
920 c->mt->future = reconst; /* future frame <- current frame */
921 reconst = NULL;
922 }
923 else
924 {
925 if (wfa->wfainfo->B_as_past_ref == YES)
926 {
927 if (c->mt->past) /* discard past frame */
928 free_image (c->mt->past);
929 c->mt->past = reconst; /* past frame <- current frame */
930 reconst = NULL;
931 }
932 else
933 {
934 if (reconst) /* discard current frame */
935 free_image (reconst);
936 reconst = NULL;
937 }
938 }
939 }
940
941 /*
942 * Start WFA coding of current frame
943 */
944 future_frame = frame == future_display;
945 c->mt->number = frame;
946
947 if (streq(image_name, "-"))
948 c->mt->original = read_image_stream(stdin,
949 stdinwidth, stdinheight,
950 stdinmaxval, stdinformat);
951 else
952 c->mt->original = read_image_file(image_name);
953
954 if (c->tiling->exponent && type == I_FRAME)
955 perform_tiling (c->mt->original, c->tiling);
956
957 frameCoder(wfa, c, output);
958
959 /*
960 * Regenerate image:
961 * 1. Compute approximation of WFA ranges (real image bintree order)
962 * 2. Generate byte image in rasterscan order
963 * 3. Apply motion compensation
964 */
965 reconst = decode_image (wfa->wfainfo->width, wfa->wfainfo->height,
966 FORMAT_4_4_4, NULL, wfa);
967
968 if (type != I_FRAME)
969 restore_mc (0, reconst, c->mt->past, c->mt->future, wfa);
970
971 if (c->mt->original)
972 free_image (c->mt->original);
973 c->mt->original = NULL;
974
975 remove_states (wfa->basis_states, wfa); /* Clear WFA structure */
976 }
977
978 if (reconst)
979 free_image (reconst);
980 if (c->mt->future)
981 free_image (c->mt->future);
982 if (c->mt->past)
983 free_image (c->mt->past);
984 if (c->mt->original)
985 free_image (c->mt->original);
986 }
987
988
989
990 static void
991 readStdinHeader(const char * const * const template,
992 unsigned int * const widthP,
993 unsigned int * const heightP,
994 xelval * const maxvalP,
995 int * const formatP) {
996 /*----------------------------------------------------------------------------
997 Read the PNM header from the Standard Input stream, if 'template' says
998 one of the images is to come from Standard Input.
999
1000 Return the contents of that stream as *widthP, etc.
1001 -----------------------------------------------------------------------------*/
1002 unsigned int i;
1003 bool endOfList;
1004 bool stdinFound;
1005
1006 for (i = 0, stdinFound = false, endOfList = false; !endOfList; ++i) {
1007 const char * const name = getInputImageName(template, i);
1008
1009 if (!name)
1010 endOfList = true;
1011 else {
1012 if (streq(name, "-"))
1013 stdinFound = true;
1014 }
1015 }
1016
1017 if (stdinFound) {
1018 int width, height;
1019
1020 pnm_readpnminit(stdin, &width, &height, maxvalP, formatP);
1021
1022 *widthP = width;
1023 *heightP = height;
1024 }
1025 }
1026
1027
1028
1029 /*****************************************************************************
1030
1031 public code
1032
1033 *****************************************************************************/
1034
1035 int
1036 fiasco_coder(char const * const * const inputname,
1037 const char * const outputname,
1038 float const quality,
1039 const fiasco_c_options_t * const options) {
1040 /*
1041 * FIASCO coder.
1042 * Encode image or video frames given by the array of filenames `inputname'
1043 * and write to the outputfile `outputname'.
1044 * If 'inputname' = NULL or
1045 * 'inputname [0]' == NULL or
1046 * 'inputname [0]' == "-", read standard input.
1047 * If 'outputname' == NULL or "-", write on standard output.
1048 * 'quality' defines the approximation quality and is 1 (worst) to 100 (best).
1049 *
1050 * Return value:
1051 * 1 on success
1052 * 0 otherwise
1053 */
1054 try
1055 {
1056 char const * const default_input [] = {"-", NULL};
1057 fiasco_c_options_t *default_options = NULL;
1058 const c_options_t *cop;
1059 char const * const *template;
1060 unsigned int stdinheight, stdinwidth;
1061 xelval stdinmaxval;
1062 int stdinformat;
1063
1064 /*
1065 * Check parameters
1066 */
1067 if (!inputname || !inputname [0] || streq (inputname [0], "-"))
1068 template = default_input;
1069 else
1070 template = inputname;
1071
1072 if (quality <= 0)
1073 {
1074 set_error (_("Compression quality has to be positive."));
1075 return 0;
1076 }
1077 else if (quality >= 100)
1078 {
1079 warning (_("Quality typically is 1 (worst) to 100 (best).\n"
1080 "Be prepared for a long running time."));
1081 }
1082
1083 if (options)
1084 {
1085 cop = cast_c_options ((fiasco_c_options_t *) options);
1086 if (!cop)
1087 return 0;
1088 }
1089 else
1090 {
1091 default_options = fiasco_c_options_new ();
1092 cop = cast_c_options (default_options);
1093 }
1094
1095 readStdinHeader(template, &stdinwidth, &stdinheight,
1096 &stdinmaxval, &stdinformat);
1097
1098 /*
1099 * Open output stream and initialize WFA
1100 */
1101 {
1102 bitfile_t *output = open_bitfile (outputname, "FIASCO_DATA",
1103 WRITE_ACCESS);
1104 if (!output)
1105 {
1106 set_error (_("Can't write outputfile `%s'.\n%s"),
1107 outputname ? outputname : "<stdout>",
1108 get_system_error ());
1109 if (default_options)
1110 fiasco_c_options_delete (default_options);
1111 return 0;
1112 }
1113 else
1114 {
1115 wfa_t *wfa = alloc_wfa (YES);
1116 coding_t *c = allocCoder(template, cop, wfa->wfainfo,
1117 stdinwidth, stdinheight,
1118 stdinmaxval, stdinformat);
1119
1120 read_basis (cop->basis_name, wfa);
1121 append_basis_states (wfa->basis_states, wfa, c);
1122
1123 c->price = 128 * 64 / quality;
1124
1125 videoCoder(template, output, wfa, c,
1126 stdinwidth, stdinheight, stdinmaxval,
1127 stdinformat);
1128
1129 close_bitfile (output);
1130 free_wfa (wfa);
1131 freeCoder(c);
1132
1133 if (default_options)
1134 fiasco_c_options_delete (default_options);
1135 }
1136 }
1137 return 1;
1138 }
1139 catch
1140 {
1141 return 0;
1142 }
1143 }
1144