fix mem leaks and open files
[flac.git] / src / test_seeking / main.c
1 /* test_seeking - Seeking tester for libFLAC
2  * Copyright (C) 2004,2005,2006,2007  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 HAVE_CONFIG_H
20 #  include <config.h>
21 #endif
22
23 #include <signal.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #if defined _MSC_VER || defined __MINGW32__
28 #include <time.h>
29 #else
30 #include <sys/time.h>
31 #endif
32 #include <sys/stat.h> /* for stat() */
33 #include "FLAC/assert.h"
34 #include "FLAC/metadata.h"
35 #include "FLAC/stream_decoder.h"
36
37 typedef struct {
38         FLAC__int32 **pcm;
39         FLAC__bool got_data;
40         FLAC__uint64 total_samples;
41         unsigned channels;
42         unsigned bits_per_sample;
43         FLAC__bool quiet;
44         FLAC__bool ignore_errors;
45         FLAC__bool error_occurred;
46 } DecoderClientData;
47
48 static FLAC__bool stop_signal_ = false;
49
50 static void our_sigint_handler_(int signal)
51 {
52         (void)signal;
53         printf("(caught SIGINT) ");
54         fflush(stdout);
55         stop_signal_ = true;
56 }
57
58 static FLAC__bool die_(const char *msg)
59 {
60         printf("ERROR: %s\n", msg);
61         return false;
62 }
63
64 static FLAC__bool die_s_(const char *msg, const FLAC__StreamDecoder *decoder)
65 {
66         FLAC__StreamDecoderState state = FLAC__stream_decoder_get_state(decoder);
67
68         if(msg)
69                 printf("FAILED, %s", msg);
70         else
71                 printf("FAILED");
72
73         printf(", state = %u (%s)\n", (unsigned)state, FLAC__StreamDecoderStateString[state]);
74
75         return false;
76 }
77
78 static off_t get_filesize_(const char *srcpath)
79 {
80         struct stat srcstat;
81
82         if(0 == stat(srcpath, &srcstat))
83                 return srcstat.st_size;
84         else
85                 return -1;
86 }
87
88 static FLAC__bool read_pcm_(FLAC__int32 *pcm[], const char *rawfilename, const char *flacfilename)
89 {
90         FILE *f;
91         unsigned channels, bps, samples, i, j;
92
93         off_t rawfilesize = get_filesize_(rawfilename);
94         if (rawfilesize < 0) {
95                 fprintf(stderr, "ERROR: can't determine filesize for %s\n", rawfilename);
96                 return false;
97         }
98         /* get sample format from flac file; would just use FLAC__metadata_get_streaminfo() except it doesn't work for Ogg FLAC yet */
99         {
100 #if 0
101                 FLAC__StreamMetadata streaminfo;
102                 if(!FLAC__metadata_get_streaminfo(flacfilename, &streaminfo)) {
103                         printf("ERROR: getting STREAMINFO from %s\n", flacfilename);
104                         return false;
105                 }
106                 channels = streaminfo.data.stream_info.channels;
107                 bps = streaminfo.data.stream_info.bits_per_sample;
108 #else
109                 FLAC__bool ok = true;
110                 FLAC__Metadata_Chain *chain = FLAC__metadata_chain_new();
111                 FLAC__Metadata_Iterator *it = 0;
112                 ok = ok && chain && (FLAC__metadata_chain_read(chain, flacfilename) || FLAC__metadata_chain_read_ogg(chain, flacfilename));
113                 ok = ok && (it = FLAC__metadata_iterator_new());
114                 if(ok) FLAC__metadata_iterator_init(it, chain);
115                 ok = ok && (FLAC__metadata_iterator_get_block(it)->type == FLAC__METADATA_TYPE_STREAMINFO);
116                 ok = ok && (channels = FLAC__metadata_iterator_get_block(it)->data.stream_info.channels);
117                 ok = ok && (bps = FLAC__metadata_iterator_get_block(it)->data.stream_info.bits_per_sample);
118                 if(it) FLAC__metadata_iterator_delete(it);
119                 if(chain) FLAC__metadata_chain_delete(chain);
120                 if(!ok) {
121                         printf("ERROR: getting STREAMINFO from %s\n", flacfilename);
122                         return false;
123                 }
124 #endif
125         }
126         if(channels > 2) {
127                 printf("ERROR: PCM verification requires 1 or 2 channels, got %u\n", channels);
128                 return false;
129         }
130         if(bps != 8 && bps != 16) {
131                 printf("ERROR: PCM verification requires 8 or 16 bps, got %u\n", bps);
132                 return false;
133         }
134         samples = rawfilesize / channels / (bps>>3);
135         if (samples > 10000000) {
136                 fprintf(stderr, "ERROR: %s is too big\n", rawfilename);
137                 return false;
138         }
139         for(i = 0; i < channels; i++) {
140                 if(0 == (pcm[i] = (FLAC__int32*)malloc(sizeof(FLAC__int32)*samples))) {
141                         printf("ERROR: allocating space for PCM samples\n");
142                         return false;
143                 }
144         }
145         if(0 == (f = fopen(rawfilename, "r"))) {
146                 printf("ERROR: opening %s for reading\n", rawfilename);
147                 return false;
148         }
149         /* assumes signed big-endian data */
150         if(bps == 8) {
151                 signed char c;
152                 for(i = 0; i < samples; i++) {
153                         for(j = 0; j < channels; j++) {
154                                 fread(&c, 1, 1, f);
155                                 pcm[j][i] = c;
156                         }
157                 }
158         }
159         else { /* bps == 16 */
160                 unsigned char c[2];
161                 for(i = 0; i < samples; i++) {
162                         for(j = 0; j < channels; j++) {
163                                 fread(&c, 1, 2, f);
164                                 pcm[j][i] = ((int)((signed char)c[0])) << 8 | (int)c[1];
165                         }
166                 }
167         }
168         fclose(f);
169         return true;
170 }
171
172 static FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
173 {
174         DecoderClientData *dcd = (DecoderClientData*)client_data;
175
176         (void)decoder, (void)buffer;
177
178         if(0 == dcd) {
179                 printf("ERROR: client_data in write callback is NULL\n");
180                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
181         }
182
183         if(dcd->error_occurred)
184                 return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
185
186         FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER); /* decoder guarantees this */
187         if (!dcd->quiet)
188 #ifdef _MSC_VER
189                 printf("frame@%I64u(%u)... ", frame->header.number.sample_number, frame->header.blocksize);
190 #else
191                 printf("frame@%llu(%u)... ", (unsigned long long)frame->header.number.sample_number, frame->header.blocksize);
192 #endif
193         fflush(stdout);
194
195         /* check against PCM data if we have it */
196         if (dcd->pcm) {
197                 unsigned c, i, j;
198                 for (c = 0; c < frame->header.channels; c++)
199                         for (i = (unsigned)frame->header.number.sample_number, j = 0; j < frame->header.blocksize; i++, j++)
200                                 if (buffer[c][j] != dcd->pcm[c][i]) {
201                                         printf("ERROR: sample mismatch at sample#%u(%u), channel=%u, expected %d, got %d\n", i, j, c, buffer[c][j], dcd->pcm[c][i]);
202                                         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
203                                 }
204         }
205
206         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
207 }
208
209 static void metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
210 {
211         DecoderClientData *dcd = (DecoderClientData*)client_data;
212
213         (void)decoder;
214
215         if(0 == dcd) {
216                 printf("ERROR: client_data in metadata callback is NULL\n");
217                 return;
218         }
219
220         if(dcd->error_occurred)
221                 return;
222
223         if (!dcd->got_data && metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
224                 dcd->got_data = true;
225                 dcd->total_samples = metadata->data.stream_info.total_samples;
226                 dcd->channels = metadata->data.stream_info.channels;
227                 dcd->bits_per_sample = metadata->data.stream_info.bits_per_sample;
228         }
229 }
230
231 static void error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
232 {
233         DecoderClientData *dcd = (DecoderClientData*)client_data;
234
235         (void)decoder;
236
237         if(0 == dcd) {
238                 printf("ERROR: client_data in error callback is NULL\n");
239                 return;
240         }
241
242         if(!dcd->ignore_errors) {
243                 printf("ERROR: got error callback: err = %u (%s)\n", (unsigned)status, FLAC__StreamDecoderErrorStatusString[status]);
244                 dcd->error_occurred = true;
245         }
246 }
247
248 /* read mode:
249  * 0 - no read after seek
250  * 1 - read 2 frames
251  * 2 - read until end
252  */
253 static FLAC__bool seek_barrage(FLAC__bool is_ogg, const char *filename, off_t filesize, unsigned count, FLAC__int64 total_samples, unsigned read_mode, FLAC__int32 **pcm)
254 {
255         FLAC__StreamDecoder *decoder;
256         DecoderClientData decoder_client_data;
257         unsigned i;
258         long int n;
259
260         decoder_client_data.pcm = pcm;
261         decoder_client_data.got_data = false;
262         decoder_client_data.total_samples = 0;
263         decoder_client_data.quiet = false;
264         decoder_client_data.ignore_errors = false;
265         decoder_client_data.error_occurred = false;
266
267         printf("\n+++ seek test: FLAC__StreamDecoder (%s FLAC, read_mode=%u)\n\n", is_ogg? "Ogg":"native", read_mode);
268
269         decoder = FLAC__stream_decoder_new();
270         if(0 == decoder)
271                 return die_("FLAC__stream_decoder_new() FAILED, returned NULL\n");
272
273         if(is_ogg) {
274                 if(FLAC__stream_decoder_init_ogg_file(decoder, filename, write_callback_, metadata_callback_, error_callback_, &decoder_client_data) != FLAC__STREAM_DECODER_INIT_STATUS_OK)
275                         return die_s_("FLAC__stream_decoder_init_file() FAILED", decoder);
276         }
277         else {
278                 if(FLAC__stream_decoder_init_file(decoder, filename, write_callback_, metadata_callback_, error_callback_, &decoder_client_data) != FLAC__STREAM_DECODER_INIT_STATUS_OK)
279                         return die_s_("FLAC__stream_decoder_init_file() FAILED", decoder);
280         }
281
282         if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder))
283                 return die_s_("FLAC__stream_decoder_process_until_end_of_metadata() FAILED", decoder);
284
285         if(!is_ogg) { /* not necessary to do this for Ogg because of its seeking method */
286         /* process until end of stream to make sure we can still seek in that state */
287                 decoder_client_data.quiet = true;
288                 if(!FLAC__stream_decoder_process_until_end_of_stream(decoder))
289                         return die_s_("FLAC__stream_decoder_process_until_end_of_stream() FAILED", decoder);
290                 decoder_client_data.quiet = false;
291
292                 printf("stream decoder state is %s\n", FLAC__stream_decoder_get_resolved_state_string(decoder));
293                 if(FLAC__stream_decoder_get_state(decoder) != FLAC__STREAM_DECODER_END_OF_STREAM)
294                         return die_s_("expected FLAC__STREAM_DECODER_END_OF_STREAM", decoder);
295         }
296
297 #ifdef _MSC_VER
298         printf("file's total_samples is %I64u\n", decoder_client_data.total_samples);
299 #else
300         printf("file's total_samples is %llu\n", (unsigned long long)decoder_client_data.total_samples);
301 #endif
302 #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
303         if (decoder_client_data.total_samples > (FLAC__uint64)RAND_MAX) {
304                 printf("ERROR: must be total_samples < %u\n", (unsigned)RAND_MAX);
305                 return false;
306         }
307 #endif
308         n = (long int)decoder_client_data.total_samples;
309
310         if(n == 0 && total_samples >= 0)
311                 n = (long int)total_samples;
312
313         /* if we don't have a total samples count, just guess based on the file size */
314         /* @@@ for is_ogg we should get it from last page's granulepos */
315         if(n == 0) {
316                 /* 8 would imply no compression, 9 guarantees that we will get some samples off the end of the stream to test that case */
317                 n = 9 * filesize / (decoder_client_data.channels * decoder_client_data.bits_per_sample);
318 #if !defined _MSC_VER && !defined __MINGW32__
319                 if(n > RAND_MAX)
320                         n = RAND_MAX;
321 #endif
322         }
323
324         printf("Begin seek barrage, count=%u\n", count);
325
326         for (i = 0; !stop_signal_ && (count == 0 || i < count); i++) {
327                 FLAC__uint64 pos;
328
329                 /* for the first 10, seek to the first 10 samples */
330                 if (n >= 10 && i < 10) {
331                         pos = i;
332                 }
333                 /* for the second 10, seek to the last 10 samples */
334                 else if (n >= 10 && i < 20) {
335                         pos = n - 1 - (i-10);
336                 }
337                 /* for the third 10, seek past the end and make sure we fail properly as expected */
338                 else if (i < 30) {
339                         pos = n + (i-20);
340                 }
341                 else {
342 #if !defined _MSC_VER && !defined __MINGW32__
343                         pos = (FLAC__uint64)(random() % n);
344 #else
345                         /* RAND_MAX is only 32767 in my MSVC */
346                         pos = (FLAC__uint64)((rand()<<15|rand()) % n);
347 #endif
348                 }
349
350 #ifdef _MSC_VER
351                 printf("seek(%I64u)... ", pos);
352 #else
353                 printf("seek(%llu)... ", (unsigned long long)pos);
354 #endif
355                 fflush(stdout);
356                 if(!FLAC__stream_decoder_seek_absolute(decoder, pos)) {
357                         if(pos >= (FLAC__uint64)n)
358                                 printf("seek past end failed as expected... ");
359                         else if(decoder_client_data.total_samples == 0 && total_samples <= 0)
360                                 printf("seek failed, assuming it was past EOF... ");
361                         else
362                                 return die_s_("FLAC__stream_decoder_seek_absolute() FAILED", decoder);
363                         if(!FLAC__stream_decoder_flush(decoder))
364                                 return die_s_("FLAC__stream_decoder_flush() FAILED", decoder);
365                 }
366                 else if(read_mode == 1) {
367                         printf("decode_frame... ");
368                         fflush(stdout);
369                         if(!FLAC__stream_decoder_process_single(decoder))
370                                 return die_s_("FLAC__stream_decoder_process_single() FAILED", decoder);
371
372                         printf("decode_frame... ");
373                         fflush(stdout);
374                         if(!FLAC__stream_decoder_process_single(decoder))
375                                 return die_s_("FLAC__stream_decoder_process_single() FAILED", decoder);
376                 }
377                 else if(read_mode == 2) {
378                         printf("decode_all... ");
379                         fflush(stdout);
380                         decoder_client_data.quiet = true;
381                         if(!FLAC__stream_decoder_process_until_end_of_stream(decoder))
382                                 return die_s_("FLAC__stream_decoder_process_until_end_of_stream() FAILED", decoder);
383                         decoder_client_data.quiet = false;
384                 }
385
386                 printf("OK\n");
387                 fflush(stdout);
388         }
389
390         if(FLAC__stream_decoder_get_state(decoder) != FLAC__STREAM_DECODER_UNINITIALIZED) {
391                 if(!FLAC__stream_decoder_finish(decoder))
392                         return die_s_("FLAC__stream_decoder_finish() FAILED", decoder);
393         }
394
395         FLAC__stream_decoder_delete(decoder);
396         printf("\nPASSED!\n");
397
398         return true;
399 }
400
401 #ifdef _MSC_VER
402 /* There's no strtoull() in MSVC6 so we just write a specialized one */
403 static FLAC__uint64 local__strtoull(const char *src)
404 {
405         FLAC__uint64 ret = 0;
406         int c;
407         FLAC__ASSERT(0 != src);
408         while(0 != (c = *src++)) {
409                 c -= '0';
410                 if(c >= 0 && c <= 9)
411                         ret = (ret * 10) + c;
412                 else
413                         break;
414         }
415         return ret;
416 }
417 #endif
418
419 int main(int argc, char *argv[])
420 {
421         const char *flacfilename, *rawfilename = 0;
422         unsigned count = 0, read_mode;
423         FLAC__int64 samples = -1;
424         off_t flacfilesize;
425         FLAC__int32 *pcm[2] = { 0, 0 };
426         FLAC__bool ok = true;
427
428         static const char * const usage = "usage: test_seeking file.flac [#seeks] [#samples-in-file.flac] [file.raw]\n";
429
430         if (argc < 2 || argc > 5) {
431                 fprintf(stderr, usage);
432                 return 1;
433         }
434
435         flacfilename = argv[1];
436
437         if (argc > 2)
438                 count = strtoul(argv[2], 0, 10);
439         if (argc > 3)
440 #ifdef _MSC_VER
441                 samples = local__strtoull(argv[4]);
442 #else
443                 samples = strtoull(argv[3], 0, 10);
444 #endif
445         if (argc > 4)
446                 rawfilename = argv[4];
447
448         if (count < 30)
449                 fprintf(stderr, "WARNING: random seeks don't kick in until after 30 preprogrammed ones\n");
450
451 #if !defined _MSC_VER && !defined __MINGW32__
452         {
453                 struct timeval tv;
454
455                 if (gettimeofday(&tv, 0) < 0) {
456                         fprintf(stderr, "WARNING: couldn't seed RNG with time\n");
457                         tv.tv_usec = 4321;
458                 }
459                 srandom(tv.tv_usec);
460         }
461 #else
462         srand((unsigned)time(0));
463 #endif
464
465         flacfilesize = get_filesize_(flacfilename);
466         if (flacfilesize < 0) {
467                 fprintf(stderr, "ERROR: can't determine filesize for %s\n", flacfilename);
468                 return 1;
469         }
470
471         if (rawfilename && !read_pcm_(pcm, rawfilename, flacfilename)) {
472                 free(pcm[0]);
473                 free(pcm[1]);
474                 return 1;
475         }
476
477         (void) signal(SIGINT, our_sigint_handler_);
478
479         for (read_mode = 0; ok && read_mode <= 2; read_mode++) {
480                 /* no need to do "decode all" read_mode if PCM checking is available */
481                 if (rawfilename && read_mode > 1)
482                         continue;
483                 if (strlen(flacfilename) > 4 && 0 == strcmp(flacfilename+strlen(flacfilename)-4, ".ogg")) {
484 #if FLAC__HAS_OGG
485                         ok = seek_barrage(/*is_ogg=*/true, flacfilename, flacfilesize, count, samples, read_mode, rawfilename? pcm : 0);
486 #else
487                         fprintf(stderr, "ERROR: Ogg FLAC not supported\n");
488                         ok = false;
489 #endif
490                 }
491                 else {
492                         ok = seek_barrage(/*is_ogg=*/false, flacfilename, flacfilesize, count, samples, read_mode, rawfilename? pcm : 0);
493                 }
494         }
495
496         free(pcm[0]);
497         free(pcm[1]);
498
499         return ok? 0 : 2;
500 }