1 /*
2  * This program is free software; you can redistribute it and/or modify
3  * it under the terms of the GNU General Public License as published by
4  * the Free Software Foundation; either version 2 of the License, or
5  * (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software
14  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
15  */
16 
17 #define FLAC_BLOCK_SIZE 4096
18 #define FLAC_FRAME_MAX_HEADER 22
19 
20 /* frame header size (16 bytes) + 4608 stereo 16-bit samples (higher than 4608 is possible, but not done) */
21 #define FLAC_MAX_FRAMESIZE 18448
22 #define FLAC_HEADER_LEN 16
23 
24 enum flac_types {
25   FLAC_TYPE_STREAMINFO,
26   FLAC_TYPE_PADDING,
27   FLAC_TYPE_APPLICATION,
28   FLAC_TYPE_SEEKTABLE,
29   FLAC_TYPE_VORBIS_COMMENT,
30   FLAC_TYPE_CUESHEET,
31   FLAC_TYPE_PICTURE
32 };
33 
34 typedef struct seekpoint {
35   uint64_t sample_number;
36   uint64_t stream_offset;
37   uint16_t frame_samples;
38 } seekpoint;
39 
40 typedef struct flacinfo {
41   PerlIO *infile;
42   char *file;
43   Buffer *buf;
44   Buffer *scratch;
45   HV *info;
46   HV *tags;
47   off_t file_size;
48   off_t audio_offset;
49 
50   uint32_t min_blocksize;
51   uint32_t max_blocksize;
52   uint32_t min_framesize;
53   uint32_t max_framesize;
54   uint8_t  channels;
55   uint32_t samplerate;
56   uint32_t bits_per_sample;
57   uint64_t total_samples;
58 
59   uint8_t seeking; // flag if we're seeking
60 
61   uint32_t num_seekpoints;
62   struct seekpoint *seekpoints;
63 } flacinfo;
64 
65 int get_flac_metadata(PerlIO *infile, char *file, HV *info, HV *tags);
66 flacinfo * _flac_parse(PerlIO *infile, char *file, HV *info, HV *tags, uint8_t seeking);
67 void _flac_parse_streaminfo(flacinfo *flac);
68 void _flac_parse_application(flacinfo *flac, int len);
69 void _flac_parse_seektable(flacinfo *flac, int len);
70 void _flac_parse_cuesheet(flacinfo *flac);
71 int _flac_parse_picture(flacinfo *flac);
72 int _flac_binary_search_sample(flacinfo *flac, uint64_t target_sample, off_t low, off_t high);
73 int _flac_read_frame_header(flacinfo *flac, unsigned char *buf, uint64_t *first_sample, uint64_t *last_sample);
74 int _flac_first_last_sample(flacinfo *flac, off_t seek_offset, off_t *frame_offset, uint64_t *first_sample, uint64_t *last_sample, uint64_t target_sample);
75 uint8_t _flac_crc8(const unsigned char *buf, unsigned len);
76 int _flac_read_utf8_uint64(unsigned char *raw, uint64_t *val, uint8_t *rawlen);
77 int _flac_read_utf8_uint32(unsigned char *raw, uint32_t *val, uint8_t *rawlen);
78 void _flac_skip(flacinfo *flac, uint32_t size);
79