use new seektable template functions, fix verify logic to work with revamped decoder...
[platform/upstream/flac.git] / src / flac / encode.c
1 /* flac - Command-line FLAC encoder/decoder
2  * Copyright (C) 2000,2001,2002  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 #if defined _WIN32 && !defined __CYGWIN__
20 /* where MSVC puts unlink() */
21 # include <io.h>
22 #else
23 # include <unistd.h>
24 #endif
25 #include <limits.h> /* for LONG_MAX */
26 #include <math.h> /* for floor() */
27 #include <stdio.h> /* for FILE et al. */
28 #include <stdlib.h> /* for malloc */
29 #include <string.h> /* for strcmp() */
30 #include "FLAC/all.h"
31 #include "encode.h"
32 #include "file.h"
33 #ifdef FLAC__HAS_OGG
34 #include "ogg/ogg.h"
35 #endif
36
37 #ifdef min
38 #undef min
39 #endif
40 #define min(x,y) ((x)<(y)?(x):(y))
41
42 /* this MUST be >= 588 so that sector aligning can take place with one read */
43 #define CHUNK_OF_SAMPLES 2048
44
45 typedef enum {
46         FLAC__VERIFY_OK,
47         FLAC__VERIFY_FAILED_IN_FRAME,
48         FLAC__VERIFY_FAILED_IN_METADATA
49 } verify_code;
50
51 static const char *verify_code_string[] = {
52         "FLAC__VERIFY_OK",
53         "FLAC__VERIFY_FAILED_IN_FRAME",
54         "FLAC__VERIFY_FAILED_IN_METADATA"
55 };
56
57 typedef enum {
58         ENCODER_IN_MAGIC = 0,
59         ENCODER_IN_METADATA = 1,
60         ENCODER_IN_AUDIO = 2
61 } EncodeState;
62
63 typedef struct {
64         FLAC__int32 *original[FLAC__MAX_CHANNELS];
65         unsigned size; /* of each original[] in samples */
66         unsigned tail; /* in wide samples */
67         const FLAC__byte *encoded_signal;
68         unsigned encoded_signal_capacity;
69         unsigned encoded_bytes;
70         EncodeState encode_state;
71         FLAC__bool needs_magic_hack;
72         verify_code result;
73         FLAC__StreamDecoder *decoder;
74 } verify_fifo_struct;
75
76 #ifdef FLAC__HAS_OGG
77 typedef struct {
78         ogg_stream_state os;
79         ogg_page og;
80 } ogg_info_struct;
81 #endif
82
83 typedef struct {
84         const char *inbasefilename;
85         FILE *fout;
86         const char *outfilename;
87         FLAC__StreamEncoder *encoder;
88         FLAC__bool verify;
89         FLAC__bool verbose;
90         FLAC__uint64 unencoded_size;
91         FLAC__uint64 total_samples_to_encode;
92         FLAC__uint64 bytes_written;
93         FLAC__uint64 samples_written;
94         FLAC__uint64 stream_offset; /* i.e. number of bytes before the first byte of the the first frame's header */
95         unsigned current_frame;
96         verify_fifo_struct verify_fifo;
97         FLAC__StreamMetadata *seek_table;
98         unsigned first_seek_point_to_check;
99 #ifdef FLAC__HAS_OGG
100         FLAC__bool use_ogg;
101         ogg_info_struct ogg;
102 #endif
103 } encoder_wrapper_struct;
104
105 static FLAC__bool is_big_endian_host;
106
107 static unsigned char ucbuffer[CHUNK_OF_SAMPLES*FLAC__MAX_CHANNELS*((FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE+7)/8)];
108 static signed char *scbuffer = (signed char *)ucbuffer;
109 static FLAC__uint16 *usbuffer = (FLAC__uint16 *)ucbuffer;
110 static FLAC__int16 *ssbuffer = (FLAC__int16 *)ucbuffer;
111
112 static FLAC__int32 in[FLAC__MAX_CHANNELS][CHUNK_OF_SAMPLES];
113 static FLAC__int32 *input[FLAC__MAX_CHANNELS];
114
115 /* local routines */
116 static FLAC__bool init(encoder_wrapper_struct *encoder_wrapper);
117 static FLAC__bool init_encoder(encode_options_t options, unsigned channels, unsigned bps, unsigned sample_rate, encoder_wrapper_struct *encoder_wrapper);
118 static FLAC__bool convert_to_seek_table(char *requested_seek_points, int num_requested_seek_points, FLAC__uint64 stream_samples, FLAC__StreamMetadata *seek_table);
119 static void format_input(FLAC__int32 *dest[], unsigned wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps, encoder_wrapper_struct *encoder_wrapper);
120 static void append_to_verify_fifo(encoder_wrapper_struct *encoder_wrapper, const FLAC__int32 * const input[], unsigned channels, unsigned wide_samples);
121 static FLAC__StreamEncoderWriteStatus write_callback(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data);
122 static void metadata_callback(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
123 static FLAC__StreamDecoderReadStatus verify_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data);
124 static FLAC__StreamDecoderWriteStatus verify_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
125 static void verify_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
126 static void verify_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
127 static void print_stats(const encoder_wrapper_struct *encoder_wrapper);
128 static FLAC__bool read_little_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn);
129 static FLAC__bool read_little_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
130 static FLAC__bool read_big_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn);
131 static FLAC__bool read_big_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
132 static FLAC__bool read_sane_extended(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn);
133 static FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val);
134 static FLAC__bool write_big_endian_uint64(FILE *f, FLAC__uint64 val);
135
136 int
137 flac__encode_aif(FILE *infile, long infilesize, const char *infilename, const char *outfilename,
138         const FLAC__byte *lookahead, unsigned lookahead_length, wav_encode_options_t options)
139 {
140         encoder_wrapper_struct encoder_wrapper;
141         FLAC__uint16 x;
142         FLAC__uint32 xx;
143         unsigned int channels= 0U, bps= 0U, sample_rate= 0U, sample_frames= 0U;
144         FLAC__bool got_comm_chunk= false, got_ssnd_chunk= false;
145         int info_align_carry= -1, info_align_zero= -1;
146         enum { NORMAL, DONE, ERROR, MISMATCH } status= NORMAL;
147
148         FLAC__ASSERT(!options.common.sector_align || options.common.skip == 0);
149
150         encoder_wrapper.encoder = 0;
151         encoder_wrapper.verify = options.common.verify;
152         encoder_wrapper.verbose = options.common.verbose;
153         encoder_wrapper.bytes_written = 0;
154         encoder_wrapper.samples_written = 0;
155         encoder_wrapper.stream_offset = 0;
156         encoder_wrapper.inbasefilename = flac__file_get_basename(infilename);
157         encoder_wrapper.outfilename = outfilename;
158         encoder_wrapper.seek_table = FLAC__metadata_object_new(FLAC__METADATA_TYPE_SEEKTABLE);
159         encoder_wrapper.first_seek_point_to_check = 0;
160 #ifdef FLAC__HAS_OGG
161         encoder_wrapper.use_ogg = options.common.use_ogg;
162 #endif
163
164         if(0 == encoder_wrapper.seek_table) {
165                 fprintf(stderr, "%s: ERROR allocating memory for seek table\n", encoder_wrapper.inbasefilename);
166                 return 1;
167         }
168
169         (void)infilesize; /* silence compiler warning about unused parameter */
170         (void)lookahead; /* silence compiler warning about unused parameter */
171         (void)lookahead_length; /* silence compiler warning about unused parameter */
172
173         if(0 == strcmp(outfilename, "-")) {
174                 encoder_wrapper.fout = file__get_binary_stdout();
175         }
176         else {
177                 if(0 == (encoder_wrapper.fout = fopen(outfilename, "wb"))) {
178                         fprintf(stderr, "%s: ERROR: can't open output file %s\n", encoder_wrapper.inbasefilename, outfilename);
179                         if(infile != stdin)
180                                 fclose(infile);
181                         return 1;
182                 }
183         }
184
185         if(!init(&encoder_wrapper))
186                 status= ERROR;
187
188         /* lookahead[] already has "FORMxxxxAIFF", do sub-chunks */
189
190         while(status==NORMAL) {
191                 size_t c= 0U;
192                 char chunk_id[4];
193
194                 /* chunk identifier; really conservative about behavior of fread() and feof() */
195                 if(feof(infile) || ((c= fread(chunk_id, 1U, 4U, infile)), c==0U && feof(infile)))
196                         status= DONE;
197                 else if(c<4U || feof(infile)) {
198                         fprintf(stderr, "%s: ERROR: incomplete chunk identifier\n", encoder_wrapper.inbasefilename);
199                         status= ERROR;
200                 }
201
202                 if(status==NORMAL && got_comm_chunk==false && !strncmp(chunk_id, "COMM", 4)) { /* common chunk */
203                         unsigned long skip;
204
205                         if(status==NORMAL) {
206                                 /* COMM chunk size */
207                                 if(!read_big_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
208                                         status= ERROR;
209                                 else if(xx<18U) {
210                                         fprintf(stderr, "%s: ERROR: non-standard 'COMM' chunk has length = %u\n", encoder_wrapper.inbasefilename, (unsigned int)xx);
211                                         status= ERROR;
212                                 }
213                                 else if(xx!=18U)
214                                         fprintf(stderr, "%s: WARNING: non-standard 'COMM' chunk has length = %u\n", encoder_wrapper.inbasefilename, (unsigned int)xx);
215                                 skip= (xx-18U)+(xx & 1U);
216                         }
217
218                         if(status==NORMAL) {
219                                 /* number of channels */
220                                 if(!read_big_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
221                                         status= ERROR;
222                                 else if(x==0U || x>FLAC__MAX_CHANNELS) {
223                                         fprintf(stderr, "%s: ERROR: unsupported number channels %u\n", encoder_wrapper.inbasefilename, (unsigned int)x);
224                                         status= ERROR;
225                                 }
226                                 else if(options.common.sector_align && x!=2U) {
227                                         fprintf(stderr, "%s: ERROR: file has %u channels, must be 2 for --sector-align\n", encoder_wrapper.inbasefilename, (unsigned int)x);
228                                         status= ERROR;
229                                 }
230                                 channels= x;
231                         }
232
233                         if(status==NORMAL) {
234                                 /* number of sample frames */
235                                 if(!read_big_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
236                                         status= ERROR;
237                                 sample_frames= xx;
238                         }
239
240                         if(status==NORMAL) {
241                                 /* bits per sample */
242                                 if(!read_big_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
243                                         status= ERROR;
244                                 else if(x!=8U && x!=16U && x!=24U) {
245                                         fprintf(stderr, "%s: ERROR: unsupported bits per sample %u\n", encoder_wrapper.inbasefilename, (unsigned int)x);
246                                         status= ERROR;
247                                 }
248                                 else if(options.common.sector_align && x!=16U) {
249                                         fprintf(stderr, "%s: ERROR: file has %u bits per sample, must be 16 for --sector-align\n", encoder_wrapper.inbasefilename, (unsigned int)x);
250                                         status= ERROR;
251                                 }
252                                 bps= x;
253                         }
254
255                         if(status==NORMAL) {
256                                 /* sample rate */
257                                 if(!read_sane_extended(infile, &xx, false, encoder_wrapper.inbasefilename))
258                                         status= ERROR;
259                                 else if(!FLAC__format_sample_rate_is_valid(xx)) {
260                                         fprintf(stderr, "%s: ERROR: unsupported sample rate %u\n", encoder_wrapper.inbasefilename, (unsigned int)xx);
261                                         status= ERROR;
262                                 }
263                                 else if(options.common.sector_align && xx!=44100U) {
264                                         fprintf(stderr, "%s: ERROR: file's sample rate is %u, must be 44100 for --sector-align\n", encoder_wrapper.inbasefilename, (unsigned int)xx);
265                                         status= ERROR;
266                                 }
267                                 sample_rate= xx;
268                         }
269
270                         /* skip any extra data in the COMM chunk */
271                         FLAC__ASSERT(skip<=LONG_MAX);
272                         while(status==NORMAL && skip>0U && fseek(infile, skip, SEEK_CUR)<0) {
273                                 unsigned int need= min(skip, sizeof ucbuffer);
274                                 if(fread(ucbuffer, 1U, need, infile)<need) {
275                                         fprintf(stderr, "%s: ERROR during read while skipping extra COMM data\n", encoder_wrapper.inbasefilename);
276                                         status= ERROR;
277                                 }
278                                 skip-= need;
279                         }
280
281                         got_comm_chunk= true;
282                 }
283                 else if(status==NORMAL && got_ssnd_chunk==false && !strncmp(chunk_id, "SSND", 4)) { /* sound data chunk */
284                         unsigned int offset= 0U, block_size= 0U, align_remainder= 0U, data_bytes;
285                         size_t bytes_per_frame= channels*(bps>>3);
286                         FLAC__bool pad= false;
287
288                         if(status==NORMAL && got_comm_chunk==false) {
289                                 fprintf(stderr, "%s: ERROR: got 'SSND' chunk before 'COMM' chunk\n", encoder_wrapper.inbasefilename);
290                                 status= ERROR;
291                         }
292
293                         if(status==NORMAL) {
294                                 /* SSND chunk size */
295                                 if(!read_big_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
296                                         status= ERROR;
297                                 else if(xx!=(sample_frames*bytes_per_frame + 8U)) {
298                                         fprintf(stderr, "%s: ERROR: SSND chunk size inconsistent with sample frame count\n", encoder_wrapper.inbasefilename);
299                                         status= ERROR;
300                                 }
301                                 data_bytes= xx;
302                                 pad= (data_bytes & 1U) ? true : false;
303                         }
304
305                         if(status==NORMAL) {
306                                 /* offset */
307                                 if(!read_big_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
308                                         status= ERROR;
309                                 else if(xx!=0U) {
310                                         fprintf(stderr, "%s: ERROR: offset is %u; must be 0\n", encoder_wrapper.inbasefilename, (unsigned int)xx);
311                                         status= ERROR;
312                                 }
313                                 offset= xx;
314                         }
315
316                         if(status==NORMAL) {
317                                 /* block size */
318                                 if(!read_big_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
319                                         status= ERROR;
320                                 else if(xx!=0U) {
321                                         fprintf(stderr, "%s: ERROR: block size is %u; must be 0\n", encoder_wrapper.inbasefilename, (unsigned int)xx);
322                                         status= ERROR;
323                                 }
324                                 block_size= xx;
325                         }
326
327                         if(status==NORMAL && options.common.skip>0U) {
328                                 FLAC__uint64 remaining= options.common.skip*bytes_per_frame;
329
330                                 /* do 1<<30 bytes at a time, since 1<<30 is a nice round number, and */
331                                 /* is guaranteed to be less than LONG_MAX */
332                                 for(; remaining>0U; remaining-= remaining>(1U<<30) ? remaining : (1U<<30))
333                                 {
334                                         unsigned long skip= remaining % (1U<<30);
335
336                                         FLAC__ASSERT(skip<=LONG_MAX);
337                                         while(status==NORMAL && skip>0 && fseek(infile, skip, SEEK_CUR)<0) {
338                                                 unsigned int need= min(skip, sizeof ucbuffer);
339                                                 if(fread(ucbuffer, 1U, need, infile)<need) {
340                                                         fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_wrapper.inbasefilename);
341                                                         status= ERROR;
342                                                 }
343                                                 skip-= need;
344                                         }
345                                 }
346                         }
347
348                         if(status==NORMAL) {
349                                 data_bytes-= (8U + (unsigned int)options.common.skip*bytes_per_frame); /*@@@ WATCHOUT: 4GB limit */
350                                 encoder_wrapper.total_samples_to_encode= data_bytes/bytes_per_frame + *options.common.align_reservoir_samples;
351                                 if(options.common.sector_align) {
352                                         align_remainder= (unsigned int)(encoder_wrapper.total_samples_to_encode % 588U);
353                                         if(options.common.is_last_file)
354                                                 encoder_wrapper.total_samples_to_encode+= (588U-align_remainder); /* will pad with zeroes */
355                                         else
356                                                 encoder_wrapper.total_samples_to_encode-= align_remainder; /* will stop short and carry over to next file */
357                                 }
358
359                                 /* +54 for the size of the AIFF headers; this is just an estimate for the progress indicator and doesn't need to be exact */
360                                 encoder_wrapper.unencoded_size= encoder_wrapper.total_samples_to_encode*bytes_per_frame+54;
361
362                                 if(!init_encoder(options.common, channels, bps, sample_rate, &encoder_wrapper))
363                                         status= ERROR;
364                                 else
365                                         encoder_wrapper.verify_fifo.encode_state = ENCODER_IN_AUDIO;
366                         }
367
368                         /* first do any samples in the reservoir */
369                         if(status==NORMAL && options.common.sector_align && *options.common.align_reservoir_samples>0U) {
370                                 append_to_verify_fifo(&encoder_wrapper, (const FLAC__int32 *const *)options.common.align_reservoir, channels, *options.common.align_reservoir_samples);
371
372                                 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, (const FLAC__int32 *const *)options.common.align_reservoir, *options.common.align_reservoir_samples)) {
373                                         fprintf(stderr, "%s: ERROR during encoding, state = %d:%s\n", encoder_wrapper.inbasefilename, FLAC__stream_encoder_get_state(encoder_wrapper.encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder_wrapper.encoder)]);
374                                         status= ERROR;
375                                 }
376                         }
377
378                         /* decrement the data_bytes counter if we need to align the file */
379                         if(status==NORMAL && options.common.sector_align) {
380                                 if(options.common.is_last_file)
381                                         *options.common.align_reservoir_samples= 0U;
382                                 else {
383                                         *options.common.align_reservoir_samples= align_remainder;
384                                         data_bytes-= (*options.common.align_reservoir_samples)*bytes_per_frame;
385                                 }
386                         }
387
388                         /* now do from the file */
389                         while(status==NORMAL && data_bytes>0) {
390                                 size_t bytes_read= fread(ucbuffer, 1U, min(data_bytes, CHUNK_OF_SAMPLES*bytes_per_frame), infile);
391
392                                 if(bytes_read==0U) {
393                                         if(ferror(infile)) {
394                                                 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
395                                                 status= ERROR;
396                                         }
397                                         else if(feof(infile)) {
398                                                 fprintf(stderr, "%s: WARNING: unexpected EOF; expected %u samples, got %u samples\n", encoder_wrapper.inbasefilename, (unsigned int)encoder_wrapper.total_samples_to_encode, (unsigned int)encoder_wrapper.samples_written);
399                                                 data_bytes= 0;
400                                         }
401                                 }
402                                 else {
403                                         if(bytes_read % bytes_per_frame != 0U) {
404                                                 fprintf(stderr, "%s: ERROR: got partial sample\n", encoder_wrapper.inbasefilename);
405                                                 status= ERROR;
406                                         }
407                                         else {
408                                                 unsigned int frames= bytes_read/bytes_per_frame;
409                                                 format_input(input, frames, true, false, channels, bps, &encoder_wrapper);
410
411                                                 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, (const FLAC__int32 *const *)input, frames)) {
412                                                         fprintf(stderr, "%s: ERROR during encoding, state = %d:%s\n", encoder_wrapper.inbasefilename, FLAC__stream_encoder_get_state(encoder_wrapper.encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder_wrapper.encoder)]);
413                                                         status= ERROR;
414                                                 }
415                                                 else
416                                                         data_bytes-= bytes_read;
417                                         }
418                                 }
419                         }
420
421                         /* now read unaligned samples into reservoir or pad with zeroes if necessary */
422                         if(status==NORMAL && options.common.sector_align) {
423                                 if(options.common.is_last_file) {
424                                         unsigned int pad_frames= 588U-align_remainder;
425
426                                         if(pad_frames<588U) {
427                                                 unsigned int i;
428
429                                                 info_align_zero= pad_frames;
430                                                 for(i= 0U; i<channels; ++i)
431                                                         memset(input[i], 0, pad_frames*(bps>>3));
432                                                 append_to_verify_fifo(&encoder_wrapper, (const FLAC__int32 *const *)input, channels, pad_frames);
433
434                                                 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, (const FLAC__int32 *const *)input, pad_frames)) {
435                                                         fprintf(stderr, "%s: ERROR during encoding, state = %d:%s\n", encoder_wrapper.inbasefilename, FLAC__stream_encoder_get_state(encoder_wrapper.encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder_wrapper.encoder)]);
436                                                         status= ERROR;
437                                                 }
438                                         }
439                                 }
440                                 else {
441                                         if(*options.common.align_reservoir_samples > 0) {
442                                                 size_t bytes_read= fread(ucbuffer, 1U, (*options.common.align_reservoir_samples)*bytes_per_frame, infile);
443
444                                                 FLAC__ASSERT(CHUNK_OF_SAMPLES>=588U);
445                                                 if(bytes_read==0U && ferror(infile)) {
446                                                         fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
447                                                         status= ERROR;
448                                                 }
449                                                 else if(bytes_read != (*options.common.align_reservoir_samples) * bytes_per_frame)
450                                                         fprintf(stderr, "%s: WARNING: unexpected EOF; read %u bytes; expected %u samples, got %u samples\n", encoder_wrapper.inbasefilename, (unsigned int)bytes_read, (unsigned int)encoder_wrapper.total_samples_to_encode, (unsigned int)encoder_wrapper.samples_written);
451                                                 else {
452                                                         info_align_carry= *options.common.align_reservoir_samples;
453                                                         format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, true, false, channels, bps, &encoder_wrapper);
454                                                 }
455                                         }
456                                 }
457                         }
458
459                         if(status==NORMAL && pad==true) {
460                                 unsigned char tmp;
461
462                                 if(fread(&tmp, 1U, 1U, infile)<1U) {
463                                         fprintf(stderr, "%s: ERROR during read of SSND pad byte\n", encoder_wrapper.inbasefilename);
464                                         status= ERROR;
465                                 }
466                         }
467
468                         got_ssnd_chunk= true;
469                 }
470                 else if(status==NORMAL) { /* other chunk */
471                         if(!strncmp(chunk_id, "COMM", 4))
472                                 fprintf(stderr, "%s: WARNING: skipping extra 'COMM' chunk\n", encoder_wrapper.inbasefilename);
473                         else if(!strncmp(chunk_id, "SSND", 4))
474                                 fprintf(stderr, "%s: WARNING: skipping extra 'SSND' chunk\n", encoder_wrapper.inbasefilename);
475                         else
476                                 fprintf(stderr, "%s: WARNING: skipping unknown chunk '%s'\n", encoder_wrapper.inbasefilename, chunk_id);
477
478                         /* chunk size */
479                         if(!read_big_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
480                                 status= ERROR;
481                         else {
482                                 unsigned long skip= xx+(xx & 1U);
483
484                                 FLAC__ASSERT(skip<=LONG_MAX);
485                                 while(status==NORMAL && skip>0U && fseek(infile, skip, SEEK_CUR)<0) {
486                                         unsigned int need= min(skip, sizeof ucbuffer);
487                                         if(fread(ucbuffer, 1U, need, infile)<need) {
488                                                 fprintf(stderr, "%s: ERROR during read while skipping unknown chunk\n", encoder_wrapper.inbasefilename);
489                                                 status= ERROR;
490                                         }
491                                         skip-= need;
492                                 }
493                         }
494                 }
495         }
496
497         if(got_ssnd_chunk==false && sample_frames!=0U) {
498                 fprintf(stderr, "%s: ERROR: missing SSND chunk\n", encoder_wrapper.inbasefilename);
499                 status= ERROR;
500         }
501
502         if(encoder_wrapper.encoder) {
503                 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
504                 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
505 #ifdef FLAC__HAS_OGG
506                 if(encoder_wrapper.use_ogg)
507                         ogg_stream_clear(&encoder_wrapper.ogg.os);
508 #endif
509         }
510         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
511                 if(status==DONE)
512                         print_stats(&encoder_wrapper);
513                 fprintf(stderr, "\n");
514         }
515
516         if(0 != encoder_wrapper.seek_table)
517                 FLAC__metadata_object_delete(encoder_wrapper.seek_table);
518         if(options.common.verify) {
519                 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
520                 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
521                 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
522                         fprintf(stderr, "Verify FAILED! (%s)  Do not trust %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
523                         status= MISMATCH;
524                 }
525         }
526
527         if(infile != stdin)
528                 fclose(infile);
529
530         if(status==DONE) {
531                 if(info_align_carry >= 0)
532                         fprintf(stderr, "%s: INFO: sector alignment causing %d samples to be carried over\n", encoder_wrapper.inbasefilename, info_align_carry);
533                 if(info_align_zero >= 0)
534                         fprintf(stderr, "%s: INFO: sector alignment causing %d zero samples to be appended\n", encoder_wrapper.inbasefilename, info_align_zero);
535         }
536         else if(status==ERROR)
537                 unlink(outfilename);
538
539         return status==ERROR || status==MISMATCH;
540 }
541
542 int flac__encode_wav(FILE *infile, long infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, wav_encode_options_t options)
543 {
544         encoder_wrapper_struct encoder_wrapper;
545         FLAC__bool is_unsigned_samples = false;
546         unsigned channels = 0, bps = 0, sample_rate = 0, data_bytes;
547         size_t bytes_per_wide_sample, bytes_read;
548         FLAC__uint16 x;
549         FLAC__uint32 xx;
550         FLAC__bool got_fmt_chunk = false, got_data_chunk = false;
551         unsigned align_remainder = 0;
552         int info_align_carry = -1, info_align_zero = -1;
553
554         FLAC__ASSERT(!options.common.sector_align || options.common.skip == 0);
555
556         encoder_wrapper.encoder = 0;
557         encoder_wrapper.verify = options.common.verify;
558         encoder_wrapper.verbose = options.common.verbose;
559         encoder_wrapper.bytes_written = 0;
560         encoder_wrapper.samples_written = 0;
561         encoder_wrapper.stream_offset = 0;
562         encoder_wrapper.inbasefilename = flac__file_get_basename(infilename);
563         encoder_wrapper.outfilename = outfilename;
564         encoder_wrapper.seek_table = FLAC__metadata_object_new(FLAC__METADATA_TYPE_SEEKTABLE);
565         encoder_wrapper.first_seek_point_to_check = 0;
566 #ifdef FLAC__HAS_OGG
567         encoder_wrapper.use_ogg = options.common.use_ogg;
568 #endif
569         (void)infilesize;
570         (void)lookahead;
571         (void)lookahead_length;
572
573         if(0 == encoder_wrapper.seek_table) {
574                 fprintf(stderr, "%s: ERROR allocating memory for seek table\n", encoder_wrapper.inbasefilename);
575                 return 1;
576         }
577
578         if(0 == strcmp(outfilename, "-")) {
579                 encoder_wrapper.fout = file__get_binary_stdout();
580         }
581         else {
582                 if(0 == (encoder_wrapper.fout = fopen(outfilename, "wb"))) {
583                         fprintf(stderr, "%s: ERROR: can't open output file %s\n", encoder_wrapper.inbasefilename, outfilename);
584                         if(infile != stdin)
585                                 fclose(infile);
586                         return 1;
587                 }
588         }
589
590         if(!init(&encoder_wrapper))
591                 goto wav_abort_;
592
593         /*
594          * lookahead[] already has "RIFFxxxxWAVE", do sub-chunks
595          */
596         while(!feof(infile)) {
597                 if(!read_little_endian_uint32(infile, &xx, true, encoder_wrapper.inbasefilename))
598                         goto wav_abort_;
599                 if(feof(infile))
600                         break;
601                 if(xx == 0x20746d66 && !got_fmt_chunk) { /* "fmt " */
602                         /* fmt sub-chunk size */
603                         if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
604                                 goto wav_abort_;
605                         if(xx < 16) {
606                                 fprintf(stderr, "%s: ERROR: found non-standard 'fmt ' sub-chunk which has length = %u\n", encoder_wrapper.inbasefilename, (unsigned)xx);
607                                 goto wav_abort_;
608                         }
609                         else if(xx != 16 && xx != 18) {
610                                 fprintf(stderr, "%s: WARNING: found non-standard 'fmt ' sub-chunk which has length = %u\n", encoder_wrapper.inbasefilename, (unsigned)xx);
611                         }
612                         data_bytes = xx;
613                         /* compression code */
614                         if(!read_little_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
615                                 goto wav_abort_;
616                         if(x != 1) {
617                                 fprintf(stderr, "%s: ERROR: unsupported compression type %u\n", encoder_wrapper.inbasefilename, (unsigned)x);
618                                 goto wav_abort_;
619                         }
620                         /* number of channels */
621                         if(!read_little_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
622                                 goto wav_abort_;
623                         if(x == 0 || x > FLAC__MAX_CHANNELS) {
624                                 fprintf(stderr, "%s: ERROR: unsupported number channels %u\n", encoder_wrapper.inbasefilename, (unsigned)x);
625                                 goto wav_abort_;
626                         }
627                         else if(options.common.sector_align && x != 2) {
628                                 fprintf(stderr, "%s: ERROR: file has %u channels, must be 2 for --sector-align\n", encoder_wrapper.inbasefilename, (unsigned)x);
629                                 goto wav_abort_;
630                         }
631                         channels = x;
632                         /* sample rate */
633                         if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
634                                 goto wav_abort_;
635                         if(!FLAC__format_sample_rate_is_valid(xx)) {
636                                 fprintf(stderr, "%s: ERROR: unsupported sample rate %u\n", encoder_wrapper.inbasefilename, (unsigned)xx);
637                                 goto wav_abort_;
638                         }
639                         else if(options.common.sector_align && xx != 44100) {
640                                 fprintf(stderr, "%s: ERROR: file's sample rate is %u, must be 44100 for --sector-align\n", encoder_wrapper.inbasefilename, (unsigned)xx);
641                                 goto wav_abort_;
642                         }
643                         sample_rate = xx;
644                         /* avg bytes per second (ignored) */
645                         if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
646                                 goto wav_abort_;
647                         /* block align (ignored) */
648                         if(!read_little_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
649                                 goto wav_abort_;
650                         /* bits per sample */
651                         if(!read_little_endian_uint16(infile, &x, false, encoder_wrapper.inbasefilename))
652                                 goto wav_abort_;
653                         if(x != 8 && x != 16 && x != 24) {
654                                 fprintf(stderr, "%s: ERROR: unsupported bits per sample %u\n", encoder_wrapper.inbasefilename, (unsigned)x);
655                                 goto wav_abort_;
656                         }
657                         else if(options.common.sector_align && x != 16) {
658                                 fprintf(stderr, "%s: ERROR: file has %u bits per sample, must be 16 for --sector-align\n", encoder_wrapper.inbasefilename, (unsigned)x);
659                                 goto wav_abort_;
660                         }
661                         bps = x;
662                         is_unsigned_samples = (x == 8);
663
664                         /* skip any extra data in the fmt sub-chunk */
665                         data_bytes -= 16;
666                         if(data_bytes > 0) {
667                                 unsigned left, need;
668                                 for(left = data_bytes; left > 0; ) {
669                                         need = min(left, CHUNK_OF_SAMPLES);
670                                         if(fread(ucbuffer, 1U, need, infile) < need) {
671                                                 fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_wrapper.inbasefilename);
672                                                 goto wav_abort_;
673                                         }
674                                         left -= need;
675                                 }
676                         }
677
678                         got_fmt_chunk = true;
679                 }
680                 else if(xx == 0x61746164 && !got_data_chunk && got_fmt_chunk) { /* "data" */
681                         /* data size */
682                         if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
683                                 goto wav_abort_;
684                         data_bytes = xx;
685
686                         bytes_per_wide_sample = channels * (bps >> 3);
687
688                         if(options.common.skip > 0) {
689                                 if(fseek(infile, bytes_per_wide_sample * (unsigned)options.common.skip, SEEK_CUR) < 0) {
690                                         /* can't seek input, read ahead manually... */
691                                         unsigned left, need;
692                                         for(left = (unsigned)options.common.skip; left > 0; ) { /*@@@ WATCHOUT: 4GB limit */
693                                                 need = min(left, CHUNK_OF_SAMPLES);
694                                                 if(fread(ucbuffer, bytes_per_wide_sample, need, infile) < need) {
695                                                         fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_wrapper.inbasefilename);
696                                                         goto wav_abort_;
697                                                 }
698                                                 left -= need;
699                                         }
700                                 }
701                         }
702
703                         data_bytes -= (unsigned)options.common.skip * bytes_per_wide_sample; /*@@@ WATCHOUT: 4GB limit */
704                         encoder_wrapper.total_samples_to_encode = data_bytes / bytes_per_wide_sample + *options.common.align_reservoir_samples;
705                         if(options.common.sector_align) {
706                                 align_remainder = (unsigned)(encoder_wrapper.total_samples_to_encode % 588);
707                                 if(options.common.is_last_file)
708                                         encoder_wrapper.total_samples_to_encode += (588-align_remainder); /* will pad with zeroes */
709                                 else
710                                         encoder_wrapper.total_samples_to_encode -= align_remainder; /* will stop short and carry over to next file */
711                         }
712
713                         /* +44 for the size of the WAV headers; this is just an estimate for the progress indicator and doesn't need to be exact */
714                         encoder_wrapper.unencoded_size = encoder_wrapper.total_samples_to_encode * bytes_per_wide_sample + 44;
715
716                         if(!init_encoder(options.common, channels, bps, sample_rate, &encoder_wrapper))
717                                 goto wav_abort_;
718
719                         encoder_wrapper.verify_fifo.encode_state = ENCODER_IN_AUDIO;
720
721                         /*
722                          * first do any samples in the reservoir
723                          */
724                         if(options.common.sector_align && *options.common.align_reservoir_samples > 0) {
725                                 append_to_verify_fifo(&encoder_wrapper, (const FLAC__int32 * const *)options.common.align_reservoir, channels, *options.common.align_reservoir_samples);
726
727                                 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, (const FLAC__int32 * const *)options.common.align_reservoir, *options.common.align_reservoir_samples)) {
728                                         fprintf(stderr, "%s: ERROR during encoding, state = %d:%s\n", encoder_wrapper.inbasefilename, FLAC__stream_encoder_get_state(encoder_wrapper.encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder_wrapper.encoder)]);
729                                         goto wav_abort_;
730                                 }
731                         }
732
733                         /*
734                          * decrement the data_bytes counter if we need to align the file
735                          */
736                         if(options.common.sector_align) {
737                                 if(options.common.is_last_file) {
738                                         *options.common.align_reservoir_samples = 0;
739                                 }
740                                 else {
741                                         *options.common.align_reservoir_samples = align_remainder;
742                                         data_bytes -= (*options.common.align_reservoir_samples) * bytes_per_wide_sample;
743                                 }
744                         }
745
746                         /*
747                          * now do from the file
748                          */
749                         while(data_bytes > 0) {
750                                 bytes_read = fread(ucbuffer, sizeof(unsigned char), min(data_bytes, CHUNK_OF_SAMPLES * bytes_per_wide_sample), infile);
751                                 if(bytes_read == 0) {
752                                         if(ferror(infile)) {
753                                                 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
754                                                 goto wav_abort_;
755                                         }
756                                         else if(feof(infile)) {
757                                                 fprintf(stderr, "%s: WARNING: unexpected EOF; expected %u samples, got %u samples\n", encoder_wrapper.inbasefilename, (unsigned)encoder_wrapper.total_samples_to_encode, (unsigned)encoder_wrapper.samples_written);
758                                                 data_bytes = 0;
759                                         }
760                                 }
761                                 else {
762                                         if(bytes_read % bytes_per_wide_sample != 0) {
763                                                 fprintf(stderr, "%s: ERROR: got partial sample\n", encoder_wrapper.inbasefilename);
764                                                 goto wav_abort_;
765                                         }
766                                         else {
767                                                 unsigned wide_samples = bytes_read / bytes_per_wide_sample;
768                                                 format_input(input, wide_samples, false, is_unsigned_samples, channels, bps, &encoder_wrapper);
769
770                                                 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, (const FLAC__int32 * const *)input, wide_samples)) {
771                                                         fprintf(stderr, "%s: ERROR during encoding, state = %d:%s\n", encoder_wrapper.inbasefilename, FLAC__stream_encoder_get_state(encoder_wrapper.encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder_wrapper.encoder)]);
772                                                         goto wav_abort_;
773                                                 }
774                                                 data_bytes -= bytes_read;
775                                         }
776                                 }
777                         }
778
779                         /*
780                          * now read unaligned samples into reservoir or pad with zeroes if necessary
781                          */
782                         if(options.common.sector_align) {
783                                 if(options.common.is_last_file) {
784                                         unsigned wide_samples = 588 - align_remainder;
785                                         if(wide_samples < 588) {
786                                                 unsigned channel;
787
788                                                 info_align_zero = wide_samples;
789                                                 data_bytes = wide_samples * (bps >> 3);
790                                                 for(channel = 0; channel < channels; channel++)
791                                                         memset(input[channel], 0, data_bytes);
792                                                 append_to_verify_fifo(&encoder_wrapper, (const FLAC__int32 * const *)input, channels, wide_samples);
793
794                                                 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, (const FLAC__int32 * const *)input, wide_samples)) {
795                                                         fprintf(stderr, "%s: ERROR during encoding, state = %d:%s\n", encoder_wrapper.inbasefilename, FLAC__stream_encoder_get_state(encoder_wrapper.encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder_wrapper.encoder)]);
796                                                         goto wav_abort_;
797                                                 }
798                                         }
799                                 }
800                                 else {
801                                         if(*options.common.align_reservoir_samples > 0) {
802                                                 FLAC__ASSERT(CHUNK_OF_SAMPLES >= 588);
803                                                 bytes_read = fread(ucbuffer, sizeof(unsigned char), (*options.common.align_reservoir_samples) * bytes_per_wide_sample, infile);
804                                                 if(bytes_read == 0 && ferror(infile)) {
805                                                         fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
806                                                         goto wav_abort_;
807                                                 }
808                                                 else if(bytes_read != (*options.common.align_reservoir_samples) * bytes_per_wide_sample) {
809                                                         fprintf(stderr, "%s: WARNING: unexpected EOF; read %u bytes; expected %u samples, got %u samples\n", encoder_wrapper.inbasefilename, (unsigned)bytes_read, (unsigned)encoder_wrapper.total_samples_to_encode, (unsigned)encoder_wrapper.samples_written);
810                                                         data_bytes = 0;
811                                                 }
812                                                 else {
813                                                         info_align_carry = *options.common.align_reservoir_samples;
814                                                         format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, false, is_unsigned_samples, channels, bps, &encoder_wrapper);
815                                                 }
816                                         }
817                                 }
818                         }
819
820                         got_data_chunk = true;
821                 }
822                 else {
823                         if(xx == 0x20746d66 && got_fmt_chunk) { /* "fmt " */
824                                 fprintf(stderr, "%s: WARNING: skipping extra 'fmt ' sub-chunk\n", encoder_wrapper.inbasefilename);
825                         }
826                         else if(xx == 0x61746164) { /* "data" */
827                                 if(got_data_chunk) {
828                                         fprintf(stderr, "%s: WARNING: skipping extra 'data' sub-chunk\n", encoder_wrapper.inbasefilename);
829                                 }
830                                 else if(!got_fmt_chunk) {
831                                         fprintf(stderr, "%s: ERROR: got 'data' sub-chunk before 'fmt' sub-chunk\n", encoder_wrapper.inbasefilename);
832                                         goto wav_abort_;
833                                 }
834                                 else {
835                                         FLAC__ASSERT(0);
836                                 }
837                         }
838                         else {
839                                 fprintf(stderr, "%s: WARNING: skipping unknown sub-chunk '%c%c%c%c'\n", encoder_wrapper.inbasefilename, (char)(xx&255), (char)((xx>>8)&255), (char)((xx>>16)&255), (char)(xx>>24));
840                         }
841                         /* sub-chunk size */
842                         if(!read_little_endian_uint32(infile, &xx, false, encoder_wrapper.inbasefilename))
843                                 goto wav_abort_;
844                         if(fseek(infile, xx, SEEK_CUR) < 0) {
845                                 /* can't seek input, read ahead manually... */
846                                 unsigned left, need;
847                                 const unsigned chunk = sizeof(ucbuffer);
848                                 for(left = xx; left > 0; ) {
849                                         need = min(left, chunk);
850                                         if(fread(ucbuffer, 1, need, infile) < need) {
851                                                 fprintf(stderr, "%s: ERROR during read while skipping unsupported sub-chunk\n", encoder_wrapper.inbasefilename);
852                                                 goto wav_abort_;
853                                         }
854                                         left -= need;
855                                 }
856                         }
857                 }
858         }
859
860         if(encoder_wrapper.encoder) {
861                 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
862                 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
863 #ifdef FLAC__HAS_OGG
864                 if(encoder_wrapper.use_ogg)
865                         ogg_stream_clear(&encoder_wrapper.ogg.os);
866 #endif
867         }
868         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
869                 print_stats(&encoder_wrapper);
870                 fprintf(stderr, "\n");
871         }
872         if(0 != encoder_wrapper.seek_table)
873                 FLAC__metadata_object_delete(encoder_wrapper.seek_table);
874         if(options.common.verify) {
875                 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
876                 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
877                 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
878                         fprintf(stderr, "Verify FAILED! (%s)  Do not trust %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
879                         return 1;
880                 }
881         }
882         if(info_align_carry >= 0)
883                 fprintf(stderr, "%s: INFO: sector alignment causing %d samples to be carried over\n", encoder_wrapper.inbasefilename, info_align_carry);
884         if(info_align_zero >= 0)
885                 fprintf(stderr, "%s: INFO: sector alignment causing %d zero samples to be appended\n", encoder_wrapper.inbasefilename, info_align_zero);
886         if(infile != stdin)
887                 fclose(infile);
888         return 0;
889 wav_abort_:
890         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0)
891                 fprintf(stderr, "\n");
892         if(encoder_wrapper.encoder) {
893                 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
894                 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
895 #ifdef FLAC__HAS_OGG
896                 if(encoder_wrapper.use_ogg)
897                         ogg_stream_clear(&encoder_wrapper.ogg.os);
898 #endif
899         }
900         if(0 != encoder_wrapper.seek_table)
901                 FLAC__metadata_object_delete(encoder_wrapper.seek_table);
902         if(options.common.verify) {
903                 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
904                 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
905                 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
906                         fprintf(stderr, "Verify FAILED! (%s)  Do not trust %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
907                         return 1;
908                 }
909         }
910         if(infile != stdin)
911                 fclose(infile);
912         unlink(outfilename);
913         return 1;
914 }
915
916 int flac__encode_raw(FILE *infile, long infilesize, const char *infilename, const char *outfilename, const FLAC__byte *lookahead, unsigned lookahead_length, raw_encode_options_t options)
917 {
918         encoder_wrapper_struct encoder_wrapper;
919         size_t bytes_read;
920         const size_t bytes_per_wide_sample = options.channels * (options.bps >> 3);
921         unsigned align_remainder = 0;
922         int info_align_carry = -1, info_align_zero = -1;
923
924         FLAC__ASSERT(!options.common.sector_align || options.common.skip == 0);
925         FLAC__ASSERT(!options.common.sector_align || options.channels == 2);
926         FLAC__ASSERT(!options.common.sector_align || options.bps == 16);
927         FLAC__ASSERT(!options.common.sector_align || options.sample_rate == 44100);
928         FLAC__ASSERT(!options.common.sector_align || infilesize >= 0);
929
930         encoder_wrapper.encoder = 0;
931         encoder_wrapper.verify = options.common.verify;
932         encoder_wrapper.verbose = options.common.verbose;
933         encoder_wrapper.bytes_written = 0;
934         encoder_wrapper.samples_written = 0;
935         encoder_wrapper.stream_offset = 0;
936         encoder_wrapper.inbasefilename = flac__file_get_basename(infilename);
937         encoder_wrapper.outfilename = outfilename;
938         encoder_wrapper.seek_table = FLAC__metadata_object_new(FLAC__METADATA_TYPE_SEEKTABLE);
939         encoder_wrapper.first_seek_point_to_check = 0;
940 #ifdef FLAC__HAS_OGG
941         encoder_wrapper.use_ogg = options.common.use_ogg;
942 #endif
943
944         if(0 == encoder_wrapper.seek_table) {
945                 fprintf(stderr, "%s: ERROR allocating memory for seek table\n", encoder_wrapper.inbasefilename);
946                 return 1;
947         }
948
949         if(0 == strcmp(outfilename, "-")) {
950                 encoder_wrapper.fout = file__get_binary_stdout();
951         }
952         else {
953                 if(0 == (encoder_wrapper.fout = fopen(outfilename, "wb"))) {
954                         fprintf(stderr, "ERROR: can't open output file %s\n", outfilename);
955                         if(infile != stdin)
956                                 fclose(infile);
957                         return 1;
958                 }
959         }
960
961         if(!init(&encoder_wrapper))
962                 goto raw_abort_;
963
964         /* get the file length */
965         if(infilesize < 0) {
966                 encoder_wrapper.total_samples_to_encode = encoder_wrapper.unencoded_size = 0;
967         }
968         else {
969                 if(options.common.sector_align) {
970                         FLAC__ASSERT(options.common.skip == 0);
971                         encoder_wrapper.total_samples_to_encode = (unsigned)infilesize / bytes_per_wide_sample + *options.common.align_reservoir_samples;
972                         align_remainder = (unsigned)(encoder_wrapper.total_samples_to_encode % 588);
973                         if(options.common.is_last_file)
974                                 encoder_wrapper.total_samples_to_encode += (588-align_remainder); /* will pad with zeroes */
975                         else
976                                 encoder_wrapper.total_samples_to_encode -= align_remainder; /* will stop short and carry over to next file */
977                 }
978                 else {
979                         encoder_wrapper.total_samples_to_encode = (unsigned)infilesize / bytes_per_wide_sample - options.common.skip;
980                 }
981
982                 encoder_wrapper.unencoded_size = encoder_wrapper.total_samples_to_encode * bytes_per_wide_sample;
983         }
984
985         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode <= 0)
986                 fprintf(stderr, "(No runtime statistics possible; please wait for encoding to finish...)\n");
987
988         if(options.common.skip > 0) {
989                 unsigned skip_bytes = bytes_per_wide_sample * (unsigned)options.common.skip;
990                 if(skip_bytes > lookahead_length) {
991                         skip_bytes -= lookahead_length;
992                         lookahead_length = 0;
993                         if(fseek(infile, (long)skip_bytes, SEEK_CUR) < 0) {
994                                 /* can't seek input, read ahead manually... */
995                                 unsigned left, need;
996                                 const unsigned chunk = sizeof(ucbuffer);
997                                 for(left = skip_bytes; left > 0; ) {
998                                         need = min(left, chunk);
999                                         if(fread(ucbuffer, 1, need, infile) < need) {
1000                                                 fprintf(stderr, "%s: ERROR during read while skipping samples\n", encoder_wrapper.inbasefilename);
1001                                                 goto raw_abort_;
1002                                         }
1003                                         left -= need;
1004                                 }
1005                         }
1006                 }
1007                 else {
1008                         lookahead += skip_bytes;
1009                         lookahead_length -= skip_bytes;
1010                 }
1011         }
1012
1013         if(!init_encoder(options.common, options.channels, options.bps, options.sample_rate, &encoder_wrapper))
1014                 goto raw_abort_;
1015
1016         encoder_wrapper.verify_fifo.encode_state = ENCODER_IN_AUDIO;
1017
1018         /*
1019          * first do any samples in the reservoir
1020          */
1021         if(options.common.sector_align && *options.common.align_reservoir_samples > 0) {
1022                 append_to_verify_fifo(&encoder_wrapper, (const FLAC__int32 * const *)options.common.align_reservoir, options.channels, *options.common.align_reservoir_samples);
1023
1024                 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, (const FLAC__int32 * const *)options.common.align_reservoir, *options.common.align_reservoir_samples)) {
1025                         fprintf(stderr, "%s: ERROR during encoding, state = %d:%s\n", encoder_wrapper.inbasefilename, FLAC__stream_encoder_get_state(encoder_wrapper.encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder_wrapper.encoder)]);
1026                         goto raw_abort_;
1027                 }
1028         }
1029
1030         /*
1031          * decrement infilesize if we need to align the file
1032          */
1033         if(options.common.sector_align) {
1034                 FLAC__ASSERT(infilesize >= 0);
1035                 if(options.common.is_last_file) {
1036                         *options.common.align_reservoir_samples = 0;
1037                 }
1038                 else {
1039                         *options.common.align_reservoir_samples = align_remainder;
1040                         infilesize -= (long)((*options.common.align_reservoir_samples) * bytes_per_wide_sample);
1041                 }
1042         }
1043
1044         /*
1045          * now do from the file
1046          */
1047         while(!feof(infile)) {
1048                 if(lookahead_length > 0) {
1049                         FLAC__ASSERT(lookahead_length < CHUNK_OF_SAMPLES * bytes_per_wide_sample);
1050                         memcpy(ucbuffer, lookahead, lookahead_length);
1051                         bytes_read = fread(ucbuffer+lookahead_length, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample - lookahead_length, infile) + lookahead_length;
1052                         if(ferror(infile)) {
1053                                 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
1054                                 goto raw_abort_;
1055                         }
1056                         lookahead_length = 0;
1057                 }
1058                 else
1059                         bytes_read = fread(ucbuffer, sizeof(unsigned char), CHUNK_OF_SAMPLES * bytes_per_wide_sample, infile);
1060
1061                 if(bytes_read == 0) {
1062                         if(ferror(infile)) {
1063                                 fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
1064                                 goto raw_abort_;
1065                         }
1066                 }
1067                 else if(bytes_read % bytes_per_wide_sample != 0) {
1068                         fprintf(stderr, "%s: ERROR: got partial sample\n", encoder_wrapper.inbasefilename);
1069                         goto raw_abort_;
1070                 }
1071                 else {
1072                         unsigned wide_samples = bytes_read / bytes_per_wide_sample;
1073                         format_input(input, wide_samples, options.is_big_endian, options.is_unsigned_samples, options.channels, options.bps, &encoder_wrapper);
1074
1075                         if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, (const FLAC__int32 * const *)input, wide_samples)) {
1076                                 fprintf(stderr, "%s: ERROR during encoding, state = %d:%s\n", encoder_wrapper.inbasefilename, FLAC__stream_encoder_get_state(encoder_wrapper.encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder_wrapper.encoder)]);
1077                                 goto raw_abort_;
1078                         }
1079                 }
1080         }
1081
1082         /*
1083          * now read unaligned samples into reservoir or pad with zeroes if necessary
1084          */
1085         if(options.common.sector_align) {
1086                 if(options.common.is_last_file) {
1087                         unsigned wide_samples = 588 - align_remainder;
1088                         if(wide_samples < 588) {
1089                                 unsigned channel, data_bytes;
1090
1091                                 info_align_zero = wide_samples;
1092                                 data_bytes = wide_samples * (options.bps >> 3);
1093                                 for(channel = 0; channel < options.channels; channel++)
1094                                         memset(input[channel], 0, data_bytes);
1095                                 append_to_verify_fifo(&encoder_wrapper, (const FLAC__int32 * const *)input, options.channels, wide_samples);
1096
1097                                 if(!FLAC__stream_encoder_process(encoder_wrapper.encoder, (const FLAC__int32 * const *)input, wide_samples)) {
1098                                         fprintf(stderr, "%s: ERROR during encoding, state = %d:%s\n", encoder_wrapper.inbasefilename, FLAC__stream_encoder_get_state(encoder_wrapper.encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder_wrapper.encoder)]);
1099                                         goto raw_abort_;
1100                                 }
1101                         }
1102                 }
1103                 else {
1104                         if(*options.common.align_reservoir_samples > 0) {
1105                                 FLAC__ASSERT(CHUNK_OF_SAMPLES >= 588);
1106                                 bytes_read = fread(ucbuffer, sizeof(unsigned char), (*options.common.align_reservoir_samples) * bytes_per_wide_sample, infile);
1107                                 if(bytes_read == 0 && ferror(infile)) {
1108                                         fprintf(stderr, "%s: ERROR during read\n", encoder_wrapper.inbasefilename);
1109                                         goto raw_abort_;
1110                                 }
1111                                 else if(bytes_read != (*options.common.align_reservoir_samples) * bytes_per_wide_sample) {
1112                                         fprintf(stderr, "%s: WARNING: unexpected EOF; read %u bytes; expected %u samples, got %u samples\n", encoder_wrapper.inbasefilename, (unsigned)bytes_read, (unsigned)encoder_wrapper.total_samples_to_encode, (unsigned)encoder_wrapper.samples_written);
1113                                 }
1114                                 else {
1115                                         info_align_carry = *options.common.align_reservoir_samples;
1116                                         format_input(options.common.align_reservoir, *options.common.align_reservoir_samples, false, options.is_unsigned_samples, options.channels, options.bps, &encoder_wrapper);
1117                                 }
1118                         }
1119                 }
1120         }
1121
1122         if(encoder_wrapper.encoder) {
1123                 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
1124                 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
1125 #ifdef FLAC__HAS_OGG
1126                 if(encoder_wrapper.use_ogg)
1127                         ogg_stream_clear(&encoder_wrapper.ogg.os);
1128 #endif
1129         }
1130         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0) {
1131                 print_stats(&encoder_wrapper);
1132                 fprintf(stderr, "\n");
1133         }
1134         if(0 != encoder_wrapper.seek_table)
1135                 FLAC__metadata_object_delete(encoder_wrapper.seek_table);
1136         if(options.common.verify) {
1137                 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
1138                 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
1139                 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
1140                         fprintf(stderr, "Verify FAILED! (%s)  Do not trust %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
1141                         return 1;
1142                 }
1143         }
1144         if(info_align_carry >= 0)
1145                 fprintf(stderr, "%s: INFO: sector alignment causing %d samples to be carried over\n", encoder_wrapper.inbasefilename, info_align_carry);
1146         if(info_align_zero >= 0)
1147                 fprintf(stderr, "%s: INFO: sector alignment causing %d zero samples to be appended\n", encoder_wrapper.inbasefilename, info_align_zero);
1148         if(infile != stdin)
1149                 fclose(infile);
1150         return 0;
1151 raw_abort_:
1152         if(encoder_wrapper.verbose && encoder_wrapper.total_samples_to_encode > 0)
1153                 fprintf(stderr, "\n");
1154         if(encoder_wrapper.encoder) {
1155                 FLAC__stream_encoder_finish(encoder_wrapper.encoder);
1156                 FLAC__stream_encoder_delete(encoder_wrapper.encoder);
1157 #ifdef FLAC__HAS_OGG
1158                 if(encoder_wrapper.use_ogg)
1159                         ogg_stream_clear(&encoder_wrapper.ogg.os);
1160 #endif
1161         }
1162         if(0 != encoder_wrapper.seek_table)
1163                 FLAC__metadata_object_delete(encoder_wrapper.seek_table);
1164         if(options.common.verify) {
1165                 FLAC__stream_decoder_finish(encoder_wrapper.verify_fifo.decoder);
1166                 FLAC__stream_decoder_delete(encoder_wrapper.verify_fifo.decoder);
1167                 if(encoder_wrapper.verify_fifo.result != FLAC__VERIFY_OK) {
1168                         fprintf(stderr, "Verify FAILED! (%s)  Do not trust %s\n", verify_code_string[encoder_wrapper.verify_fifo.result], outfilename);
1169                         return 1;
1170                 }
1171         }
1172         if(infile != stdin)
1173                 fclose(infile);
1174         unlink(outfilename);
1175         return 1;
1176 }
1177
1178 FLAC__bool init(encoder_wrapper_struct *encoder_wrapper)
1179 {
1180         unsigned i;
1181         FLAC__uint32 test = 1;
1182
1183         is_big_endian_host = (*((FLAC__byte*)(&test)))? false : true;
1184
1185         for(i = 0; i < FLAC__MAX_CHANNELS; i++)
1186                 input[i] = &(in[i][0]);
1187
1188         encoder_wrapper->encoder = FLAC__stream_encoder_new();
1189         if(0 == encoder_wrapper->encoder) {
1190                 fprintf(stderr, "%s: ERROR creating the encoder instance\n", encoder_wrapper->inbasefilename);
1191                 return false;
1192         }
1193
1194 #ifdef FLAC__HAS_OGG
1195         if(encoder_wrapper->use_ogg) {
1196                 if(ogg_stream_init(&encoder_wrapper->ogg.os, 0) != 0) {
1197                         fprintf(stderr, "%s: ERROR initializing the Ogg stream\n", encoder_wrapper->inbasefilename);
1198                         FLAC__stream_encoder_delete(encoder_wrapper->encoder);
1199                         return false;
1200                 }
1201         }
1202 #endif
1203
1204         return true;
1205 }
1206
1207 FLAC__bool init_encoder(encode_options_t options, unsigned channels, unsigned bps, unsigned sample_rate, encoder_wrapper_struct *encoder_wrapper)
1208 {
1209         unsigned i, num_metadata;
1210         FLAC__StreamMetadata padding;
1211         FLAC__StreamMetadata *metadata[2];
1212
1213         if(channels != 2)
1214                 options.do_mid_side = options.loose_mid_side = false;
1215
1216         if(encoder_wrapper->verify) {
1217                 /* set up the fifo which will hold the original signal to compare against */
1218                 encoder_wrapper->verify_fifo.size = options.blocksize + CHUNK_OF_SAMPLES;
1219                 for(i = 0; i < channels; i++) {
1220                         if(0 == (encoder_wrapper->verify_fifo.original[i] = (FLAC__int32*)malloc(sizeof(FLAC__int32) * encoder_wrapper->verify_fifo.size))) {
1221                                 fprintf(stderr, "%s: ERROR allocating verify buffers\n", encoder_wrapper->inbasefilename);
1222                                 return false;
1223                         }
1224                 }
1225                 encoder_wrapper->verify_fifo.tail = 0;
1226                 encoder_wrapper->verify_fifo.encode_state = ENCODER_IN_MAGIC;
1227                 encoder_wrapper->verify_fifo.result = FLAC__VERIFY_OK;
1228
1229                 /* set up a stream decoder for verification */
1230                 encoder_wrapper->verify_fifo.decoder = FLAC__stream_decoder_new();
1231                 if(0 == encoder_wrapper->verify_fifo.decoder) {
1232                         fprintf(stderr, "%s: ERROR creating the verify decoder instance\n", encoder_wrapper->inbasefilename);
1233                         return false;
1234                 }
1235                 FLAC__stream_decoder_set_read_callback(encoder_wrapper->verify_fifo.decoder, verify_read_callback);
1236                 FLAC__stream_decoder_set_write_callback(encoder_wrapper->verify_fifo.decoder, verify_write_callback);
1237                 FLAC__stream_decoder_set_metadata_callback(encoder_wrapper->verify_fifo.decoder, verify_metadata_callback);
1238                 FLAC__stream_decoder_set_error_callback(encoder_wrapper->verify_fifo.decoder, verify_error_callback);
1239                 FLAC__stream_decoder_set_client_data(encoder_wrapper->verify_fifo.decoder, encoder_wrapper);
1240                 if(FLAC__stream_decoder_init(encoder_wrapper->verify_fifo.decoder) != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA) {
1241                         fprintf(stderr, "%s: ERROR initializing decoder, state = %d:%s\n", encoder_wrapper->inbasefilename, FLAC__stream_decoder_get_state(encoder_wrapper->verify_fifo.decoder), FLAC__StreamDecoderStateString[FLAC__stream_decoder_get_state(encoder_wrapper->verify_fifo.decoder)]);
1242                         return false;
1243                 }
1244         }
1245
1246         if(!convert_to_seek_table(options.requested_seek_points, options.num_requested_seek_points, encoder_wrapper->total_samples_to_encode, encoder_wrapper->seek_table)) {
1247                 fprintf(stderr, "%s: ERROR allocating memory for seek table\n", encoder_wrapper->inbasefilename);
1248                 return false;
1249         }
1250
1251         num_metadata = 0;
1252         if(encoder_wrapper->seek_table->data.seek_table.num_points > 0) {
1253                 encoder_wrapper->seek_table->is_last = false; /* the encoder will set this for us */
1254                 metadata[num_metadata++] = encoder_wrapper->seek_table;
1255         }
1256         if(options.padding > 0) {
1257                 padding.is_last = false; /* the encoder will set this for us */
1258                 padding.type = FLAC__METADATA_TYPE_PADDING;
1259                 padding.length = (unsigned)options.padding;
1260                 metadata[num_metadata++] = &padding;
1261         }
1262
1263         FLAC__stream_encoder_set_streamable_subset(encoder_wrapper->encoder, !options.lax);
1264         FLAC__stream_encoder_set_do_mid_side_stereo(encoder_wrapper->encoder, options.do_mid_side);
1265         FLAC__stream_encoder_set_loose_mid_side_stereo(encoder_wrapper->encoder, options.loose_mid_side);
1266         FLAC__stream_encoder_set_channels(encoder_wrapper->encoder, channels);
1267         FLAC__stream_encoder_set_bits_per_sample(encoder_wrapper->encoder, bps);
1268         FLAC__stream_encoder_set_sample_rate(encoder_wrapper->encoder, sample_rate);
1269         FLAC__stream_encoder_set_blocksize(encoder_wrapper->encoder, options.blocksize);
1270         FLAC__stream_encoder_set_max_lpc_order(encoder_wrapper->encoder, options.max_lpc_order);
1271         FLAC__stream_encoder_set_qlp_coeff_precision(encoder_wrapper->encoder, options.qlp_coeff_precision);
1272         FLAC__stream_encoder_set_do_qlp_coeff_prec_search(encoder_wrapper->encoder, options.do_qlp_coeff_prec_search);
1273         FLAC__stream_encoder_set_do_escape_coding(encoder_wrapper->encoder, options.do_escape_coding);
1274         FLAC__stream_encoder_set_do_exhaustive_model_search(encoder_wrapper->encoder, options.do_exhaustive_model_search);
1275         FLAC__stream_encoder_set_min_residual_partition_order(encoder_wrapper->encoder, options.min_residual_partition_order);
1276         FLAC__stream_encoder_set_max_residual_partition_order(encoder_wrapper->encoder, options.max_residual_partition_order);
1277         FLAC__stream_encoder_set_rice_parameter_search_dist(encoder_wrapper->encoder, options.rice_parameter_search_dist);
1278         FLAC__stream_encoder_set_total_samples_estimate(encoder_wrapper->encoder, encoder_wrapper->total_samples_to_encode);
1279         FLAC__stream_encoder_set_metadata(encoder_wrapper->encoder, (num_metadata > 0)? metadata : 0, num_metadata);
1280         FLAC__stream_encoder_set_write_callback(encoder_wrapper->encoder, write_callback);
1281         FLAC__stream_encoder_set_metadata_callback(encoder_wrapper->encoder, metadata_callback);
1282         FLAC__stream_encoder_set_client_data(encoder_wrapper->encoder, encoder_wrapper);
1283
1284         if(FLAC__stream_encoder_init(encoder_wrapper->encoder) != FLAC__STREAM_ENCODER_OK) {
1285                 fprintf(stderr, "%s: ERROR initializing encoder, state = %d:%s\n", encoder_wrapper->inbasefilename, FLAC__stream_encoder_get_state(encoder_wrapper->encoder), FLAC__StreamEncoderStateString[FLAC__stream_encoder_get_state(encoder_wrapper->encoder)]);
1286                 return false;
1287         }
1288
1289         /* the above call writes all the metadata, so we save the stream offset now */
1290         encoder_wrapper->stream_offset = encoder_wrapper->bytes_written;
1291
1292         return true;
1293 }
1294
1295 FLAC__bool convert_to_seek_table(char *requested_seek_points, int num_requested_seek_points, FLAC__uint64 stream_samples, FLAC__StreamMetadata *seek_table)
1296 {
1297         unsigned i, real_points, placeholders;
1298         char *pt = requested_seek_points, *q;
1299
1300         if(num_requested_seek_points == 0)
1301                 return true;
1302
1303         if(num_requested_seek_points < 0) {
1304                 strcpy(requested_seek_points, "100x<");
1305                 num_requested_seek_points = 1;
1306         }
1307
1308         /* first count how many individual seek points we may need */
1309         real_points = placeholders = 0;
1310         for(i = 0; i < (unsigned)num_requested_seek_points; i++) {
1311                 q = strchr(pt, '<');
1312                 FLAC__ASSERT(0 != q);
1313                 *q = '\0';
1314
1315                 if(0 == strcmp(pt, "X")) { /* -S X */
1316                         placeholders++;
1317                 }
1318                 else if(pt[strlen(pt)-1] == 'x') { /* -S #x */
1319                         if(stream_samples > 0) /* we can only do these if we know the number of samples to encode up front */
1320                                 real_points += (unsigned)atoi(pt);
1321                 }
1322                 else { /* -S # */
1323                         real_points++;
1324                 }
1325                 *q++ = '<';
1326
1327                 pt = q;
1328         }
1329         pt = requested_seek_points;
1330
1331         for(i = 0; i < (unsigned)num_requested_seek_points; i++) {
1332                 q = strchr(pt, '<');
1333                 FLAC__ASSERT(0 != q);
1334                 *q++ = '\0';
1335
1336                 if(0 == strcmp(pt, "X")) { /* -S X */
1337                         if(!FLAC__metadata_object_seektable_template_append_placeholders(seek_table, 1))
1338                                 return false;
1339                 }
1340                 else if(pt[strlen(pt)-1] == 'x') { /* -S #x */
1341                         if(stream_samples > 0) { /* we can only do these if we know the number of samples to encode up front */
1342                                 if(!FLAC__metadata_object_seektable_template_append_spaced_points(seek_table, atoi(pt), stream_samples))
1343                                         return false;
1344                         }
1345                 }
1346                 else { /* -S # */
1347                         FLAC__uint64 n = (unsigned)atoi(pt);
1348                         if(!FLAC__metadata_object_seektable_template_append_point(seek_table, n))
1349                                 return false;
1350                 }
1351
1352                 pt = q;
1353         }
1354
1355         if(!FLAC__metadata_object_seektable_template_sort(seek_table, /*compact=*/true))
1356                 return false;
1357
1358         return true;
1359 }
1360
1361 void format_input(FLAC__int32 *dest[], unsigned wide_samples, FLAC__bool is_big_endian, FLAC__bool is_unsigned_samples, unsigned channels, unsigned bps, encoder_wrapper_struct *encoder_wrapper)
1362 {
1363         unsigned wide_sample, sample, channel, byte;
1364
1365         if(bps == 8) {
1366                 if(is_unsigned_samples) {
1367                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1368                                 for(channel = 0; channel < channels; channel++, sample++)
1369                                         dest[channel][wide_sample] = (FLAC__int32)ucbuffer[sample] - 0x80;
1370                 }
1371                 else {
1372                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1373                                 for(channel = 0; channel < channels; channel++, sample++)
1374                                         dest[channel][wide_sample] = (FLAC__int32)scbuffer[sample];
1375                 }
1376         }
1377         else if(bps == 16) {
1378                 if(is_big_endian != is_big_endian_host) {
1379                         unsigned char tmp;
1380                         const unsigned bytes = wide_samples * channels * (bps >> 3);
1381                         for(byte = 0; byte < bytes; byte += 2) {
1382                                 tmp = ucbuffer[byte];
1383                                 ucbuffer[byte] = ucbuffer[byte+1];
1384                                 ucbuffer[byte+1] = tmp;
1385                         }
1386                 }
1387                 if(is_unsigned_samples) {
1388                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1389                                 for(channel = 0; channel < channels; channel++, sample++)
1390                                         dest[channel][wide_sample] = (FLAC__int32)usbuffer[sample] - 0x8000;
1391                 }
1392                 else {
1393                         for(sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1394                                 for(channel = 0; channel < channels; channel++, sample++)
1395                                         dest[channel][wide_sample] = (FLAC__int32)ssbuffer[sample];
1396                 }
1397         }
1398         else if(bps == 24) {
1399                 if(!is_big_endian) {
1400                         unsigned char tmp;
1401                         const unsigned bytes = wide_samples * channels * (bps >> 3);
1402                         for(byte = 0; byte < bytes; byte += 3) {
1403                                 tmp = ucbuffer[byte];
1404                                 ucbuffer[byte] = ucbuffer[byte+2];
1405                                 ucbuffer[byte+2] = tmp;
1406                         }
1407                 }
1408                 if(is_unsigned_samples) {
1409                         for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1410                                 for(channel = 0; channel < channels; channel++, sample++) {
1411                                         dest[channel][wide_sample]  = ucbuffer[byte++]; dest[channel][wide_sample] <<= 8;
1412                                         dest[channel][wide_sample] |= ucbuffer[byte++]; dest[channel][wide_sample] <<= 8;
1413                                         dest[channel][wide_sample] |= ucbuffer[byte++];
1414                                         dest[channel][wide_sample] -= 0x800000;
1415                                 }
1416                 }
1417                 else {
1418                         for(byte = sample = wide_sample = 0; wide_sample < wide_samples; wide_sample++)
1419                                 for(channel = 0; channel < channels; channel++, sample++) {
1420                                         dest[channel][wide_sample]  = scbuffer[byte++]; dest[channel][wide_sample] <<= 8;
1421                                         dest[channel][wide_sample] |= ucbuffer[byte++]; dest[channel][wide_sample] <<= 8;
1422                                         dest[channel][wide_sample] |= ucbuffer[byte++];
1423                                 }
1424                 }
1425         }
1426         else {
1427                 FLAC__ASSERT(0);
1428         }
1429
1430         append_to_verify_fifo(encoder_wrapper, (const FLAC__int32 * const *)dest, channels, wide_samples);
1431 }
1432
1433 void append_to_verify_fifo(encoder_wrapper_struct *encoder_wrapper, const FLAC__int32 * const input[], unsigned channels, unsigned wide_samples)
1434 {
1435         if(encoder_wrapper->verify) {
1436                 unsigned channel;
1437                 for(channel = 0; channel < channels; channel++)
1438                         memcpy(&encoder_wrapper->verify_fifo.original[channel][encoder_wrapper->verify_fifo.tail], input[channel], sizeof(FLAC__int32) * wide_samples);
1439                 encoder_wrapper->verify_fifo.tail += wide_samples;
1440                 FLAC__ASSERT(encoder_wrapper->verify_fifo.tail <= encoder_wrapper->verify_fifo.size);
1441         }
1442 }
1443
1444 FLAC__StreamEncoderWriteStatus write_callback(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], unsigned bytes, unsigned samples, unsigned current_frame, void *client_data)
1445 {
1446         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
1447         const unsigned mask = (FLAC__stream_encoder_get_do_exhaustive_model_search(encoder) || FLAC__stream_encoder_get_do_qlp_coeff_prec_search(encoder))? 0x1f : 0x7f;
1448
1449         /* mark the current seek point if hit (if stream_offset == 0 that means we're still writing metadata and haven't hit the first frame yet) */
1450         if(encoder_wrapper->stream_offset > 0 && encoder_wrapper->seek_table->data.seek_table.num_points > 0) {
1451                 /*@@@ WATCHOUT: assumes the encoder is fixed-blocksize, which will be true indefinitely: */
1452                 const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
1453                 const FLAC__uint64 frame_first_sample = (FLAC__uint64)current_frame * (FLAC__uint64)blocksize;
1454                 const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
1455                 FLAC__uint64 test_sample;
1456                 unsigned i;
1457                 for(i = encoder_wrapper->first_seek_point_to_check; i < encoder_wrapper->seek_table->data.seek_table.num_points; i++) {
1458                         test_sample = encoder_wrapper->seek_table->data.seek_table.points[i].sample_number;
1459                         if(test_sample > frame_last_sample) {
1460                                 break;
1461                         }
1462                         else if(test_sample >= frame_first_sample) {
1463                                 encoder_wrapper->seek_table->data.seek_table.points[i].sample_number = frame_first_sample;
1464                                 encoder_wrapper->seek_table->data.seek_table.points[i].stream_offset = encoder_wrapper->bytes_written - encoder_wrapper->stream_offset;
1465                                 encoder_wrapper->seek_table->data.seek_table.points[i].frame_samples = blocksize;
1466                                 encoder_wrapper->first_seek_point_to_check++;
1467                                 /* DO NOT: "break;" and here's why:
1468                                  * The seektable template may contain more than one target
1469                                  * sample for any given frame; we will keep looping, generating
1470                                  * duplicate seekpoints for them, and we'll clean it up later,
1471                                  * just before writing the seektable back to the metadata.
1472                                  */
1473                         }
1474                         else {
1475                                 encoder_wrapper->first_seek_point_to_check++;
1476                         }
1477                 }
1478         }
1479
1480         encoder_wrapper->bytes_written += bytes;
1481         encoder_wrapper->samples_written += samples;
1482         encoder_wrapper->current_frame = current_frame;
1483
1484         if(samples && encoder_wrapper->verbose && encoder_wrapper->total_samples_to_encode > 0 && !(current_frame & mask))
1485                 print_stats(encoder_wrapper);
1486
1487         if(encoder_wrapper->verify) {
1488                 encoder_wrapper->verify_fifo.encoded_signal = buffer;
1489                 encoder_wrapper->verify_fifo.encoded_bytes = bytes;
1490                 if(encoder_wrapper->verify_fifo.encode_state > ENCODER_IN_MAGIC) {
1491                         if(!FLAC__stream_decoder_process_single(encoder_wrapper->verify_fifo.decoder)) {
1492                                 encoder_wrapper->verify_fifo.result = encoder_wrapper->verify_fifo.encode_state > ENCODER_IN_METADATA? FLAC__VERIFY_FAILED_IN_FRAME : FLAC__VERIFY_FAILED_IN_METADATA;
1493
1494                                 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
1495                         }
1496                 }
1497                 else {
1498                         encoder_wrapper->verify_fifo.encode_state = ENCODER_IN_METADATA;
1499                         encoder_wrapper->verify_fifo.needs_magic_hack = true;
1500                 }
1501         }
1502
1503 #ifdef FLAC__HAS_OGG
1504         if(encoder_wrapper->use_ogg) {
1505                 ogg_packet op;
1506
1507                 memset(&op, 0, sizeof(op));
1508                 op.packet = (unsigned char *)buffer;
1509                 op.granulepos = encoder_wrapper->samples_written - 1;
1510                 /*@@@ WATCHOUT:
1511                  * this depends on the behavior of libFLAC that we will get one
1512                  * write_callback first with all the metadata (and 'samples'
1513                  * will be 0), then one write_callback for each frame.
1514                  */
1515                 op.packetno = (samples == 0? -1 : (int)encoder_wrapper->current_frame);
1516                 op.bytes = bytes;
1517
1518                 if (encoder_wrapper->bytes_written == bytes)
1519                         op.b_o_s = 1;
1520
1521                 if (encoder_wrapper->total_samples_to_encode == encoder_wrapper->samples_written)
1522                         op.e_o_s = 1;
1523
1524                 ogg_stream_packetin(&encoder_wrapper->ogg.os, &op);
1525
1526                 while(ogg_stream_pageout(&encoder_wrapper->ogg.os, &encoder_wrapper->ogg.og) != 0) {
1527                         int written;
1528                         written = fwrite(encoder_wrapper->ogg.og.header, 1, encoder_wrapper->ogg.og.header_len, encoder_wrapper->fout);
1529                         if (written != encoder_wrapper->ogg.og.header_len)
1530                                 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
1531
1532                         written = fwrite(encoder_wrapper->ogg.og.body, 1, encoder_wrapper->ogg.og.body_len, encoder_wrapper->fout);
1533                         if (written != encoder_wrapper->ogg.og.body_len)
1534                                 return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
1535                 }
1536
1537                 return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
1538         }
1539         else
1540 #endif
1541         {
1542                 if(fwrite(buffer, sizeof(FLAC__byte), bytes, encoder_wrapper->fout) == bytes)
1543                         return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
1544                 else
1545                         return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
1546         }
1547 }
1548
1549 void metadata_callback(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data)
1550 {
1551         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
1552         FLAC__byte b;
1553         FILE *f = encoder_wrapper->fout;
1554         const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
1555         const unsigned min_framesize = metadata->data.stream_info.min_framesize;
1556         const unsigned max_framesize = metadata->data.stream_info.max_framesize;
1557
1558         FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
1559
1560         /*
1561          * If we are writing to an ogg stream, there is no need to go back
1562          * and update the STREAMINFO or SEEKTABLE blocks; the values we would
1563          * update are not necessary with Ogg as the transport.  We can't do
1564          * it reliably anyway without knowing the Ogg structure.
1565          */
1566 #ifdef FLAC__HAS_OGG
1567         if(encoder_wrapper->use_ogg)
1568                 return;
1569 #endif
1570
1571         /*
1572          * we get called by the encoder when the encoding process has
1573          * finished so that we can update the STREAMINFO and SEEKTABLE
1574          * blocks.
1575          */
1576
1577         (void)encoder; /* silence compiler warning about unused parameter */
1578
1579         if(f != stdout) {
1580                 fclose(encoder_wrapper->fout);
1581                 if(0 == (f = fopen(encoder_wrapper->outfilename, "r+b")))
1582                         return;
1583         }
1584
1585         /* all this is based on intimate knowledge of the stream header
1586          * layout, but a change to the header format that would break this
1587          * would also break all streams encoded in the previous format.
1588          */
1589
1590         if(-1 == fseek(f, 26, SEEK_SET)) goto end_;
1591         fwrite(metadata->data.stream_info.md5sum, 1, 16, f);
1592
1593         /* if we get this far we know we can seek so no need to check the
1594          * return value from fseek()
1595          */
1596         fseek(f, 21, SEEK_SET);
1597         if(fread(&b, 1, 1, f) != 1) goto framesize_;
1598         fseek(f, 21, SEEK_SET);
1599         b = (b & 0xf0) | (FLAC__byte)((samples >> 32) & 0x0F);
1600         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1601         b = (FLAC__byte)((samples >> 24) & 0xFF);
1602         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1603         b = (FLAC__byte)((samples >> 16) & 0xFF);
1604         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1605         b = (FLAC__byte)((samples >> 8) & 0xFF);
1606         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1607         b = (FLAC__byte)(samples & 0xFF);
1608         if(fwrite(&b, 1, 1, f) != 1) goto framesize_;
1609
1610 framesize_:
1611         fseek(f, 12, SEEK_SET);
1612         b = (FLAC__byte)((min_framesize >> 16) & 0xFF);
1613         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1614         b = (FLAC__byte)((min_framesize >> 8) & 0xFF);
1615         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1616         b = (FLAC__byte)(min_framesize & 0xFF);
1617         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1618         b = (FLAC__byte)((max_framesize >> 16) & 0xFF);
1619         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1620         b = (FLAC__byte)((max_framesize >> 8) & 0xFF);
1621         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1622         b = (FLAC__byte)(max_framesize & 0xFF);
1623         if(fwrite(&b, 1, 1, f) != 1) goto seektable_;
1624
1625 seektable_:
1626         if(encoder_wrapper->seek_table->data.seek_table.num_points > 0) {
1627                 long pos;
1628                 unsigned i;
1629
1630                 (void)FLAC__metadata_object_seektable_template_sort(encoder_wrapper->seek_table, /*compact=*/false);
1631
1632                 FLAC__ASSERT(FLAC__metadata_object_seektable_is_legal(encoder_wrapper->seek_table));
1633
1634                 /* convert any unused seek points to placeholders */
1635                 for(i = 0; i < encoder_wrapper->seek_table->data.seek_table.num_points; i++) {
1636                         if(encoder_wrapper->seek_table->data.seek_table.points[i].sample_number == FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER)
1637                                 break;
1638                         else if(encoder_wrapper->seek_table->data.seek_table.points[i].frame_samples == 0)
1639                                 encoder_wrapper->seek_table->data.seek_table.points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
1640                 }
1641
1642                 /* the offset of the seek table data 'pos' should be after then stream sync and STREAMINFO block and SEEKTABLE header */
1643                 pos = (FLAC__STREAM_SYNC_LEN + FLAC__STREAM_METADATA_IS_LAST_LEN + FLAC__STREAM_METADATA_TYPE_LEN + FLAC__STREAM_METADATA_LENGTH_LEN) / 8;
1644                 pos += metadata->length;
1645                 pos += (FLAC__STREAM_METADATA_IS_LAST_LEN + FLAC__STREAM_METADATA_TYPE_LEN + FLAC__STREAM_METADATA_LENGTH_LEN) / 8;
1646                 fseek(f, pos, SEEK_SET);
1647                 for(i = 0; i < encoder_wrapper->seek_table->data.seek_table.num_points; i++) {
1648                         if(!write_big_endian_uint64(f, encoder_wrapper->seek_table->data.seek_table.points[i].sample_number)) goto end_;
1649                         if(!write_big_endian_uint64(f, encoder_wrapper->seek_table->data.seek_table.points[i].stream_offset)) goto end_;
1650                         if(!write_big_endian_uint16(f, (FLAC__uint16)encoder_wrapper->seek_table->data.seek_table.points[i].frame_samples)) goto end_;
1651                 }
1652         }
1653
1654 end_:
1655         fclose(f);
1656         return;
1657 }
1658
1659 FLAC__StreamDecoderReadStatus verify_read_callback(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], unsigned *bytes, void *client_data)
1660 {
1661         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
1662         const unsigned encoded_bytes = encoder_wrapper->verify_fifo.encoded_bytes;
1663         (void)decoder;
1664
1665         if(encoder_wrapper->verify_fifo.needs_magic_hack) {
1666                 FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
1667                 *bytes = FLAC__STREAM_SYNC_LENGTH;
1668                 memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
1669                 encoder_wrapper->verify_fifo.needs_magic_hack = false;
1670         }
1671         else {
1672                 if(encoded_bytes <= *bytes) {
1673                         *bytes = encoded_bytes;
1674                         memcpy(buffer, encoder_wrapper->verify_fifo.encoded_signal, *bytes);
1675                 }
1676                 else {
1677                         memcpy(buffer, encoder_wrapper->verify_fifo.encoded_signal, *bytes);
1678                         encoder_wrapper->verify_fifo.encoded_signal += *bytes;
1679                         encoder_wrapper->verify_fifo.encoded_bytes -= *bytes;
1680                 }
1681         }
1682
1683         return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
1684 }
1685
1686 FLAC__StreamDecoderWriteStatus verify_write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
1687 {
1688         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
1689         unsigned channel, l, r;
1690         const unsigned channels = FLAC__stream_decoder_get_channels(decoder);
1691         const unsigned bytes_per_block = sizeof(FLAC__int32) * FLAC__stream_decoder_get_blocksize(decoder);
1692
1693         for(channel = 0; channel < channels; channel++) {
1694                 if(0 != memcmp(buffer[channel], encoder_wrapper->verify_fifo.original[channel], bytes_per_block)) {
1695                         unsigned sample = 0;
1696                         int expect = 0, got = 0;
1697                         fprintf(stderr, "\n%s: ERROR: mismatch in decoded data, verify FAILED!\n", encoder_wrapper->inbasefilename);
1698                         fprintf(stderr, "       Please submit a bug report to\n");
1699                         fprintf(stderr, "           http://sourceforge.net/bugs/?func=addbug&group_id=13478\n");
1700                         fprintf(stderr, "       Make sure to include an email contact in the comment and/or use the\n");
1701                         fprintf(stderr, "       \"Monitor\" feature to monitor the bug status.\n");
1702                         for(l = 0, r = FLAC__stream_decoder_get_blocksize(decoder); l < r; l++) {
1703                                 if(buffer[channel][l] != encoder_wrapper->verify_fifo.original[channel][l]) {
1704                                         sample = l;
1705                                         expect = (int)encoder_wrapper->verify_fifo.original[channel][l];
1706                                         got = (int)buffer[channel][l];
1707                                         break;
1708                                 }
1709                         }
1710                         FLAC__ASSERT(l < r);
1711                         FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
1712                         fprintf(stderr, "       Absolute sample=%u, frame=%u, channel=%u, sample=%u, expected %d, got %d\n", (unsigned)frame->header.number.sample_number + sample, (unsigned)frame->header.number.sample_number / FLAC__stream_decoder_get_blocksize(decoder), channel, sample, expect, got); /*@@@ WATCHOUT: 4GB limit */
1713                         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1714                 }
1715         }
1716         /* dequeue the frame from the fifo */
1717         for(channel = 0; channel < channels; channel++) {
1718                 for(l = 0, r = frame->header.blocksize; r < encoder_wrapper->verify_fifo.tail; l++, r++) {
1719                         encoder_wrapper->verify_fifo.original[channel][l] = encoder_wrapper->verify_fifo.original[channel][r];
1720                 }
1721         }
1722         encoder_wrapper->verify_fifo.tail -= frame->header.blocksize;
1723         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
1724 }
1725
1726 void verify_metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
1727 {
1728         (void)decoder;
1729         (void)metadata;
1730         (void)client_data;
1731 }
1732
1733 void verify_error_callback(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
1734 {
1735         encoder_wrapper_struct *encoder_wrapper = (encoder_wrapper_struct *)client_data;
1736         (void)decoder;
1737         fprintf(stderr, "\n%s: ERROR: verification decoder returned error %d:%s\n", encoder_wrapper->inbasefilename, status, FLAC__StreamDecoderErrorStatusString[status]);
1738 }
1739
1740 void print_stats(const encoder_wrapper_struct *encoder_wrapper)
1741 {
1742 #if defined _MSC_VER || defined __MINGW32__
1743         /* with VC++ you have to spoon feed it the casting */
1744         const double progress = (double)(FLAC__int64)encoder_wrapper->samples_written / (double)(FLAC__int64)encoder_wrapper->total_samples_to_encode;
1745         const double ratio = (double)(FLAC__int64)encoder_wrapper->bytes_written / ((double)(FLAC__int64)encoder_wrapper->unencoded_size * progress);
1746 #else
1747         const double progress = (double)encoder_wrapper->samples_written / (double)encoder_wrapper->total_samples_to_encode;
1748         const double ratio = (double)encoder_wrapper->bytes_written / ((double)encoder_wrapper->unencoded_size * progress);
1749 #endif
1750
1751         if(encoder_wrapper->samples_written == encoder_wrapper->total_samples_to_encode) {
1752                 fprintf(stderr, "\r%s:%s wrote %u bytes, ratio=%0.3f",
1753                         encoder_wrapper->inbasefilename,
1754                         encoder_wrapper->verify? (encoder_wrapper->verify_fifo.result == FLAC__VERIFY_OK? " Verify OK," : " Verify FAILED!") : "",
1755                         (unsigned)encoder_wrapper->bytes_written,
1756                         ratio
1757                 );
1758         }
1759         else {
1760                 fprintf(stderr, "\r%s: %u%% complete, ratio=%0.3f", encoder_wrapper->inbasefilename, (unsigned)floor(progress * 100.0 + 0.5), ratio);
1761         }
1762 }
1763
1764 FLAC__bool read_little_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn)
1765 {
1766         size_t bytes_read = fread(val, 1, 2, f);
1767
1768         if(bytes_read == 0) {
1769                 if(!eof_ok) {
1770                         fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1771                         return false;
1772                 }
1773                 else
1774                         return true;
1775         }
1776         else if(bytes_read < 2) {
1777                 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1778                 return false;
1779         }
1780         else {
1781                 if(is_big_endian_host) {
1782                         FLAC__byte tmp, *b = (FLAC__byte*)val;
1783                         tmp = b[1]; b[1] = b[0]; b[0] = tmp;
1784                 }
1785                 return true;
1786         }
1787 }
1788
1789 FLAC__bool read_little_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
1790 {
1791         size_t bytes_read = fread(val, 1, 4, f);
1792
1793         if(bytes_read == 0) {
1794                 if(!eof_ok) {
1795                         fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1796                         return false;
1797                 }
1798                 else
1799                         return true;
1800         }
1801         else if(bytes_read < 4) {
1802                 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1803                 return false;
1804         }
1805         else {
1806                 if(is_big_endian_host) {
1807                         FLAC__byte tmp, *b = (FLAC__byte*)val;
1808                         tmp = b[3]; b[3] = b[0]; b[0] = tmp;
1809                         tmp = b[2]; b[2] = b[1]; b[1] = tmp;
1810                 }
1811                 return true;
1812         }
1813 }
1814
1815 FLAC__bool
1816 read_big_endian_uint16(FILE *f, FLAC__uint16 *val, FLAC__bool eof_ok, const char *fn)
1817 {
1818         unsigned char buf[4];
1819         size_t bytes_read= fread(buf, 1, 2, f);
1820
1821         if(bytes_read==0U && eof_ok)
1822                 return true;
1823         else if(bytes_read<2U) {
1824                 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1825                 return false;
1826         }
1827
1828         /* this is independent of host endianness */
1829         *val= (FLAC__uint16)(buf[0])<<8 | buf[1];
1830
1831         return true;
1832 }
1833
1834 FLAC__bool
1835 read_big_endian_uint32(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
1836 {
1837         unsigned char buf[4];
1838         size_t bytes_read= fread(buf, 1, 4, f);
1839
1840         if(bytes_read==0U && eof_ok)
1841                 return true;
1842         else if(bytes_read<4U) {
1843                 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1844                 return false;
1845         }
1846
1847         /* this is independent of host endianness */
1848         *val= (FLAC__uint32)(buf[0])<<24 | (FLAC__uint32)(buf[1])<<16 |
1849                 (FLAC__uint32)(buf[2])<<8 | buf[3];
1850
1851         return true;
1852 }
1853
1854 FLAC__bool
1855 read_sane_extended(FILE *f, FLAC__uint32 *val, FLAC__bool eof_ok, const char *fn)
1856         /* Read an IEEE 754 80-bit (aka SANE) extended floating point value from 'f',
1857          * convert it into an integral value and store in 'val'.  Return false if only
1858          * between 1 and 9 bytes remain in 'f', if 0 bytes remain in 'f' and 'eof_ok' is
1859          * false, or if the value is negative, between zero and one, or too large to be
1860          * represented by 'val'; return true otherwise.
1861          */
1862 {
1863         unsigned int i;
1864         unsigned char buf[10];
1865         size_t bytes_read= fread(buf, 1U, 10U, f);
1866         FLAC__int16 e= ((FLAC__uint16)(buf[0])<<8 | (FLAC__uint16)(buf[1]))-0x3FFF;
1867         FLAC__int16 shift= 63-e;
1868         FLAC__uint64 p= 0U;
1869
1870         if(bytes_read==0U && eof_ok)
1871                 return true;
1872         else if(bytes_read<10U) {
1873                 fprintf(stderr, "%s: ERROR: unexpected EOF\n", fn);
1874                 return false;
1875         }
1876         else if((buf[0]>>7)==1U || e<0 || e>63) {
1877                 fprintf(stderr, "%s: ERROR: invalid floating-point value\n", fn);
1878                 return false;
1879         }
1880
1881         for(i= 0U; i<8U; ++i)
1882                 p|= (FLAC__uint64)(buf[i+2])<<(56U-i*8);
1883         *val= (FLAC__uint32)(p>>shift)+(p>>(shift-1) & 0x1);
1884
1885         return true;
1886 }
1887
1888 FLAC__bool write_big_endian_uint16(FILE *f, FLAC__uint16 val)
1889 {
1890         if(!is_big_endian_host) {
1891                 FLAC__byte *b = (FLAC__byte *)&val, tmp;
1892                 tmp = b[0]; b[0] = b[1]; b[1] = tmp;
1893         }
1894         return fwrite(&val, 1, 2, f) == 2;
1895 }
1896
1897 FLAC__bool write_big_endian_uint64(FILE *f, FLAC__uint64 val)
1898 {
1899         if(!is_big_endian_host) {
1900                 FLAC__byte *b = (FLAC__byte *)&val, tmp;
1901                 tmp = b[0]; b[0] = b[7]; b[7] = tmp;
1902                 tmp = b[1]; b[1] = b[6]; b[6] = tmp;
1903                 tmp = b[2]; b[2] = b[5]; b[5] = tmp;
1904                 tmp = b[3]; b[3] = b[4]; b[4] = tmp;
1905         }
1906         return fwrite(&val, 1, 8, f) == 8;
1907 }