add printing of seek points in verbose mode
[flac.git] / src / flac / encode.c
1 /* flac - Command-line FLAC encoder/decoder
2  * Copyright (C) 2000,2001  Josh Coalson
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
17  */
18
19 /*@@@ need to "_finish()" the verify decoder */
20
21 #include <assert.h>
22 #if defined _WIN32 && !defined __CYGWIN__
23 /* where MSVC puts unlink() */
24 # include <io.h>
25 #else
26 # include <unistd.h>
27 #endif
28 #include <stdio.h> /* for FILE et al. */
29 #include <stdlib.h> /* for malloc */
30 #include <string.h> /* for strcmp() */
31 #include "FLAC/all.h"
32 #include "encode.h"
33
34 #ifdef min
35 #undef min
36 #endif
37 #define min(x,y) ((x)<(y)?(x):(y))
38
39 #define CHUNK_OF_SAMPLES 2048
40
41 typedef enum {
42         FLAC__VERIFY_OK,
43         FLAC__VERIFY_FAILED_IN_FRAME,
44         FLAC__VERIFY_FAILED_IN_METADATA
45 } verify_code;
46
47 static const char *verify_code_string[] = {
48         "FLAC__VERIFY_OK",
49         "FLAC__VERIFY_FAILED_IN_FRAME",
50         "FLAC__VERIFY_FAILED_IN_METADATA"
51 };
52
53 typedef struct {
54         int32 *original[FLAC__MAX_CHANNELS];
55         unsigned size; /* of each original[] in samples */
56         unsigned tail; /* in wide samples */
57         const byte *encoded_signal;
58         unsigned encoded_signal_capacity;
59         unsigned encoded_bytes;
60         bool into_frames;
61         verify_code result;
62         FLAC__StreamDecoder *decoder;
63 } verify_fifo_struct;
64
65 typedef struct {
66         FILE *fout;
67         const char *outfile;
68         FLAC__Encoder *encoder;
69         bool verify;
70         bool verbose;
71         uint64 unencoded_size;
72         uint64 total_samples_to_encode;
73         uint64 bytes_written;
74         uint64 samples_written;
75         unsigned current_frame;
76         verify_fifo_struct verify_fifo;
77         FLAC__StreamMetaData_SeekTable seek_table;
78 } encoder_wrapper_struct;
79
80 static bool is_big_endian_host;
81
82 static unsigned char ucbuffer[CHUNK_OF_SAMPLES*FLAC__MAX_CHANNELS*((FLAC__MAX_BITS_PER_SAMPLE+7)/8)];
83 static signed char *scbuffer = (signed char *)ucbuffer;
84 static uint16 *usbuffer = (uint16 *)ucbuffer;
85 static int16 *ssbuffer = (int16 *)ucbuffer;
86
87 static int32 in[FLAC__MAX_CHANNELS][CHUNK_OF_SAMPLES];
88 static int32 *input[FLAC__MAX_CHANNELS];
89
90 /* local routines */
91 static bool init(encoder_wrapper_struct *encoder_wrapper);
92 static bool init_encoder(bool lax, bool do_mid_side, bool loose_mid_side, bool do_exhaustive_model_search, bool do_qlp_coeff_prec_search, unsigned rice_optimization_level, unsigned max_lpc_order, unsigned blocksize, unsigned qlp_coeff_precision, unsigned channels, unsigned bps, unsigned sample_rate, unsigned padding, char *requested_seek_points, int num_requested_seek_points, encoder_wrapper_struct *encoder_wrapper);
93 static bool convert_to_seek_table(char *requested_seek_points, int num_requested_seek_points, uint64 stream_samples, unsigned blocksize, FLAC__StreamMetaData_SeekTable *seek_table);
94 static void append_point_to_seek_table(FLAC__StreamMetaData_SeekTable *seek_table, uint64 sample, uint64 stream_samples, uint64 blocksize);
95 static int seekpoint_compare(const FLAC__StreamMetaData_SeekPoint *l, const FLAC__StreamMetaData_SeekPoint *r);
96 static void format_input(unsigned wide_samples, bool is_big_endian, bool is_unsigned_samples, unsigned channels, unsigned bps, encoder_wrapper_struct *encoder_wrapper);
97 static FLAC__EncoderWriteStatus write_callback(const FLAC__Encoder *encoder, const byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data);
98 static void metadata_callback(const FLAC__Encoder *encoder, const FLAC__StreamMetaData *metadata, void *client_data);
99 static FLAC__StreamDecoderReadStatus verify_read_callback(const FLAC__StreamDecoder *decoder, byte buffer[], unsigned *bytes, void *client_data);
100 static FLAC__StreamDecoderWriteStatus verify_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const int32 *buffer[], void *client_data);
101 static void verify_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data);
102 static void verify_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
103 static void print_stats(const encoder_wrapper_struct *encoder_wrapper);
104 static bool read_little_endian_uint16(FILE *f, uint16 *val, bool eof_ok);
105 static bool read_little_endian_uint32(FILE *f, uint32 *val, bool eof_ok);
106
107 int encode_wav(const char *infile, const char *outfile, bool verbose, uint64 skip, bool verify, bool lax, bool do_mid_side, bool loose_mid_side, bool do_exhaustive_model_search, bool do_qlp_coeff_prec_search, unsigned rice_optimization_level, unsigned max_lpc_order, unsigned blocksize, unsigned qlp_coeff_precision, unsigned padding, char *requested_seek_points, int num_requested_seek_points)
108 {
109         encoder_wrapper_struct encoder_wrapper;
110         FILE *fin;
111         bool is_unsigned_samples;
112         unsigned channels, bps, sample_rate, data_bytes;
113         size_t bytes_per_wide_sample, bytes_read;
114         uint16 x;
115         uint32 xx;
116
117         encoder_wrapper.encoder = 0;
118         encoder_wrapper.verify = verify;
119         encoder_wrapper.verbose = verbose;
120         encoder_wrapper.bytes_written = 0;
121         encoder_wrapper.samples_written = 0;
122         encoder_wrapper.outfile = outfile;
123
124         if(0 == strcmp(infile, "-")) {
125                 fin = stdin;
126         }
127         else {
128                 if(0 == (fin = fopen(infile, "rb"))) {
129                         fprintf(stderr, "ERROR: can't open input file %s\n", infile);
130                         return false;
131                 }
132         }
133         if(0 == strcmp(outfile, "-")) {
134                 encoder_wrapper.fout = stdout;
135         }
136         else {
137                 if(0 == (encoder_wrapper.fout = fopen(outfile, "wb"))) {
138                         fprintf(stderr, "ERROR: can't open output file %s\n", outfile);
139                         fclose(fin);
140                         return false;
141                 }
142         }
143
144         if(!init(&encoder_wrapper))
145                 goto wav_abort_;
146
147         /*
148          * check the RIFF chunk
149          */
150         if(!read_little_endian_uint32(fin, &xx, false))
151                 goto wav_abort_;
152         if(xx != 0x46464952) { /* "RIFF" */
153                 fprintf(stderr, "ERROR: no RIFF header\n");
154                 goto wav_abort_;
155         }
156         if(!read_little_endian_uint32(fin, &xx, false))
157                 goto wav_abort_;
158
159         /*
160          * now process the WAVE chunk
161          */
162         if(!read_little_endian_uint32(fin, &xx, true))
163                 goto wav_end_;
164         if(xx != 0x45564157) { /* "WAVE" */
165                 fprintf(stderr, "ERROR: no WAVE header\n");
166                 goto wav_abort_;
167         }
168
169         /* do the format sub-chunk */
170         if(!read_little_endian_uint32(fin, &xx, false))
171                 goto wav_abort_;
172         if(xx != 0x20746d66) { /* "fmt " */
173                 fprintf(stderr, "ERROR: no format sub-chunk\n");
174                 goto wav_abort_;
175         }
176         /* fmt chunk size */
177         if(!read_little_endian_uint32(fin, &xx, false))
178                 goto wav_abort_;
179         if(xx != 16) {
180                 fprintf(stderr, "ERROR: unsupported chunk\n");
181                 goto wav_abort_;
182         }
183         /* compression code */
184         if(!read_little_endian_uint16(fin, &x, false))
185                 goto wav_abort_;
186         if(x != 1) {
187                 fprintf(stderr, "ERROR: unsupported compression type %u\n", (unsigned)x);
188                 goto wav_abort_;
189         }
190         /* number of channels */
191         if(!read_little_endian_uint16(fin, &x, false))
192                 goto wav_abort_;
193         if(x == 0 || x > FLAC__MAX_CHANNELS) {
194                 fprintf(stderr, "ERROR: unsupported number channels %u\n", (unsigned)x);
195                 goto wav_abort_;
196         }
197         channels = x;
198         /* sample rate */
199         if(!read_little_endian_uint32(fin, &xx, false))
200                 goto wav_abort_;
201         if(xx == 0 || xx > FLAC__MAX_SAMPLE_RATE) {
202                 fprintf(stderr, "ERROR: unsupported sample rate %u\n", (unsigned)xx);
203                 goto wav_abort_;
204         }
205         sample_rate = xx;
206         /* avg bytes per second (ignored) */
207         if(!read_little_endian_uint32(fin, &xx, false))
208                 goto wav_abort_;
209         /* block align (ignored) */
210         if(!read_little_endian_uint16(fin, &x, false))
211                 goto wav_abort_;
212         /* bits per sample */
213         if(!read_little_endian_uint16(fin, &x, false))
214                 goto wav_abort_;
215         if(x != 8 && x != 16) {
216                 fprintf(stderr, "ERROR: unsupported bits per sample %u\n", (unsigned)x);
217                 goto wav_abort_;
218         }
219         bps = x;
220         is_unsigned_samples = (x == 8);
221
222         /* do the data sub-chunk */
223         if(!read_little_endian_uint32(fin, &xx, false))
224                 goto wav_abort_;
225         if(xx != 0x61746164) { /* "data" */
226                 fprintf(stderr, "ERROR: no data sub-chunk\n");
227                 goto wav_abort_;
228         }
229         /* data size */
230         if(!read_little_endian_uint32(fin, &xx, false))
231                 goto wav_abort_;
232         data_bytes = xx;
233
234         bytes_per_wide_sample = channels * (bps >> 3);
235
236         if(skip > 0) {
237                 if(fin != stdin) {
238                         if(-1 == fseek(fin, bytes_per_wide_sample * (unsigned)skip, SEEK_CUR)) {
239                                 fprintf(stderr, "ERROR seeking while skipping samples in input file %s\n", infile);
240                                 goto wav_abort_;
241                         }
242                 }
243                 else {
244                         int64 left;
245                         unsigned need;
246                         for(left = (int64)skip; left > 0; left -= CHUNK_OF_SAMPLES) {
247                                 need = min(left, CHUNK_OF_SAMPLES);
248                                 if(fread(ucbuffer, 1, bytes_per_wide_sample * need, fin) < need) {
249                                         fprintf(stderr, "ERROR seeking while skipping samples in input file %s\n", infile);
250                                         goto wav_abort_;
251                                 }
252                         }
253                 }
254         }
255
256         encoder_wrapper.total_samples_to_encode = data_bytes / bytes_per_wide_sample - skip;
257         encoder_wrapper.unencoded_size = encoder_wrapper.total_samples_to_encode * bytes_per_wide_sample + 44; /* 44 for the size of the WAV headers */
258
259         if(!init_encoder(lax, do_mid_side, loose_mid_side, do_exhaustive_model_search, do_qlp_coeff_prec_search, rice_optimization_level, max_lpc_order, blocksize, qlp_coeff_precision, channels, bps, sample_rate, padding, requested_seek_points, num_requested_seek_points, &encoder_wrapper))
260                 goto wav_abort_;
261
262         encoder_wrapper.verify_fifo.into_frames = true;
263
264         while(data_bytes > 0) {
265                 bytes_read = fread(ucbuffer, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample, fin);
266                 if(bytes_read == 0) {
267                         if(ferror(fin)) {
268                                 fprintf(stderr, "ERROR reading from %s\n", infile);
269                                 goto wav_abort_;
270                         }
271                         else if(feof(fin))
272                                 break;
273                 }
274                 else {
275                         if(bytes_read > data_bytes)
276                                 bytes_read = data_bytes; /* chop off anything after the end of the data chunk */
277                         if(bytes_read % bytes_per_wide_sample != 0) {
278                                 fprintf(stderr, "ERROR, got partial sample from input file %s\n", infile);
279                                 goto wav_abort_;
280                         }
281                         else {
282                                 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
283                                 format_input(wide_samples, false, is_unsigned_samples, channels, bps, &encoder_wrapper);
284                                 if(!FLAC__encoder_process(encoder_wrapper.encoder, input, wide_samples)) {
285                                         fprintf(stderr, "ERROR during encoding, state = %d:%s\n", encoder_wrapper.encoder->state, FLAC__EncoderStateString[encoder_wrapper.encoder->state]);
286                                         goto wav_abort_;
287                                 }
288                                 data_bytes -= bytes_read;
289                         }
290                 }
291         }
292
293 wav_end_:
294         if(encoder_wrapper.encoder) {
295                 if(encoder_wrapper.encoder->state == FLAC__ENCODER_OK)
296                         FLAC__encoder_finish(encoder_wrapper.encoder);
297                 FLAC__encoder_free_instance(encoder_wrapper.encoder);
298         }
299         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
300                 print_stats(&encoder_wrapper);
301                 printf("\n");
302         }
303         if(verify) {
304                 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
305                         printf("Verify FAILED! (%s)  Do not use %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfile);
306                         return 1;
307                 }
308                 else {
309                         printf("Verify succeeded\n");
310                 }
311         }
312         fclose(fin);
313         return 0;
314 wav_abort_:
315         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0)
316                 printf("\n");
317         if(encoder_wrapper.encoder) {
318                 if(encoder_wrapper.encoder->state == FLAC__ENCODER_OK)
319                         FLAC__encoder_finish(encoder_wrapper.encoder);
320                 FLAC__encoder_free_instance(encoder_wrapper.encoder);
321         }
322         if(verify) {
323                 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
324                         printf("Verify FAILED! (%s)  Do not use %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfile);
325                         return 1;
326                 }
327                 else {
328                         printf("Verify succeeded\n");
329                 }
330         }
331         fclose(fin);
332         unlink(outfile);
333         return 1;
334 }
335
336 int encode_raw(const char *infile, const char *outfile, bool verbose, uint64 skip, bool verify, bool lax, bool do_mid_side, bool loose_mid_side, bool do_exhaustive_model_search, bool do_qlp_coeff_prec_search, unsigned rice_optimization_level, unsigned max_lpc_order, unsigned blocksize, unsigned qlp_coeff_precision, unsigned padding, char *requested_seek_points, int num_requested_seek_points, bool is_big_endian, bool is_unsigned_samples, unsigned channels, unsigned bps, unsigned sample_rate)
337 {
338         encoder_wrapper_struct encoder_wrapper;
339         FILE *fin;
340         size_t bytes_read;
341         const size_t bytes_per_wide_sample = channels * (bps >> 3);
342
343         encoder_wrapper.encoder = 0;
344         encoder_wrapper.verify = verify;
345         encoder_wrapper.verbose = verbose;
346         encoder_wrapper.bytes_written = 0;
347         encoder_wrapper.samples_written = 0;
348         encoder_wrapper.outfile = outfile;
349
350         if(0 == strcmp(infile, "-")) {
351                 fin = stdin;
352         }
353         else {
354                 if(0 == (fin = fopen(infile, "rb"))) {
355                         fprintf(stderr, "ERROR: can't open input file %s\n", infile);
356                         return false;
357                 }
358         }
359         if(0 == strcmp(outfile, "-")) {
360                 encoder_wrapper.fout = stdout;
361         }
362         else {
363                 if(0 == (encoder_wrapper.fout = fopen(outfile, "wb"))) {
364                         fprintf(stderr, "ERROR: can't open output file %s\n", outfile);
365                         fclose(fin);
366                         return false;
367                 }
368         }
369
370         if(!init(&encoder_wrapper))
371                 goto raw_abort_;
372
373         /* get the file length */
374         if(0 != fseek(fin, 0, SEEK_END)) {
375                 encoder_wrapper.total_samples_to_encode = encoder_wrapper.unencoded_size = 0;
376         }
377         else {
378                 long filesize;
379                 fflush(fin);
380                 if(-1 == (filesize = ftell(fin))) {
381                         encoder_wrapper.total_samples_to_encode = encoder_wrapper.unencoded_size = 0;
382                 }
383                 else {
384                         encoder_wrapper.unencoded_size = filesize - skip * bytes_per_wide_sample;
385                         encoder_wrapper.total_samples_to_encode = filesize / bytes_per_wide_sample - skip;
386                 }
387         }
388
389         if(skip > 0) {
390                 if(fin != stdin) {
391                         if(-1 == fseek(fin, bytes_per_wide_sample * (unsigned)skip, SEEK_SET)) {
392                                 fprintf(stderr, "ERROR seeking while skipping samples in input file %s\n", infile);
393                                 goto raw_abort_;
394                         }
395                 }
396                 else {
397                         int64 left;
398                         unsigned need;
399                         for(left = (int64)skip; left > 0; left -= CHUNK_OF_SAMPLES) {
400                                 need = min(left, CHUNK_OF_SAMPLES);
401                                 if(fread(ucbuffer, 1, bytes_per_wide_sample * need, fin) < need) {
402                                         fprintf(stderr, "ERROR seeking while skipping samples in input file %s\n", infile);
403                                         goto raw_abort_;
404                                 }
405                         }
406                 }
407         }
408         else {
409                 fseek(fin, 0, SEEK_SET);
410         }
411
412         if(!init_encoder(lax, do_mid_side, loose_mid_side, do_exhaustive_model_search, do_qlp_coeff_prec_search, rice_optimization_level, max_lpc_order, blocksize, qlp_coeff_precision, channels, bps, sample_rate, padding, requested_seek_points, num_requested_seek_points, &encoder_wrapper))
413                 goto raw_abort_;
414
415         encoder_wrapper.verify_fifo.into_frames = true;
416
417         while(!feof(fin)) {
418                 bytes_read = fread(ucbuffer, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample, fin);
419                 if(bytes_read == 0) {
420                         if(ferror(fin)) {
421                                 fprintf(stderr, "ERROR reading from %s\n", infile);
422                                 goto raw_abort_;
423                         }
424                 }
425                 else if(bytes_read % bytes_per_wide_sample != 0) {
426                         fprintf(stderr, "ERROR, got partial sample from input file %s\n", infile);
427                         goto raw_abort_;
428                 }
429                 else {
430                         unsigned wide_samples = bytes_read / bytes_per_wide_sample;
431                         format_input(wide_samples, is_big_endian, is_unsigned_samples, channels, bps, &encoder_wrapper);
432                         if(!FLAC__encoder_process(encoder_wrapper.encoder, input, wide_samples)) {
433                                 fprintf(stderr, "ERROR during encoding, state = %d:%s\n", encoder_wrapper.encoder->state, FLAC__EncoderStateString[encoder_wrapper.encoder->state]);
434                                 goto raw_abort_;
435                         }
436                 }
437         }
438
439         if(encoder_wrapper.encoder) {
440                 if(encoder_wrapper.encoder->state == FLAC__ENCODER_OK)
441                         FLAC__encoder_finish(encoder_wrapper.encoder);
442                 FLAC__encoder_free_instance(encoder_wrapper.encoder);
443         }
444         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
445                 print_stats(&encoder_wrapper);
446                 printf("\n");
447         }
448         if(verify) {
449                 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
450                         printf("Verify FAILED! (%s)  Do not use %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfile);
451                         return 1;
452                 }
453                 else {
454                         printf("Verify succeeded\n");
455                 }
456         }
457         fclose(fin);
458         return 0;
459 raw_abort_:
460         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0)
461                 printf("\n");
462         if(encoder_wrapper.encoder) {
463                 if(encoder_wrapper.encoder->state == FLAC__ENCODER_OK)
464                         FLAC__encoder_finish(encoder_wrapper.encoder);
465                 FLAC__encoder_free_instance(encoder_wrapper.encoder);
466         }
467         if(verify) {
468                 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
469                         printf("Verify FAILED! (%s)  Do not use %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfile);
470                         return 1;
471                 }
472                 else {
473                         printf("Verify succeeded\n");
474                 }
475         }
476         fclose(fin);
477         unlink(outfile);
478         return 1;
479 }
480
481 bool init(encoder_wrapper_struct *encoder_wrapper)
482 {
483         unsigned i;
484         uint32 test = 1;
485
486         is_big_endian_host = (*((byte*)(&test)))? false : true;
487
488         for(i = 0; i < FLAC__MAX_CHANNELS; i++)
489                 input[i] = &(in[i][0]);
490
491         encoder_wrapper->encoder = FLAC__encoder_get_new_instance();
492         if(0 == encoder_wrapper->encoder) {
493                 fprintf(stderr, "ERROR creating the encoder instance\n");
494                 return false;
495         }
496
497         return true;
498 }
499
500 bool init_encoder(bool lax, bool do_mid_side, bool loose_mid_side, bool do_exhaustive_model_search, bool do_qlp_coeff_prec_search, unsigned rice_optimization_level, unsigned max_lpc_order, unsigned blocksize, unsigned qlp_coeff_precision, unsigned channels, unsigned bps, unsigned sample_rate, unsigned padding, char *requested_seek_points, int num_requested_seek_points, encoder_wrapper_struct *encoder_wrapper)
501 {
502         unsigned i;
503
504         if(channels != 2)
505                 do_mid_side = loose_mid_side = false;
506
507         if(encoder_wrapper->verify) {
508                 /* set up the fifo which will hold the original signal to compare against */
509                 encoder_wrapper->verify_fifo.size = blocksize + CHUNK_OF_SAMPLES;
510                 for(i = 0; i < channels; i++) {
511                         if(0 == (encoder_wrapper->verify_fifo.original[i] = (int32*)malloc(sizeof(int32) * encoder_wrapper->verify_fifo.size))) {
512                                 fprintf(stderr, "ERROR allocating verify buffers\n");
513                                 return false;
514                         }
515                 }
516                 encoder_wrapper->verify_fifo.tail = 0;
517                 encoder_wrapper->verify_fifo.into_frames = false;
518                 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_OK;
519
520                 /* set up a stream decoder for verification */
521                 encoder_wrapper->verify_fifo.decoder = FLAC__stream_decoder_get_new_instance();
522                 if(0 == encoder_wrapper->verify_fifo.decoder) {
523                         fprintf(stderr, "ERROR creating the verify decoder instance\n");
524                         return false;
525                 }
526                 if(FLAC__stream_decoder_init(encoder_wrapper->verify_fifo.decoder, verify_read_callback, verify_write_callback, verify_metadata_callback, verify_error_callback, encoder_wrapper) != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA) {
527                         fprintf(stderr, "ERROR initializing decoder, state = %d:%s\n", encoder_wrapper->verify_fifo.decoder->state, FLAC__StreamDecoderStateString[encoder_wrapper->verify_fifo.decoder->state]);
528                         return false;
529                 }
530         }
531
532         if(!convert_to_seek_table(requested_seek_points, num_requested_seek_points, encoder_wrapper->total_samples_to_encode, blocksize, &encoder_wrapper->seek_table)) {
533                 fprintf(stderr, "ERROR allocating seek table\n");
534                 return false;
535         }
536
537         if(encoder_wrapper->verbose && encoder_wrapper->seek_table.num_points > 0) {
538                 printf("seek points:");
539                 for(i = 0; i < encoder_wrapper->seek_table.num_points; i++) {
540                         if(encoder_wrapper->seek_table.points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER)
541                                 printf(" %llu", encoder_wrapper->seek_table.points[i].sample_number);
542                         else
543                                 printf(" X");
544                 }
545                 printf("\n");
546         }
547
548         encoder_wrapper->encoder->streamable_subset = !lax;
549         encoder_wrapper->encoder->channels = channels;
550         encoder_wrapper->encoder->bits_per_sample = bps;
551         encoder_wrapper->encoder->sample_rate = sample_rate;
552         encoder_wrapper->encoder->blocksize = blocksize;
553         encoder_wrapper->encoder->qlp_coeff_precision = qlp_coeff_precision;
554         encoder_wrapper->encoder->max_lpc_order = max_lpc_order;
555         encoder_wrapper->encoder->do_mid_side_stereo = do_mid_side;
556         encoder_wrapper->encoder->loose_mid_side_stereo = loose_mid_side;
557         encoder_wrapper->encoder->do_exhaustive_model_search = do_exhaustive_model_search;
558         encoder_wrapper->encoder->do_qlp_coeff_prec_search = do_qlp_coeff_prec_search;
559         encoder_wrapper->encoder->rice_optimization_level = rice_optimization_level;
560         encoder_wrapper->encoder->total_samples_estimate = encoder_wrapper->total_samples_to_encode;
561         encoder_wrapper->encoder->seek_table = (encoder_wrapper->seek_table.num_points > 0)? &encoder_wrapper->seek_table : 0;
562         encoder_wrapper->encoder->padding = padding;
563
564         if(FLAC__encoder_init(encoder_wrapper->encoder, write_callback, metadata_callback, encoder_wrapper) != FLAC__ENCODER_OK) {
565                 fprintf(stderr, "ERROR initializing encoder, state = %d:%s\n", encoder_wrapper->encoder->state, FLAC__EncoderStateString[encoder_wrapper->encoder->state]);
566                 return false;
567         }
568
569         return true;
570 }
571
572 bool convert_to_seek_table(char *requested_seek_points, int num_requested_seek_points, uint64 stream_samples, unsigned blocksize, FLAC__StreamMetaData_SeekTable *seek_table)
573 {
574         unsigned i, j, real_points, placeholders;
575         char *pt = requested_seek_points, *q;
576         bool first;
577
578         seek_table->num_points = 0;
579
580         if(num_requested_seek_points == 0)
581                 return true;
582
583         if(num_requested_seek_points < 0) {
584                 strcpy(requested_seek_points, ",100x");
585                 num_requested_seek_points = 100;
586         }
587
588         /* first count how many individual seek point we may need */
589         real_points = placeholders = 0;
590         for(i = 0; i < (unsigned)num_requested_seek_points; i++) {
591                 q = strchr(pt, ',');
592                 assert(0 != q);
593                 *q = '\0';
594
595                 if(0 == strcmp(pt, "X")) { /* -S X */
596                         placeholders++;
597                 }
598                 else if(pt[strlen(pt)-1] == 'x') { /* -S #x */
599                         if(stream_samples > 0) /* we can only do these if we know the number of samples to encode up front */
600                                 real_points += (unsigned)atoi(pt);
601                 }
602                 else { /* -S # */
603                         real_points++;
604                 }
605                 *q++ = ',';
606
607                 pt = q;
608         }
609
610         /* make some space */
611         if(0 == (seek_table->points = (FLAC__StreamMetaData_SeekPoint*)malloc(sizeof(FLAC__StreamMetaData_SeekPoint) * (real_points+placeholders))))
612                 return false;
613
614         for(i = 0; i < (unsigned)num_requested_seek_points; i++) {
615                 q = strchr(pt, ',');
616                 assert(0 != q);
617                 *q++ = '\0';
618
619                 if(0 == strcmp(pt, "X")) { /* -S X */
620                         placeholders++;
621                 }
622                 else if(pt[strlen(pt)-1] == 'x') { /* -S #x */
623                         if(stream_samples > 0) { /* we can only do these if we know the number of samples to encode up front */
624                                 unsigned j, n;
625                                 n = (unsigned)atoi(pt);
626                                 for(j = 0; j < n; j++)
627                                         append_point_to_seek_table(seek_table, stream_samples * (uint64)j / (uint64)n, stream_samples, blocksize);
628                         }
629                 }
630                 else { /* -S # */
631                         append_point_to_seek_table(seek_table, (uint64)atoi(pt), stream_samples, blocksize);
632                 }
633
634                 pt = q;
635         }
636
637         /* sort the seekpoints */
638         qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetaData_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare);
639
640         /* uniqify the seekpoints */
641         first = false;
642         for(i = j = 0; i < seek_table->num_points; i++) {
643                 if(!first) {
644                         if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
645                                 continue;
646                 }
647                 first = false;
648                 seek_table->points[j++] = seek_table->points[i];
649         }
650         seek_table->num_points = j;
651
652         /* append placeholders */
653         for(i = 0, j = seek_table->num_points; i < placeholders; i++, j++)
654                 seek_table->points[j].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
655         seek_table->num_points += placeholders;
656
657         return true;
658 }
659
660 void append_point_to_seek_table(FLAC__StreamMetaData_SeekTable *seek_table, uint64 sample, uint64 stream_samples, uint64 blocksize)
661 {
662         const uint64 target_sample = (sample / blocksize) * blocksize;
663
664         if(stream_samples == 0 || target_sample < stream_samples)
665                 seek_table->points[seek_table->num_points++].sample_number = target_sample;
666 }
667
668 int seekpoint_compare(const FLAC__StreamMetaData_SeekPoint *l, const FLAC__StreamMetaData_SeekPoint *r)
669 {
670         /* we don't just 'return l->sample_number - r->sample_number' since the result (int64) might overflow an 'int' */
671         if(l->sample_number == r->sample_number)
672                 return 0;
673         else if(l->sample_number < r->sample_number)
674                 return -1;
675         else
676                 return 1;
677 }
678
679 void format_input(unsigned wide_samples, bool is_big_endian, bool is_unsigned_samples, unsigned channels, unsigned bps, encoder_wrapper_struct *encoder_wrapper)
680 {
681         unsigned wide_sample, sample, channel, byte;
682
683         if(bps == 8) {
684                 if(is_unsigned_samples) {
685                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
686                                 for(channel = 0; channel < channels; channel++, sample++)
687                                         input[channel][wide_sample] = (int32)ucbuffer[sample] - 0x80;
688                 }
689                 else {
690                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
691                                 for(channel = 0; channel < channels; channel++, sample++)
692                                         input[channel][wide_sample] = (int32)scbuffer[sample];
693                 }
694         }
695         else if(bps == 16) {
696                 if(is_big_endian != is_big_endian_host) {
697                         unsigned char tmp;
698                         const unsigned bytes = wide_samples * channels * (bps >> 3);
699                         for(byte = 0; byte < bytes; byte += 2) {
700                                 tmp = ucbuffer[byte];
701                                 ucbuffer[byte] = ucbuffer[byte+1];
702                                 ucbuffer[byte+1] = tmp;
703                         }
704                 }
705                 if(is_unsigned_samples) {
706                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
707                                 for(channel = 0; channel < channels; channel++, sample++)
708                                         input[channel][wide_sample] = (int32)usbuffer[sample] - 0x8000;
709                 }
710                 else {
711                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
712                                 for(channel = 0; channel < channels; channel++, sample++)
713                                         input[channel][wide_sample] = (int32)ssbuffer[sample];
714                 }
715         }
716         else if(bps == 24) {
717                 if(!is_big_endian) {
718                         unsigned char tmp;
719                         const unsigned bytes = wide_samples * channels * (bps >> 3);
720                         for(byte = 0; byte < bytes; byte += 3) {
721                                 tmp = ucbuffer[byte];
722                                 ucbuffer[byte] = ucbuffer[byte+2];
723                                 ucbuffer[byte+2] = tmp;
724                         }
725                 }
726                 if(is_unsigned_samples) {
727                         for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
728                                 for(channel = 0; channel < channels; channel++, sample++) {
729                                         input[channel][wide_sample]  = ucbuffer[byte++]; input[channel][wide_sample] <<= 8;
730                                         input[channel][wide_sample] |= ucbuffer[byte++]; input[channel][wide_sample] <<= 8;
731                                         input[channel][wide_sample] |= ucbuffer[byte++];
732                                         input[channel][wide_sample] -= 0x800000;
733                                 }
734                 }
735                 else {
736                         for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
737                                 for(channel = 0; channel < channels; channel++, sample++) {
738                                         input[channel][wide_sample]  = scbuffer[byte++]; input[channel][wide_sample] <<= 8;
739                                         input[channel][wide_sample] |= ucbuffer[byte++]; input[channel][wide_sample] <<= 8;
740                                         input[channel][wide_sample] |= ucbuffer[byte++];
741                                 }
742                 }
743         }
744         else {
745                 assert(0);
746         }
747
748         if(encoder_wrapper->verify) {
749                 for(channel = 0; channel < channels; channel++)
750                         memcpy(&encoder_wrapper->verify_fifo.original[channel][encoder_wrapper->verify_fifo.tail], &input[channel][0], sizeof(int32) * wide_samples);
751                 encoder_wrapper->verify_fifo.tail += wide_samples;
752                 assert(encoder_wrapper->verify_fifo.tail <= encoder_wrapper->verify_fifo.size);
753         }
754 }
755
756 FLAC__EncoderWriteStatus write_callback(const FLAC__Encoder *encoder, const byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data)
757 {
758         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
759         unsigned mask = (encoder->do_exhaustive_model_search || encoder->do_qlp_coeff_prec_search)? 0x07 : 0x1f;
760
761         encoder_wrapper->bytes_written += bytes;
762         encoder_wrapper->samples_written += samples;
763         encoder_wrapper->current_frame = current_frame;
764
765         if(samples && encoder_wrapper->verbose && encoder_wrapper->total_samples_to_encode > 0 && !(current_frame & mask))
766                 print_stats(encoder_wrapper);
767
768         if(encoder_wrapper->verify) {
769                 encoder_wrapper->verify_fifo.encoded_signal = buffer;
770                 encoder_wrapper->verify_fifo.encoded_bytes = bytes;
771                 if(encoder_wrapper->verify_fifo.into_frames) {
772                         if(!FLAC__stream_decoder_process_one_frame(encoder_wrapper->verify_fifo.decoder)) {
773                                 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_FAILED_IN_FRAME;
774                                 return FLAC__ENCODER_WRITE_FATAL_ERROR;
775                         }
776                 }
777                 else {
778                         if(!FLAC__stream_decoder_process_metadata(encoder_wrapper->verify_fifo.decoder)) {
779                                 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_FAILED_IN_METADATA;
780                                 return FLAC__ENCODER_WRITE_FATAL_ERROR;
781                         }
782                 }
783         }
784
785         if(fwrite(buffer, sizeof(byte), bytes, encoder_wrapper->fout) == bytes)
786                 return FLAC__ENCODER_WRITE_OK;
787         else
788                 return FLAC__ENCODER_WRITE_FATAL_ERROR;
789 }
790
791 void metadata_callback(const FLAC__Encoder *encoder, const FLAC__StreamMetaData *metadata, void *client_data)
792 {
793         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
794         byte b;
795         FILE *f;
796         const uint64 samples = metadata->data.stream_info.total_samples;
797         const unsigned min_framesize = metadata->data.stream_info.min_framesize;
798         const unsigned max_framesize = metadata->data.stream_info.max_framesize;
799
800         (void)encoder; /* silence compiler warning about unused parameter */
801
802         if(encoder_wrapper->fout == stdout)
803                 return;
804
805         fclose(encoder_wrapper->fout);
806         if(0 == (f = fopen(encoder_wrapper->outfile, "r+b")))
807                 return;
808
809         /* all this is based on intimate knowledge of the stream header
810          * layout, but a change to the header format that would break this
811          * would also break all streams encoded in the previous format.
812          */
813
814         if(-1 == fseek(f, 26, SEEK_SET)) goto samples_;
815         fwrite(metadata->data.stream_info.md5sum, 1, 16, f);
816
817 samples_:
818         if(-1 == fseek(f, 21, SEEK_SET)) goto framesize_;
819         if(fread(&b, 1, 1, f) != 1) goto framesize_;
820         if(-1 == fseek(f, 21, SEEK_SET)) goto framesize_;
821         b = (b & 0xf0) | (byte)((samples >> 32) & 0x0F);
822         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
823         b = (byte)((samples >> 24) & 0xFF);
824         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
825         b = (byte)((samples >> 16) & 0xFF);
826         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
827         b = (byte)((samples >> 8) & 0xFF);
828         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
829         b = (byte)(samples & 0xFF);
830         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
831
832 framesize_:
833         if(-1 == fseek(f, 12, SEEK_SET)) goto end_;
834         b = (byte)((min_framesize >> 16) & 0xFF);
835         if(fwrite(&b, 1, 1, f) != 1) goto end_;
836         b = (byte)((min_framesize >> 8) & 0xFF);
837         if(fwrite(&b, 1, 1, f) != 1) goto end_;
838         b = (byte)(min_framesize & 0xFF);
839         if(fwrite(&b, 1, 1, f) != 1) goto end_;
840         b = (byte)((max_framesize >> 16) & 0xFF);
841         if(fwrite(&b, 1, 1, f) != 1) goto end_;
842         b = (byte)((max_framesize >> 8) & 0xFF);
843         if(fwrite(&b, 1, 1, f) != 1) goto end_;
844         b = (byte)(max_framesize & 0xFF);
845         if(fwrite(&b, 1, 1, f) != 1) goto end_;
846 end_:
847         fclose(f);
848         return;
849 }
850
851 FLAC__StreamDecoderReadStatus verify_read_callback(const FLAC__StreamDecoder *decoder, byte buffer[], unsigned *bytes, void *client_data)
852 {
853         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
854         const unsigned encoded_bytes = encoder_wrapper->verify_fifo.encoded_bytes;
855         (void)decoder;
856
857         if(encoded_bytes <= *bytes) {
858                 *bytes = encoded_bytes;
859                 memcpy(buffer, encoder_wrapper->verify_fifo.encoded_signal, *bytes);
860         }
861         else {
862                 memcpy(buffer, encoder_wrapper->verify_fifo.encoded_signal, *bytes);
863                 encoder_wrapper->verify_fifo.encoded_signal += *bytes;
864                 encoder_wrapper->verify_fifo.encoded_bytes -= *bytes;
865         }
866
867         return FLAC__STREAM_DECODER_READ_CONTINUE;
868 }
869
870 FLAC__StreamDecoderWriteStatus verify_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const int32 *buffer[], void *client_data)
871 {
872         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
873         unsigned channel, l, r;
874
875         for(channel = 0; channel < decoder->channels; channel++) {
876                 if(0 != memcmp(buffer[channel], encoder_wrapper->verify_fifo.original[channel], sizeof(int32) * decoder->blocksize)) {
877                         fprintf(stderr, "\nERROR: mismatch in decoded data, verify FAILED!\n");
878                         fprintf(stderr, "       Please submit a bug report to http://sourceforge.net/bugs/?func=addbug&group_id=13478\n");
879                         return FLAC__STREAM_DECODER_WRITE_ABORT;
880                 }
881         }
882         /* dequeue the frame from the fifo */
883         for(channel = 0; channel < decoder->channels; channel++) {
884                 for(l = 0, r = frame->header.blocksize; r < encoder_wrapper->verify_fifo.tail; l++, r++) {
885                         encoder_wrapper->verify_fifo.original[channel][l] = encoder_wrapper->verify_fifo.original[channel][r];
886                 }
887         }
888         encoder_wrapper->verify_fifo.tail -= frame->header.blocksize;
889         return FLAC__STREAM_DECODER_WRITE_CONTINUE;
890 }
891
892 void verify_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data)
893 {
894         (void)decoder;
895         (void)metadata;
896         (void)client_data;
897 }
898
899 void verify_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
900 {
901         (void)decoder;
902         (void)client_data;
903         fprintf(stderr, "\nERROR: verification decoder returned error %d:%s\n", status, FLAC__StreamDecoderErrorStatusString[status]);
904 }
905
906 void print_stats(const encoder_wrapper_struct *encoder_wrapper)
907 {
908 #ifdef _MSC_VER
909         /* with VC++ you have to spoon feed it the casting */
910         double progress = (double)(int64)encoder_wrapper->samples_written / (double)(int64)encoder_wrapper->total_samples_to_encode;
911 #else
912         double progress = (double)encoder_wrapper->samples_written / (double)encoder_wrapper->total_samples_to_encode;
913 #endif
914         printf("\r%0.2f%% complete: frame %u, wrote %u bytes, %u of %u samples, ratio = %5.3f",
915                 progress * 100.0, encoder_wrapper->current_frame,
916                 (unsigned)encoder_wrapper->bytes_written, (unsigned)encoder_wrapper->samples_written, (unsigned)encoder_wrapper->total_samples_to_encode,
917 #ifdef _MSC_VER
918                 /* with VC++ you have to spoon feed it the casting */
919                 (double)(int64)encoder_wrapper->bytes_written / ((double)(int64)encoder_wrapper->unencoded_size * progress)
920 #else
921                 (double)encoder_wrapper->bytes_written / ((double)encoder_wrapper->unencoded_size * progress)
922 #endif
923         );
924         fflush(stdout);
925 }
926
927 bool read_little_endian_uint16(FILE *f, uint16 *val, bool eof_ok)
928 {
929         size_t bytes_read = fread(val, 1, 2, f);
930
931         if(bytes_read == 0) {
932                 if(!eof_ok) {
933                         fprintf(stderr, "ERROR: unexpected EOF\n");
934                         return false;
935                 }
936                 else
937                         return true;
938         }
939         else if(bytes_read < 2) {
940                 fprintf(stderr, "ERROR: unexpected EOF\n");
941                 return false;
942         }
943         else {
944                 if(is_big_endian_host) {
945                         byte tmp, *b = (byte*)val;
946                         tmp = b[1]; b[1] = b[0]; b[0] = tmp;
947                 }
948                 return true;
949         }
950 }
951
952 bool read_little_endian_uint32(FILE *f, uint32 *val, bool eof_ok)
953 {
954         size_t bytes_read = fread(val, 1, 4, f);
955
956         if(bytes_read == 0) {
957                 if(!eof_ok) {
958                         fprintf(stderr, "ERROR: unexpected EOF\n");
959                         return false;
960                 }
961                 else
962                         return true;
963         }
964         else if(bytes_read < 4) {
965                 fprintf(stderr, "ERROR: unexpected EOF\n");
966                 return false;
967         }
968         else {
969                 if(is_big_endian_host) {
970                         byte tmp, *b = (byte*)val;
971                         tmp = b[3]; b[3] = b[0]; b[0] = tmp;
972                         tmp = b[2]; b[2] = b[1]; b[1] = tmp;
973                 }
974                 return true;
975         }
976 }