add support for specifying seek points
[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         if(channels != 2)
503                 do_mid_side = loose_mid_side = false;
504
505         if(encoder_wrapper->verify) {
506                 unsigned i;
507
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         encoder_wrapper->encoder->streamable_subset = !lax;
538         encoder_wrapper->encoder->channels = channels;
539         encoder_wrapper->encoder->bits_per_sample = bps;
540         encoder_wrapper->encoder->sample_rate = sample_rate;
541         encoder_wrapper->encoder->blocksize = blocksize;
542         encoder_wrapper->encoder->qlp_coeff_precision = qlp_coeff_precision;
543         encoder_wrapper->encoder->max_lpc_order = max_lpc_order;
544         encoder_wrapper->encoder->do_mid_side_stereo = do_mid_side;
545         encoder_wrapper->encoder->loose_mid_side_stereo = loose_mid_side;
546         encoder_wrapper->encoder->do_exhaustive_model_search = do_exhaustive_model_search;
547         encoder_wrapper->encoder->do_qlp_coeff_prec_search = do_qlp_coeff_prec_search;
548         encoder_wrapper->encoder->rice_optimization_level = rice_optimization_level;
549         encoder_wrapper->encoder->total_samples_estimate = encoder_wrapper->total_samples_to_encode;
550         encoder_wrapper->encoder->seek_table = (encoder_wrapper->seek_table.num_points > 0)? &encoder_wrapper->seek_table : 0;
551         encoder_wrapper->encoder->padding = padding;
552
553         if(FLAC__encoder_init(encoder_wrapper->encoder, write_callback, metadata_callback, encoder_wrapper) != FLAC__ENCODER_OK) {
554                 fprintf(stderr, "ERROR initializing encoder, state = %d:%s\n", encoder_wrapper->encoder->state, FLAC__EncoderStateString[encoder_wrapper->encoder->state]);
555                 return false;
556         }
557
558         return true;
559 }
560
561 bool convert_to_seek_table(char *requested_seek_points, int num_requested_seek_points, uint64 stream_samples, unsigned blocksize, FLAC__StreamMetaData_SeekTable *seek_table)
562 {
563         unsigned i, j, real_points, placeholders;
564         char *pt = requested_seek_points, *q;
565         bool first;
566
567         seek_table->num_points = 0;
568
569         if(num_requested_seek_points == 0)
570                 return true;
571
572         if(num_requested_seek_points < 0) {
573                 strcpy(requested_seek_points, ",100x");
574                 num_requested_seek_points = 100;
575         }
576
577         /* first count how many individual seek point we may need */
578         real_points = placeholders = 0;
579         for(i = 0; i < (unsigned)num_requested_seek_points; i++) {
580                 q = strchr(pt, ',');
581                 assert(0 != q);
582                 *q = '\0';
583
584                 if(0 == strcmp(pt, "X")) { /* -S X */
585                         placeholders++;
586                 }
587                 else if(pt[strlen(pt)-1] == 'x') { /* -S #x */
588                         if(stream_samples > 0) /* we can only do these if we know the number of samples to encode up front */
589                                 real_points += (unsigned)atoi(pt);
590                 }
591                 else { /* -S # */
592                         real_points++;
593                 }
594                 *q++ = ',';
595
596                 pt = q;
597         }
598
599         /* make some space */
600         if(0 == (seek_table->points = (FLAC__StreamMetaData_SeekPoint*)malloc(sizeof(FLAC__StreamMetaData_SeekPoint) * (real_points+placeholders))))
601                 return false;
602
603         for(i = 0; i < (unsigned)num_requested_seek_points; i++) {
604                 q = strchr(pt, ',');
605                 assert(0 != q);
606                 *q++ = '\0';
607
608                 if(0 == strcmp(pt, "X")) { /* -S X */
609                         placeholders++;
610                 }
611                 else if(pt[strlen(pt)-1] == 'x') { /* -S #x */
612                         if(stream_samples > 0) { /* we can only do these if we know the number of samples to encode up front */
613                                 unsigned j, n;
614                                 n = (unsigned)atoi(pt);
615                                 for(j = 0; j < n; j++)
616                                         append_point_to_seek_table(seek_table, stream_samples * (uint64)j / (uint64)n, stream_samples, blocksize);
617                         }
618                 }
619                 else { /* -S # */
620                         append_point_to_seek_table(seek_table, (uint64)atoi(pt), stream_samples, blocksize);
621                 }
622
623                 pt = q;
624         }
625
626         /* sort the seekpoints */
627         qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetaData_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare);
628
629         /* uniqify the seekpoints */
630         first = false;
631         for(i = j = 0; i < seek_table->num_points; i++) {
632                 if(!first) {
633                         if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
634                                 continue;
635                 }
636                 first = false;
637                 seek_table->points[j++] = seek_table->points[i];
638         }
639         seek_table->num_points = j;
640
641         /* append placeholders */
642         for(i = 0, j = seek_table->num_points; i < placeholders; i++, j++)
643                 seek_table->points[j].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
644         seek_table->num_points += placeholders;
645
646         return true;
647 }
648
649 void append_point_to_seek_table(FLAC__StreamMetaData_SeekTable *seek_table, uint64 sample, uint64 stream_samples, uint64 blocksize)
650 {
651         const uint64 target_sample = (sample / blocksize) * blocksize;
652
653         if(stream_samples == 0 || target_sample < stream_samples)
654                 seek_table->points[seek_table->num_points++].sample_number = target_sample;
655 }
656
657 int seekpoint_compare(const FLAC__StreamMetaData_SeekPoint *l, const FLAC__StreamMetaData_SeekPoint *r)
658 {
659         /* we don't just 'return l->sample_number - r->sample_number' since the result (int64) might overflow an 'int' */
660         if(l->sample_number == r->sample_number)
661                 return 0;
662         else if(l->sample_number < r->sample_number)
663                 return -1;
664         else
665                 return 1;
666 }
667
668 void format_input(unsigned wide_samples, bool is_big_endian, bool is_unsigned_samples, unsigned channels, unsigned bps, encoder_wrapper_struct *encoder_wrapper)
669 {
670         unsigned wide_sample, sample, channel, byte;
671
672         if(bps == 8) {
673                 if(is_unsigned_samples) {
674                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
675                                 for(channel = 0; channel < channels; channel++, sample++)
676                                         input[channel][wide_sample] = (int32)ucbuffer[sample] - 0x80;
677                 }
678                 else {
679                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
680                                 for(channel = 0; channel < channels; channel++, sample++)
681                                         input[channel][wide_sample] = (int32)scbuffer[sample];
682                 }
683         }
684         else if(bps == 16) {
685                 if(is_big_endian != is_big_endian_host) {
686                         unsigned char tmp;
687                         const unsigned bytes = wide_samples * channels * (bps >> 3);
688                         for(byte = 0; byte < bytes; byte += 2) {
689                                 tmp = ucbuffer[byte];
690                                 ucbuffer[byte] = ucbuffer[byte+1];
691                                 ucbuffer[byte+1] = tmp;
692                         }
693                 }
694                 if(is_unsigned_samples) {
695                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
696                                 for(channel = 0; channel < channels; channel++, sample++)
697                                         input[channel][wide_sample] = (int32)usbuffer[sample] - 0x8000;
698                 }
699                 else {
700                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
701                                 for(channel = 0; channel < channels; channel++, sample++)
702                                         input[channel][wide_sample] = (int32)ssbuffer[sample];
703                 }
704         }
705         else if(bps == 24) {
706                 if(!is_big_endian) {
707                         unsigned char tmp;
708                         const unsigned bytes = wide_samples * channels * (bps >> 3);
709                         for(byte = 0; byte < bytes; byte += 3) {
710                                 tmp = ucbuffer[byte];
711                                 ucbuffer[byte] = ucbuffer[byte+2];
712                                 ucbuffer[byte+2] = tmp;
713                         }
714                 }
715                 if(is_unsigned_samples) {
716                         for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
717                                 for(channel = 0; channel < channels; channel++, sample++) {
718                                         input[channel][wide_sample]  = ucbuffer[byte++]; input[channel][wide_sample] <<= 8;
719                                         input[channel][wide_sample] |= ucbuffer[byte++]; input[channel][wide_sample] <<= 8;
720                                         input[channel][wide_sample] |= ucbuffer[byte++];
721                                         input[channel][wide_sample] -= 0x800000;
722                                 }
723                 }
724                 else {
725                         for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
726                                 for(channel = 0; channel < channels; channel++, sample++) {
727                                         input[channel][wide_sample]  = scbuffer[byte++]; input[channel][wide_sample] <<= 8;
728                                         input[channel][wide_sample] |= ucbuffer[byte++]; input[channel][wide_sample] <<= 8;
729                                         input[channel][wide_sample] |= ucbuffer[byte++];
730                                 }
731                 }
732         }
733         else {
734                 assert(0);
735         }
736
737         if(encoder_wrapper->verify) {
738                 for(channel = 0; channel < channels; channel++)
739                         memcpy(&encoder_wrapper->verify_fifo.original[channel][encoder_wrapper->verify_fifo.tail], &input[channel][0], sizeof(int32) * wide_samples);
740                 encoder_wrapper->verify_fifo.tail += wide_samples;
741                 assert(encoder_wrapper->verify_fifo.tail <= encoder_wrapper->verify_fifo.size);
742         }
743 }
744
745 FLAC__EncoderWriteStatus write_callback(const FLAC__Encoder *encoder, const byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data)
746 {
747         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
748         unsigned mask = (encoder->do_exhaustive_model_search || encoder->do_qlp_coeff_prec_search)? 0x07 : 0x1f;
749
750         encoder_wrapper->bytes_written += bytes;
751         encoder_wrapper->samples_written += samples;
752         encoder_wrapper->current_frame = current_frame;
753
754         if(samples && encoder_wrapper->verbose && encoder_wrapper->total_samples_to_encode > 0 && !(current_frame & mask))
755                 print_stats(encoder_wrapper);
756
757         if(encoder_wrapper->verify) {
758                 encoder_wrapper->verify_fifo.encoded_signal = buffer;
759                 encoder_wrapper->verify_fifo.encoded_bytes = bytes;
760                 if(encoder_wrapper->verify_fifo.into_frames) {
761                         if(!FLAC__stream_decoder_process_one_frame(encoder_wrapper->verify_fifo.decoder)) {
762                                 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_FAILED_IN_FRAME;
763                                 return FLAC__ENCODER_WRITE_FATAL_ERROR;
764                         }
765                 }
766                 else {
767                         if(!FLAC__stream_decoder_process_metadata(encoder_wrapper->verify_fifo.decoder)) {
768                                 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_FAILED_IN_METADATA;
769                                 return FLAC__ENCODER_WRITE_FATAL_ERROR;
770                         }
771                 }
772         }
773
774         if(fwrite(buffer, sizeof(byte), bytes, encoder_wrapper->fout) == bytes)
775                 return FLAC__ENCODER_WRITE_OK;
776         else
777                 return FLAC__ENCODER_WRITE_FATAL_ERROR;
778 }
779
780 void metadata_callback(const FLAC__Encoder *encoder, const FLAC__StreamMetaData *metadata, void *client_data)
781 {
782         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
783         byte b;
784         FILE *f;
785         const uint64 samples = metadata->data.stream_info.total_samples;
786         const unsigned min_framesize = metadata->data.stream_info.min_framesize;
787         const unsigned max_framesize = metadata->data.stream_info.max_framesize;
788
789         (void)encoder; /* silence compiler warning about unused parameter */
790
791         if(encoder_wrapper->fout == stdout)
792                 return;
793
794         fclose(encoder_wrapper->fout);
795         if(0 == (f = fopen(encoder_wrapper->outfile, "r+b")))
796                 return;
797
798         /* all this is based on intimate knowledge of the stream header
799          * layout, but a change to the header format that would break this
800          * would also break all streams encoded in the previous format.
801          */
802
803         if(-1 == fseek(f, 26, SEEK_SET)) goto samples_;
804         fwrite(metadata->data.stream_info.md5sum, 1, 16, f);
805
806 samples_:
807         if(-1 == fseek(f, 21, SEEK_SET)) goto framesize_;
808         if(fread(&b, 1, 1, f) != 1) goto framesize_;
809         if(-1 == fseek(f, 21, SEEK_SET)) goto framesize_;
810         b = (b & 0xf0) | (byte)((samples >> 32) & 0x0F);
811         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
812         b = (byte)((samples >> 24) & 0xFF);
813         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
814         b = (byte)((samples >> 16) & 0xFF);
815         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
816         b = (byte)((samples >> 8) & 0xFF);
817         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
818         b = (byte)(samples & 0xFF);
819         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
820
821 framesize_:
822         if(-1 == fseek(f, 12, SEEK_SET)) goto end_;
823         b = (byte)((min_framesize >> 16) & 0xFF);
824         if(fwrite(&b, 1, 1, f) != 1) goto end_;
825         b = (byte)((min_framesize >> 8) & 0xFF);
826         if(fwrite(&b, 1, 1, f) != 1) goto end_;
827         b = (byte)(min_framesize & 0xFF);
828         if(fwrite(&b, 1, 1, f) != 1) goto end_;
829         b = (byte)((max_framesize >> 16) & 0xFF);
830         if(fwrite(&b, 1, 1, f) != 1) goto end_;
831         b = (byte)((max_framesize >> 8) & 0xFF);
832         if(fwrite(&b, 1, 1, f) != 1) goto end_;
833         b = (byte)(max_framesize & 0xFF);
834         if(fwrite(&b, 1, 1, f) != 1) goto end_;
835 end_:
836         fclose(f);
837         return;
838 }
839
840 FLAC__StreamDecoderReadStatus verify_read_callback(const FLAC__StreamDecoder *decoder, byte buffer[], unsigned *bytes, void *client_data)
841 {
842         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
843         const unsigned encoded_bytes = encoder_wrapper->verify_fifo.encoded_bytes;
844         (void)decoder;
845
846         if(encoded_bytes <= *bytes) {
847                 *bytes = encoded_bytes;
848                 memcpy(buffer, encoder_wrapper->verify_fifo.encoded_signal, *bytes);
849         }
850         else {
851                 memcpy(buffer, encoder_wrapper->verify_fifo.encoded_signal, *bytes);
852                 encoder_wrapper->verify_fifo.encoded_signal += *bytes;
853                 encoder_wrapper->verify_fifo.encoded_bytes -= *bytes;
854         }
855
856         return FLAC__STREAM_DECODER_READ_CONTINUE;
857 }
858
859 FLAC__StreamDecoderWriteStatus verify_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const int32 *buffer[], void *client_data)
860 {
861         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
862         unsigned channel, l, r;
863
864         for(channel = 0; channel < decoder->channels; channel++) {
865                 if(0 != memcmp(buffer[channel], encoder_wrapper->verify_fifo.original[channel], sizeof(int32) * decoder->blocksize)) {
866                         fprintf(stderr, "\nERROR: mismatch in decoded data, verify FAILED!\n");
867                         fprintf(stderr, "       Please submit a bug report to http://sourceforge.net/bugs/?func=addbug&group_id=13478\n");
868                         return FLAC__STREAM_DECODER_WRITE_ABORT;
869                 }
870         }
871         /* dequeue the frame from the fifo */
872         for(channel = 0; channel < decoder->channels; channel++) {
873                 for(l = 0, r = frame->header.blocksize; r < encoder_wrapper->verify_fifo.tail; l++, r++) {
874                         encoder_wrapper->verify_fifo.original[channel][l] = encoder_wrapper->verify_fifo.original[channel][r];
875                 }
876         }
877         encoder_wrapper->verify_fifo.tail -= frame->header.blocksize;
878         return FLAC__STREAM_DECODER_WRITE_CONTINUE;
879 }
880
881 void verify_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetaData *metadata, void *client_data)
882 {
883         (void)decoder;
884         (void)metadata;
885         (void)client_data;
886 }
887
888 void verify_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
889 {
890         (void)decoder;
891         (void)client_data;
892         fprintf(stderr, "\nERROR: verification decoder returned error %d:%s\n", status, FLAC__StreamDecoderErrorStatusString[status]);
893 }
894
895 void print_stats(const encoder_wrapper_struct *encoder_wrapper)
896 {
897 #ifdef _MSC_VER
898         /* with VC++ you have to spoon feed it the casting */
899         double progress = (double)(int64)encoder_wrapper->samples_written / (double)(int64)encoder_wrapper->total_samples_to_encode;
900 #else
901         double progress = (double)encoder_wrapper->samples_written / (double)encoder_wrapper->total_samples_to_encode;
902 #endif
903         printf("\r%0.2f%% complete: frame %u, wrote %u bytes, %u of %u samples, ratio = %5.3f",
904                 progress * 100.0, encoder_wrapper->current_frame,
905                 (unsigned)encoder_wrapper->bytes_written, (unsigned)encoder_wrapper->samples_written, (unsigned)encoder_wrapper->total_samples_to_encode,
906 #ifdef _MSC_VER
907                 /* with VC++ you have to spoon feed it the casting */
908                 (double)(int64)encoder_wrapper->bytes_written / ((double)(int64)encoder_wrapper->unencoded_size * progress)
909 #else
910                 (double)encoder_wrapper->bytes_written / ((double)encoder_wrapper->unencoded_size * progress)
911 #endif
912         );
913         fflush(stdout);
914 }
915
916 bool read_little_endian_uint16(FILE *f, uint16 *val, bool eof_ok)
917 {
918         size_t bytes_read = fread(val, 1, 2, f);
919
920         if(bytes_read == 0) {
921                 if(!eof_ok) {
922                         fprintf(stderr, "ERROR: unexpected EOF\n");
923                         return false;
924                 }
925                 else
926                         return true;
927         }
928         else if(bytes_read < 2) {
929                 fprintf(stderr, "ERROR: unexpected EOF\n");
930                 return false;
931         }
932         else {
933                 if(is_big_endian_host) {
934                         byte tmp, *b = (byte*)val;
935                         tmp = b[1]; b[1] = b[0]; b[0] = tmp;
936                 }
937                 return true;
938         }
939 }
940
941 bool read_little_endian_uint32(FILE *f, uint32 *val, bool eof_ok)
942 {
943         size_t bytes_read = fread(val, 1, 4, f);
944
945         if(bytes_read == 0) {
946                 if(!eof_ok) {
947                         fprintf(stderr, "ERROR: unexpected EOF\n");
948                         return false;
949                 }
950                 else
951                         return true;
952         }
953         else if(bytes_read < 4) {
954                 fprintf(stderr, "ERROR: unexpected EOF\n");
955                 return false;
956         }
957         else {
958                 if(is_big_endian_host) {
959                         byte tmp, *b = (byte*)val;
960                         tmp = b[3]; b[3] = b[0]; b[0] = tmp;
961                         tmp = b[2]; b[2] = b[1]; b[1] = tmp;
962                 }
963                 return true;
964         }
965 }