0ba0d200f2ae1f482ad8664dcd8bd49616f87985
[flac.git] / src / libFLAC / metadata_iterators.c
1 /* libFLAC - Free Lossless Audio Codec library
2  * Copyright (C) 2001,2002,2003,2004,2005,2006,2007,2008,2009  Josh Coalson
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * - Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  *
11  * - Redistributions in binary form must reproduce the above copyright
12  * notice, this list of conditions and the following disclaimer in the
13  * documentation and/or other materials provided with the distribution.
14  *
15  * - Neither the name of the Xiph.org Foundation nor the names of its
16  * contributors may be used to endorse or promote products derived from
17  * this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22  * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */
31
32 #if HAVE_CONFIG_H
33 #  include <config.h>
34 #endif
35
36 #include <errno.h>
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <string.h>
40
41 #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
42 #if defined __BORLANDC__
43 #include <utime.h> /* for utime() */
44 #else
45 #include <sys/utime.h> /* for utime() */
46 #endif
47 #include <io.h> /* for chmod() */
48 #include <sys/types.h> /* for off_t */
49 #else
50 #include <sys/types.h> /* some flavors of BSD (like OS X) require this to get time_t */
51 #include <utime.h> /* for utime() */
52 #include <unistd.h> /* for chown(), unlink() */
53 #endif
54 #include <sys/stat.h> /* for stat(), maybe chmod() */
55
56 #include "private/metadata.h"
57
58 #include "FLAC/assert.h"
59 #include "FLAC/stream_decoder.h"
60 #include "share/alloc.h"
61 #include "share/compat.h"
62
63 #ifdef max
64 #undef max
65 #endif
66 #define max(a,b) ((a)>(b)?(a):(b))
67 #ifdef min
68 #undef min
69 #endif
70 #define min(a,b) ((a)<(b)?(a):(b))
71
72
73 /****************************************************************************
74  *
75  * Local function declarations
76  *
77  ***************************************************************************/
78
79 static void pack_uint32_(FLAC__uint32 val, FLAC__byte *b, unsigned bytes);
80 static void pack_uint32_little_endian_(FLAC__uint32 val, FLAC__byte *b, unsigned bytes);
81 static void pack_uint64_(FLAC__uint64 val, FLAC__byte *b, unsigned bytes);
82 static FLAC__uint32 unpack_uint32_(FLAC__byte *b, unsigned bytes);
83 static FLAC__uint32 unpack_uint32_little_endian_(FLAC__byte *b, unsigned bytes);
84 static FLAC__uint64 unpack_uint64_(FLAC__byte *b, unsigned bytes);
85
86 static FLAC__bool read_metadata_block_header_(FLAC__Metadata_SimpleIterator *iterator);
87 static FLAC__bool read_metadata_block_data_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block);
88 static FLAC__bool read_metadata_block_header_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__bool *is_last, FLAC__MetadataType *type, unsigned *length);
89 static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Seek seek_cb, FLAC__StreamMetadata *block);
90 static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_streaminfo_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_StreamInfo *block);
91 static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_padding_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Seek seek_cb, FLAC__StreamMetadata_Padding *block, unsigned block_length);
92 static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_application_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_Application *block, unsigned block_length);
93 static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_seektable_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_SeekTable *block, unsigned block_length);
94 static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_vorbis_comment_entry_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_VorbisComment_Entry *entry);
95 static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_vorbis_comment_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_VorbisComment *block);
96 static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_cuesheet_track_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_CueSheet_Track *track);
97 static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_cuesheet_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_CueSheet *block);
98 static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_picture_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_Picture *block);
99 static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_unknown_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_Unknown *block, unsigned block_length);
100
101 static FLAC__bool write_metadata_block_header_(FILE *file, FLAC__Metadata_SimpleIteratorStatus *status, const FLAC__StreamMetadata *block);
102 static FLAC__bool write_metadata_block_data_(FILE *file, FLAC__Metadata_SimpleIteratorStatus *status, const FLAC__StreamMetadata *block);
103 static FLAC__bool write_metadata_block_header_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata *block);
104 static FLAC__bool write_metadata_block_data_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata *block);
105 static FLAC__bool write_metadata_block_data_streaminfo_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_StreamInfo *block);
106 static FLAC__bool write_metadata_block_data_padding_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Padding *block, unsigned block_length);
107 static FLAC__bool write_metadata_block_data_application_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Application *block, unsigned block_length);
108 static FLAC__bool write_metadata_block_data_seektable_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_SeekTable *block);
109 static FLAC__bool write_metadata_block_data_vorbis_comment_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_VorbisComment *block);
110 static FLAC__bool write_metadata_block_data_cuesheet_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_CueSheet *block);
111 static FLAC__bool write_metadata_block_data_picture_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Picture *block);
112 static FLAC__bool write_metadata_block_data_unknown_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Unknown *block, unsigned block_length);
113
114 static FLAC__bool write_metadata_block_stationary_(FLAC__Metadata_SimpleIterator *iterator, const FLAC__StreamMetadata *block);
115 static FLAC__bool write_metadata_block_stationary_with_padding_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, unsigned padding_length, FLAC__bool padding_is_last);
116 static FLAC__bool rewrite_whole_file_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool append);
117
118 static void simple_iterator_push_(FLAC__Metadata_SimpleIterator *iterator);
119 static FLAC__bool simple_iterator_pop_(FLAC__Metadata_SimpleIterator *iterator);
120
121 static unsigned seek_to_first_metadata_block_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Seek seek_cb);
122 static unsigned seek_to_first_metadata_block_(FILE *f);
123
124 static FLAC__bool simple_iterator_copy_file_prefix_(FLAC__Metadata_SimpleIterator *iterator, FILE **tempfile, char **tempfilename, FLAC__bool append);
125 static FLAC__bool simple_iterator_copy_file_postfix_(FLAC__Metadata_SimpleIterator *iterator, FILE **tempfile, char **tempfilename, int fixup_is_last_code, off_t fixup_is_last_flag_offset, FLAC__bool backup);
126
127 static FLAC__bool copy_n_bytes_from_file_(FILE *file, FILE *tempfile, off_t bytes, FLAC__Metadata_SimpleIteratorStatus *status);
128 static FLAC__bool copy_n_bytes_from_file_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOHandle temp_handle, FLAC__IOCallback_Write temp_write_cb, off_t bytes, FLAC__Metadata_SimpleIteratorStatus *status);
129 static FLAC__bool copy_remaining_bytes_from_file_(FILE *file, FILE *tempfile, FLAC__Metadata_SimpleIteratorStatus *status);
130 static FLAC__bool copy_remaining_bytes_from_file_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Eof eof_cb, FLAC__IOHandle temp_handle, FLAC__IOCallback_Write temp_write_cb, FLAC__Metadata_SimpleIteratorStatus *status);
131
132 static FLAC__bool open_tempfile_(const char *filename, const char *tempfile_path_prefix, FILE **tempfile, char **tempfilename, FLAC__Metadata_SimpleIteratorStatus *status);
133 static FLAC__bool transport_tempfile_(const char *filename, FILE **tempfile, char **tempfilename, FLAC__Metadata_SimpleIteratorStatus *status);
134 static void cleanup_tempfile_(FILE **tempfile, char **tempfilename);
135
136 static FLAC__bool get_file_stats_(const char *filename, struct stat *stats);
137 static void set_file_stats_(const char *filename, struct stat *stats);
138
139 static int fseek_wrapper_(FLAC__IOHandle handle, FLAC__int64 offset, int whence);
140 static FLAC__int64 ftell_wrapper_(FLAC__IOHandle handle);
141
142 static FLAC__Metadata_ChainStatus get_equivalent_status_(FLAC__Metadata_SimpleIteratorStatus status);
143
144
145 #ifdef FLAC__VALGRIND_TESTING
146 static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
147 {
148         size_t ret = fwrite(ptr, size, nmemb, stream);
149         if(!ferror(stream))
150                 fflush(stream);
151         return ret;
152 }
153 #else
154 #define local__fwrite fwrite
155 #endif
156
157 /****************************************************************************
158  *
159  * Level 0 implementation
160  *
161  ***************************************************************************/
162
163 static FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
164 static void metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
165 static void error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
166
167 typedef struct {
168         FLAC__bool got_error;
169         FLAC__StreamMetadata *object;
170 } level0_client_data;
171
172 static FLAC__StreamMetadata *get_one_metadata_block_(const char *filename, FLAC__MetadataType type)
173 {
174         level0_client_data cd;
175         FLAC__StreamDecoder *decoder;
176
177         FLAC__ASSERT(0 != filename);
178
179         cd.got_error = false;
180         cd.object = 0;
181
182         decoder = FLAC__stream_decoder_new();
183
184         if(0 == decoder)
185                 return 0;
186
187         FLAC__stream_decoder_set_md5_checking(decoder, false);
188         FLAC__stream_decoder_set_metadata_ignore_all(decoder);
189         FLAC__stream_decoder_set_metadata_respond(decoder, type);
190
191         if(FLAC__stream_decoder_init_file(decoder, filename, write_callback_, metadata_callback_, error_callback_, &cd) != FLAC__STREAM_DECODER_INIT_STATUS_OK || cd.got_error) {
192                 (void)FLAC__stream_decoder_finish(decoder);
193                 FLAC__stream_decoder_delete(decoder);
194                 return 0;
195         }
196
197         if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder) || cd.got_error) {
198                 (void)FLAC__stream_decoder_finish(decoder);
199                 FLAC__stream_decoder_delete(decoder);
200                 if(0 != cd.object)
201                         FLAC__metadata_object_delete(cd.object);
202                 return 0;
203         }
204
205         (void)FLAC__stream_decoder_finish(decoder);
206         FLAC__stream_decoder_delete(decoder);
207
208         return cd.object;
209 }
210
211 FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo)
212 {
213         FLAC__StreamMetadata *object;
214
215         FLAC__ASSERT(0 != filename);
216         FLAC__ASSERT(0 != streaminfo);
217
218         object = get_one_metadata_block_(filename, FLAC__METADATA_TYPE_STREAMINFO);
219
220         if (object) {
221                 /* can just copy the contents since STREAMINFO has no internal structure */
222                 *streaminfo = *object;
223                 FLAC__metadata_object_delete(object);
224                 return true;
225         }
226         else {
227                 return false;
228         }
229 }
230
231 FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags)
232 {
233         FLAC__ASSERT(0 != filename);
234         FLAC__ASSERT(0 != tags);
235
236         *tags = get_one_metadata_block_(filename, FLAC__METADATA_TYPE_VORBIS_COMMENT);
237
238         return 0 != *tags;
239 }
240
241 FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet)
242 {
243         FLAC__ASSERT(0 != filename);
244         FLAC__ASSERT(0 != cuesheet);
245
246         *cuesheet = get_one_metadata_block_(filename, FLAC__METADATA_TYPE_CUESHEET);
247
248         return 0 != *cuesheet;
249 }
250
251 FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
252 {
253         (void)decoder, (void)frame, (void)buffer, (void)client_data;
254
255         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
256 }
257
258 void metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
259 {
260         level0_client_data *cd = (level0_client_data *)client_data;
261         (void)decoder;
262
263         /*
264          * we assume we only get here when the one metadata block we were
265          * looking for was passed to us
266          */
267         if(!cd->got_error && 0 == cd->object) {
268                 if(0 == (cd->object = FLAC__metadata_object_clone(metadata)))
269                         cd->got_error = true;
270         }
271 }
272
273 void error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
274 {
275         level0_client_data *cd = (level0_client_data *)client_data;
276         (void)decoder;
277
278         if(status != FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC)
279                 cd->got_error = true;
280 }
281
282 FLAC_API FLAC__bool FLAC__metadata_get_picture(const char *filename, FLAC__StreamMetadata **picture, FLAC__StreamMetadata_Picture_Type type, const char *mime_type, const FLAC__byte *description, unsigned max_width, unsigned max_height, unsigned max_depth, unsigned max_colors)
283 {
284         FLAC__Metadata_SimpleIterator *it;
285         FLAC__uint64 max_area_seen = 0;
286         FLAC__uint64 max_depth_seen = 0;
287
288         FLAC__ASSERT(0 != filename);
289         FLAC__ASSERT(0 != picture);
290
291         *picture = 0;
292
293         it = FLAC__metadata_simple_iterator_new();
294         if(0 == it)
295                 return false;
296         if(!FLAC__metadata_simple_iterator_init(it, filename, /*read_only=*/true, /*preserve_file_stats=*/true)) {
297                 FLAC__metadata_simple_iterator_delete(it);
298                 return false;
299         }
300         do {
301                 if(FLAC__metadata_simple_iterator_get_block_type(it) == FLAC__METADATA_TYPE_PICTURE) {
302                         FLAC__StreamMetadata *obj = FLAC__metadata_simple_iterator_get_block(it);
303                         FLAC__uint64 area = (FLAC__uint64)obj->data.picture.width * (FLAC__uint64)obj->data.picture.height;
304                         /* check constraints */
305                         if(
306                                 (type == (FLAC__StreamMetadata_Picture_Type)(-1) || type == obj->data.picture.type) &&
307                                 (mime_type == 0 || !strcmp(mime_type, obj->data.picture.mime_type)) &&
308                                 (description == 0 || !strcmp((const char *)description, (const char *)obj->data.picture.description)) &&
309                                 obj->data.picture.width <= max_width &&
310                                 obj->data.picture.height <= max_height &&
311                                 obj->data.picture.depth <= max_depth &&
312                                 obj->data.picture.colors <= max_colors &&
313                                 (area > max_area_seen || (area == max_area_seen && obj->data.picture.depth > max_depth_seen))
314                         ) {
315                                 if(*picture)
316                                         FLAC__metadata_object_delete(*picture);
317                                 *picture = obj;
318                                 max_area_seen = area;
319                                 max_depth_seen = obj->data.picture.depth;
320                         }
321                         else {
322                                 FLAC__metadata_object_delete(obj);
323                         }
324                 }
325         } while(FLAC__metadata_simple_iterator_next(it));
326
327         FLAC__metadata_simple_iterator_delete(it);
328
329         return (0 != *picture);
330 }
331
332
333 /****************************************************************************
334  *
335  * Level 1 implementation
336  *
337  ***************************************************************************/
338
339 #define SIMPLE_ITERATOR_MAX_PUSH_DEPTH (1+4)
340 /* 1 for initial offset, +4 for our own personal use */
341
342 struct FLAC__Metadata_SimpleIterator {
343         FILE *file;
344         char *filename, *tempfile_path_prefix;
345         struct stat stats;
346         FLAC__bool has_stats;
347         FLAC__bool is_writable;
348         FLAC__Metadata_SimpleIteratorStatus status;
349         off_t offset[SIMPLE_ITERATOR_MAX_PUSH_DEPTH];
350         off_t first_offset; /* this is the offset to the STREAMINFO block */
351         unsigned depth;
352         /* this is the metadata block header of the current block we are pointing to: */
353         FLAC__bool is_last;
354         FLAC__MetadataType type;
355         unsigned length;
356 };
357
358 FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[] = {
359         "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK",
360         "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT",
361         "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE",
362         "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE",
363         "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE",
364         "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA",
365         "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR",
366         "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR",
367         "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR",
368         "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR",
369         "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR",
370         "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR",
371         "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR"
372 };
373
374
375 FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void)
376 {
377         FLAC__Metadata_SimpleIterator *iterator = calloc(1, sizeof(FLAC__Metadata_SimpleIterator));
378
379         if(0 != iterator) {
380                 iterator->file = 0;
381                 iterator->filename = 0;
382                 iterator->tempfile_path_prefix = 0;
383                 iterator->has_stats = false;
384                 iterator->is_writable = false;
385                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
386                 iterator->first_offset = iterator->offset[0] = -1;
387                 iterator->depth = 0;
388         }
389
390         return iterator;
391 }
392
393 static void simple_iterator_free_guts_(FLAC__Metadata_SimpleIterator *iterator)
394 {
395         FLAC__ASSERT(0 != iterator);
396
397         if(0 != iterator->file) {
398                 fclose(iterator->file);
399                 iterator->file = 0;
400                 if(iterator->has_stats)
401                         set_file_stats_(iterator->filename, &iterator->stats);
402         }
403         if(0 != iterator->filename) {
404                 free(iterator->filename);
405                 iterator->filename = 0;
406         }
407         if(0 != iterator->tempfile_path_prefix) {
408                 free(iterator->tempfile_path_prefix);
409                 iterator->tempfile_path_prefix = 0;
410         }
411 }
412
413 FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator)
414 {
415         FLAC__ASSERT(0 != iterator);
416
417         simple_iterator_free_guts_(iterator);
418         free(iterator);
419 }
420
421 FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator)
422 {
423         FLAC__Metadata_SimpleIteratorStatus status;
424
425         FLAC__ASSERT(0 != iterator);
426
427         status = iterator->status;
428         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
429         return status;
430 }
431
432 static FLAC__bool simple_iterator_prime_input_(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool read_only)
433 {
434         unsigned ret;
435
436         FLAC__ASSERT(0 != iterator);
437
438         if(read_only || 0 == (iterator->file = fopen(iterator->filename, "r+b"))) {
439                 iterator->is_writable = false;
440                 if(read_only || errno == EACCES) {
441                         if(0 == (iterator->file = fopen(iterator->filename, "rb"))) {
442                                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE;
443                                 return false;
444                         }
445                 }
446                 else {
447                         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE;
448                         return false;
449                 }
450         }
451         else {
452                 iterator->is_writable = true;
453         }
454
455         ret = seek_to_first_metadata_block_(iterator->file);
456         switch(ret) {
457                 case 0:
458                         iterator->depth = 0;
459                         iterator->first_offset = iterator->offset[iterator->depth] = ftello(iterator->file);
460                         return read_metadata_block_header_(iterator);
461                 case 1:
462                         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
463                         return false;
464                 case 2:
465                         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
466                         return false;
467                 case 3:
468                         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE;
469                         return false;
470                 default:
471                         FLAC__ASSERT(0);
472                         return false;
473         }
474 }
475
476 #if 0
477 @@@ If we decide to finish implementing this, put this comment back in metadata.h
478 /*
479  * The 'tempfile_path_prefix' allows you to specify a directory where
480  * tempfiles should go.  Remember that if your metadata edits cause the
481  * FLAC file to grow, the entire file will have to be rewritten.  If
482  * 'tempfile_path_prefix' is NULL, the temp file will be written in the
483  * same directory as the original FLAC file.  This makes replacing the
484  * original with the tempfile fast but requires extra space in the same
485  * partition for the tempfile.  If space is a problem, you can pass a
486  * directory name belonging to a different partition in
487  * 'tempfile_path_prefix'.  Note that you should use the forward slash
488  * '/' as the directory separator.  A trailing slash is not needed; it
489  * will be added automatically.
490  */
491 FLAC__bool FLAC__metadata_simple_iterator_init(FLAC__Metadata_SimpleIterator *iterator, const char *filename, FLAC__bool preserve_file_stats, const char *tempfile_path_prefix);
492 #endif
493
494 FLAC_API FLAC__bool FLAC__metadata_simple_iterator_init(FLAC__Metadata_SimpleIterator *iterator, const char *filename, FLAC__bool read_only, FLAC__bool preserve_file_stats)
495 {
496         const char *tempfile_path_prefix = 0; /*@@@ search for comments near 'rename(...)' for what it will take to finish implementing this */
497
498         FLAC__ASSERT(0 != iterator);
499         FLAC__ASSERT(0 != filename);
500
501         simple_iterator_free_guts_(iterator);
502
503         if(!read_only && preserve_file_stats)
504                 iterator->has_stats = get_file_stats_(filename, &iterator->stats);
505
506         if(0 == (iterator->filename = strdup(filename))) {
507                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
508                 return false;
509         }
510         if(0 != tempfile_path_prefix && 0 == (iterator->tempfile_path_prefix = strdup(tempfile_path_prefix))) {
511                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
512                 return false;
513         }
514
515         return simple_iterator_prime_input_(iterator, read_only);
516 }
517
518 FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator)
519 {
520         FLAC__ASSERT(0 != iterator);
521         FLAC__ASSERT(0 != iterator->file);
522
523         return iterator->is_writable;
524 }
525
526 FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator)
527 {
528         FLAC__ASSERT(0 != iterator);
529         FLAC__ASSERT(0 != iterator->file);
530
531         if(iterator->is_last)
532                 return false;
533
534         if(0 != fseeko(iterator->file, iterator->length, SEEK_CUR)) {
535                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
536                 return false;
537         }
538
539         iterator->offset[iterator->depth] = ftello(iterator->file);
540
541         return read_metadata_block_header_(iterator);
542 }
543
544 FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator)
545 {
546         off_t this_offset;
547
548         FLAC__ASSERT(0 != iterator);
549         FLAC__ASSERT(0 != iterator->file);
550
551         if(iterator->offset[iterator->depth] == iterator->first_offset)
552                 return false;
553
554         if(0 != fseeko(iterator->file, iterator->first_offset, SEEK_SET)) {
555                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
556                 return false;
557         }
558         this_offset = iterator->first_offset;
559         if(!read_metadata_block_header_(iterator))
560                 return false;
561
562         /* we ignore any error from ftello() and catch it in fseeko() */
563         while(ftello(iterator->file) + (off_t)iterator->length < iterator->offset[iterator->depth]) {
564                 if(0 != fseeko(iterator->file, iterator->length, SEEK_CUR)) {
565                         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
566                         return false;
567                 }
568                 this_offset = ftello(iterator->file);
569                 if(!read_metadata_block_header_(iterator))
570                         return false;
571         }
572
573         iterator->offset[iterator->depth] = this_offset;
574
575         return true;
576 }
577
578 /*@@@@add to tests*/
579 FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator)
580 {
581         FLAC__ASSERT(0 != iterator);
582         FLAC__ASSERT(0 != iterator->file);
583
584         return iterator->is_last;
585 }
586
587 /*@@@@add to tests*/
588 FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator)
589 {
590         FLAC__ASSERT(0 != iterator);
591         FLAC__ASSERT(0 != iterator->file);
592
593         return iterator->offset[iterator->depth];
594 }
595
596 FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator)
597 {
598         FLAC__ASSERT(0 != iterator);
599         FLAC__ASSERT(0 != iterator->file);
600
601         return iterator->type;
602 }
603
604 /*@@@@add to tests*/
605 FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator)
606 {
607         FLAC__ASSERT(0 != iterator);
608         FLAC__ASSERT(0 != iterator->file);
609
610         return iterator->length;
611 }
612
613 /*@@@@add to tests*/
614 FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id)
615 {
616         const unsigned id_bytes = FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8;
617
618         FLAC__ASSERT(0 != iterator);
619         FLAC__ASSERT(0 != iterator->file);
620         FLAC__ASSERT(0 != id);
621
622         if(iterator->type != FLAC__METADATA_TYPE_APPLICATION) {
623                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT;
624                 return false;
625         }
626
627         if(fread(id, 1, id_bytes, iterator->file) != id_bytes) {
628                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
629                 return false;
630         }
631
632         /* back up */
633         if(0 != fseeko(iterator->file, -((int)id_bytes), SEEK_CUR)) {
634                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
635                 return false;
636         }
637
638         return true;
639 }
640
641 FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator)
642 {
643         FLAC__StreamMetadata *block = FLAC__metadata_object_new(iterator->type);
644
645         FLAC__ASSERT(0 != iterator);
646         FLAC__ASSERT(0 != iterator->file);
647
648         if(0 != block) {
649                 block->is_last = iterator->is_last;
650                 block->length = iterator->length;
651
652                 if(!read_metadata_block_data_(iterator, block)) {
653                         FLAC__metadata_object_delete(block);
654                         return 0;
655                 }
656
657                 /* back up to the beginning of the block data to stay consistent */
658                 if(0 != fseeko(iterator->file, iterator->offset[iterator->depth] + FLAC__STREAM_METADATA_HEADER_LENGTH, SEEK_SET)) {
659                         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
660                         FLAC__metadata_object_delete(block);
661                         return 0;
662                 }
663         }
664         else
665                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
666
667         return block;
668 }
669
670 FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding)
671 {
672         FLAC__ASSERT_DECLARATION(off_t debug_target_offset = iterator->offset[iterator->depth];)
673         FLAC__bool ret;
674
675         FLAC__ASSERT(0 != iterator);
676         FLAC__ASSERT(0 != iterator->file);
677         FLAC__ASSERT(0 != block);
678
679         if(!iterator->is_writable) {
680                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE;
681                 return false;
682         }
683
684         if(iterator->type == FLAC__METADATA_TYPE_STREAMINFO || block->type == FLAC__METADATA_TYPE_STREAMINFO) {
685                 if(iterator->type != block->type) {
686                         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT;
687                         return false;
688                 }
689         }
690
691         block->is_last = iterator->is_last;
692
693         if(iterator->length == block->length)
694                 return write_metadata_block_stationary_(iterator, block);
695         else if(iterator->length > block->length) {
696                 if(use_padding && iterator->length >= FLAC__STREAM_METADATA_HEADER_LENGTH + block->length) {
697                         ret = write_metadata_block_stationary_with_padding_(iterator, block, iterator->length - FLAC__STREAM_METADATA_HEADER_LENGTH - block->length, block->is_last);
698                         FLAC__ASSERT(!ret || iterator->offset[iterator->depth] == debug_target_offset);
699                         FLAC__ASSERT(!ret || ftello(iterator->file) == debug_target_offset + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH);
700                         return ret;
701                 }
702                 else {
703                         ret = rewrite_whole_file_(iterator, block, /*append=*/false);
704                         FLAC__ASSERT(!ret || iterator->offset[iterator->depth] == debug_target_offset);
705                         FLAC__ASSERT(!ret || ftello(iterator->file) == debug_target_offset + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH);
706                         return ret;
707                 }
708         }
709         else /* iterator->length < block->length */ {
710                 unsigned padding_leftover = 0;
711                 FLAC__bool padding_is_last = false;
712                 if(use_padding) {
713                         /* first see if we can even use padding */
714                         if(iterator->is_last) {
715                                 use_padding = false;
716                         }
717                         else {
718                                 const unsigned extra_padding_bytes_required = block->length - iterator->length;
719                                 simple_iterator_push_(iterator);
720                                 if(!FLAC__metadata_simple_iterator_next(iterator)) {
721                                         (void)simple_iterator_pop_(iterator);
722                                         return false;
723                                 }
724                                 if(iterator->type != FLAC__METADATA_TYPE_PADDING) {
725                                         use_padding = false;
726                                 }
727                                 else {
728                                         if(FLAC__STREAM_METADATA_HEADER_LENGTH + iterator->length == extra_padding_bytes_required) {
729                                                 padding_leftover = 0;
730                                                 block->is_last = iterator->is_last;
731                                         }
732                                         else if(iterator->length < extra_padding_bytes_required)
733                                                 use_padding = false;
734                                         else {
735                                                 padding_leftover = FLAC__STREAM_METADATA_HEADER_LENGTH + iterator->length - extra_padding_bytes_required;
736                                                 padding_is_last = iterator->is_last;
737                                                 block->is_last = false;
738                                         }
739                                 }
740                                 if(!simple_iterator_pop_(iterator))
741                                         return false;
742                         }
743                 }
744                 if(use_padding) {
745                         if(padding_leftover == 0) {
746                                 ret = write_metadata_block_stationary_(iterator, block);
747                                 FLAC__ASSERT(!ret || iterator->offset[iterator->depth] == debug_target_offset);
748                                 FLAC__ASSERT(!ret || ftello(iterator->file) == debug_target_offset + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH);
749                                 return ret;
750                         }
751                         else {
752                                 FLAC__ASSERT(padding_leftover >= FLAC__STREAM_METADATA_HEADER_LENGTH);
753                                 ret = write_metadata_block_stationary_with_padding_(iterator, block, padding_leftover - FLAC__STREAM_METADATA_HEADER_LENGTH, padding_is_last);
754                                 FLAC__ASSERT(!ret || iterator->offset[iterator->depth] == debug_target_offset);
755                                 FLAC__ASSERT(!ret || ftello(iterator->file) == debug_target_offset + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH);
756                                 return ret;
757                         }
758                 }
759                 else {
760                         ret = rewrite_whole_file_(iterator, block, /*append=*/false);
761                         FLAC__ASSERT(!ret || iterator->offset[iterator->depth] == debug_target_offset);
762                         FLAC__ASSERT(!ret || ftello(iterator->file) == debug_target_offset + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH);
763                         return ret;
764                 }
765         }
766 }
767
768 FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding)
769 {
770         unsigned padding_leftover = 0;
771         FLAC__bool padding_is_last = false;
772
773         FLAC__ASSERT_DECLARATION(off_t debug_target_offset = iterator->offset[iterator->depth] + FLAC__STREAM_METADATA_HEADER_LENGTH + iterator->length;)
774         FLAC__bool ret;
775
776         FLAC__ASSERT(0 != iterator);
777         FLAC__ASSERT(0 != iterator->file);
778         FLAC__ASSERT(0 != block);
779
780         if(!iterator->is_writable)
781                 return false;
782
783         if(block->type == FLAC__METADATA_TYPE_STREAMINFO) {
784                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT;
785                 return false;
786         }
787
788         block->is_last = iterator->is_last;
789
790         if(use_padding) {
791                 /* first see if we can even use padding */
792                 if(iterator->is_last) {
793                         use_padding = false;
794                 }
795                 else {
796                         simple_iterator_push_(iterator);
797                         if(!FLAC__metadata_simple_iterator_next(iterator)) {
798                                 (void)simple_iterator_pop_(iterator);
799                                 return false;
800                         }
801                         if(iterator->type != FLAC__METADATA_TYPE_PADDING) {
802                                 use_padding = false;
803                         }
804                         else {
805                                 if(iterator->length == block->length) {
806                                         padding_leftover = 0;
807                                         block->is_last = iterator->is_last;
808                                 }
809                                 else if(iterator->length < FLAC__STREAM_METADATA_HEADER_LENGTH + block->length)
810                                         use_padding = false;
811                                 else {
812                                         padding_leftover = iterator->length - block->length;
813                                         padding_is_last = iterator->is_last;
814                                         block->is_last = false;
815                                 }
816                         }
817                         if(!simple_iterator_pop_(iterator))
818                                 return false;
819                 }
820         }
821         if(use_padding) {
822                 /* move to the next block, which is suitable padding */
823                 if(!FLAC__metadata_simple_iterator_next(iterator))
824                         return false;
825                 if(padding_leftover == 0) {
826                         ret = write_metadata_block_stationary_(iterator, block);
827                         FLAC__ASSERT(iterator->offset[iterator->depth] == debug_target_offset);
828                         FLAC__ASSERT(ftello(iterator->file) == debug_target_offset + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH);
829                         return ret;
830                 }
831                 else {
832                         FLAC__ASSERT(padding_leftover >= FLAC__STREAM_METADATA_HEADER_LENGTH);
833                         ret = write_metadata_block_stationary_with_padding_(iterator, block, padding_leftover - FLAC__STREAM_METADATA_HEADER_LENGTH, padding_is_last);
834                         FLAC__ASSERT(iterator->offset[iterator->depth] == debug_target_offset);
835                         FLAC__ASSERT(ftello(iterator->file) == debug_target_offset + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH);
836                         return ret;
837                 }
838         }
839         else {
840                 ret = rewrite_whole_file_(iterator, block, /*append=*/true);
841                 FLAC__ASSERT(iterator->offset[iterator->depth] == debug_target_offset);
842                 FLAC__ASSERT(ftello(iterator->file) == debug_target_offset + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH);
843                 return ret;
844         }
845 }
846
847 FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding)
848 {
849         FLAC__ASSERT_DECLARATION(off_t debug_target_offset = iterator->offset[iterator->depth];)
850         FLAC__bool ret;
851
852         if(iterator->type == FLAC__METADATA_TYPE_STREAMINFO) {
853                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT;
854                 return false;
855         }
856
857         if(use_padding) {
858                 FLAC__StreamMetadata *padding = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING);
859                 if(0 == padding) {
860                         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
861                         return false;
862                 }
863                 padding->length = iterator->length;
864                 if(!FLAC__metadata_simple_iterator_set_block(iterator, padding, false)) {
865                         FLAC__metadata_object_delete(padding);
866                         return false;
867                 }
868                 FLAC__metadata_object_delete(padding);
869                 if(!FLAC__metadata_simple_iterator_prev(iterator))
870                         return false;
871                 FLAC__ASSERT(iterator->offset[iterator->depth] + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH + (off_t)iterator->length == debug_target_offset);
872                 FLAC__ASSERT(ftello(iterator->file) + (off_t)iterator->length == debug_target_offset);
873                 return true;
874         }
875         else {
876                 ret = rewrite_whole_file_(iterator, 0, /*append=*/false);
877                 FLAC__ASSERT(iterator->offset[iterator->depth] + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH + (off_t)iterator->length == debug_target_offset);
878                 FLAC__ASSERT(ftello(iterator->file) + (off_t)iterator->length == debug_target_offset);
879                 return ret;
880         }
881 }
882
883
884
885 /****************************************************************************
886  *
887  * Level 2 implementation
888  *
889  ***************************************************************************/
890
891
892 typedef struct FLAC__Metadata_Node {
893         FLAC__StreamMetadata *data;
894         struct FLAC__Metadata_Node *prev, *next;
895 } FLAC__Metadata_Node;
896
897 struct FLAC__Metadata_Chain {
898         char *filename; /* will be NULL if using callbacks */
899         FLAC__bool is_ogg;
900         FLAC__Metadata_Node *head;
901         FLAC__Metadata_Node *tail;
902         unsigned nodes;
903         FLAC__Metadata_ChainStatus status;
904         off_t first_offset, last_offset;
905         /*
906          * This is the length of the chain initially read from the FLAC file.
907          * it is used to compare against the current length to decide whether
908          * or not the whole file has to be rewritten.
909          */
910         off_t initial_length;
911         /* @@@ hacky, these are currently only needed by ogg reader */
912         FLAC__IOHandle handle;
913         FLAC__IOCallback_Read read_cb;
914 };
915
916 struct FLAC__Metadata_Iterator {
917         FLAC__Metadata_Chain *chain;
918         FLAC__Metadata_Node *current;
919 };
920
921 FLAC_API const char * const FLAC__Metadata_ChainStatusString[] = {
922         "FLAC__METADATA_CHAIN_STATUS_OK",
923         "FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT",
924         "FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE",
925         "FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE",
926         "FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE",
927         "FLAC__METADATA_CHAIN_STATUS_BAD_METADATA",
928         "FLAC__METADATA_CHAIN_STATUS_READ_ERROR",
929         "FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR",
930         "FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR",
931         "FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR",
932         "FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR",
933         "FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR",
934         "FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR",
935         "FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS",
936         "FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH",
937         "FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL"
938 };
939
940
941 static FLAC__Metadata_Node *node_new_(void)
942 {
943         return calloc(1, sizeof(FLAC__Metadata_Node));
944 }
945
946 static void node_delete_(FLAC__Metadata_Node *node)
947 {
948         FLAC__ASSERT(0 != node);
949         if(0 != node->data)
950                 FLAC__metadata_object_delete(node->data);
951         free(node);
952 }
953
954 static void chain_init_(FLAC__Metadata_Chain *chain)
955 {
956         FLAC__ASSERT(0 != chain);
957
958         chain->filename = 0;
959         chain->is_ogg = false;
960         chain->head = chain->tail = 0;
961         chain->nodes = 0;
962         chain->status = FLAC__METADATA_CHAIN_STATUS_OK;
963         chain->initial_length = 0;
964         chain->read_cb = 0;
965 }
966
967 static void chain_clear_(FLAC__Metadata_Chain *chain)
968 {
969         FLAC__Metadata_Node *node, *next;
970
971         FLAC__ASSERT(0 != chain);
972
973         for(node = chain->head; node; ) {
974                 next = node->next;
975                 node_delete_(node);
976                 node = next;
977         }
978
979         if(0 != chain->filename)
980                 free(chain->filename);
981
982         chain_init_(chain);
983 }
984
985 static void chain_append_node_(FLAC__Metadata_Chain *chain, FLAC__Metadata_Node *node)
986 {
987         FLAC__ASSERT(0 != chain);
988         FLAC__ASSERT(0 != node);
989         FLAC__ASSERT(0 != node->data);
990
991         node->next = node->prev = 0;
992         node->data->is_last = true;
993         if(0 != chain->tail)
994                 chain->tail->data->is_last = false;
995
996         if(0 == chain->head)
997                 chain->head = node;
998         else {
999                 FLAC__ASSERT(0 != chain->tail);
1000                 chain->tail->next = node;
1001                 node->prev = chain->tail;
1002         }
1003         chain->tail = node;
1004         chain->nodes++;
1005 }
1006
1007 static void chain_remove_node_(FLAC__Metadata_Chain *chain, FLAC__Metadata_Node *node)
1008 {
1009         FLAC__ASSERT(0 != chain);
1010         FLAC__ASSERT(0 != node);
1011
1012         if(node == chain->head)
1013                 chain->head = node->next;
1014         else
1015                 node->prev->next = node->next;
1016
1017         if(node == chain->tail)
1018                 chain->tail = node->prev;
1019         else
1020                 node->next->prev = node->prev;
1021
1022         if(0 != chain->tail)
1023                 chain->tail->data->is_last = true;
1024
1025         chain->nodes--;
1026 }
1027
1028 static void chain_delete_node_(FLAC__Metadata_Chain *chain, FLAC__Metadata_Node *node)
1029 {
1030         chain_remove_node_(chain, node);
1031         node_delete_(node);
1032 }
1033
1034 static off_t chain_calculate_length_(FLAC__Metadata_Chain *chain)
1035 {
1036         const FLAC__Metadata_Node *node;
1037         off_t length = 0;
1038         for(node = chain->head; node; node = node->next)
1039                 length += (FLAC__STREAM_METADATA_HEADER_LENGTH + node->data->length);
1040         return length;
1041 }
1042
1043 static void iterator_insert_node_(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Node *node)
1044 {
1045         FLAC__ASSERT(0 != node);
1046         FLAC__ASSERT(0 != node->data);
1047         FLAC__ASSERT(0 != iterator);
1048         FLAC__ASSERT(0 != iterator->current);
1049         FLAC__ASSERT(0 != iterator->chain);
1050         FLAC__ASSERT(0 != iterator->chain->head);
1051         FLAC__ASSERT(0 != iterator->chain->tail);
1052
1053         node->data->is_last = false;
1054
1055         node->prev = iterator->current->prev;
1056         node->next = iterator->current;
1057
1058         if(0 == node->prev)
1059                 iterator->chain->head = node;
1060         else
1061                 node->prev->next = node;
1062
1063         iterator->current->prev = node;
1064
1065         iterator->chain->nodes++;
1066 }
1067
1068 static void iterator_insert_node_after_(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Node *node)
1069 {
1070         FLAC__ASSERT(0 != node);
1071         FLAC__ASSERT(0 != node->data);
1072         FLAC__ASSERT(0 != iterator);
1073         FLAC__ASSERT(0 != iterator->current);
1074         FLAC__ASSERT(0 != iterator->chain);
1075         FLAC__ASSERT(0 != iterator->chain->head);
1076         FLAC__ASSERT(0 != iterator->chain->tail);
1077
1078         iterator->current->data->is_last = false;
1079
1080         node->prev = iterator->current;
1081         node->next = iterator->current->next;
1082
1083         if(0 == node->next)
1084                 iterator->chain->tail = node;
1085         else
1086                 node->next->prev = node;
1087
1088         node->prev->next = node;
1089
1090         iterator->chain->tail->data->is_last = true;
1091
1092         iterator->chain->nodes++;
1093 }
1094
1095 /* return true iff node and node->next are both padding */
1096 static FLAC__bool chain_merge_adjacent_padding_(FLAC__Metadata_Chain *chain, FLAC__Metadata_Node *node)
1097 {
1098         if(node->data->type == FLAC__METADATA_TYPE_PADDING && 0 != node->next && node->next->data->type == FLAC__METADATA_TYPE_PADDING) {
1099                 const unsigned growth = FLAC__STREAM_METADATA_HEADER_LENGTH + node->next->data->length;
1100                 node->data->length += growth;
1101
1102                 chain_delete_node_(chain, node->next);
1103                 return true;
1104         }
1105         else
1106                 return false;
1107 }
1108
1109 /* Returns the new length of the chain, or 0 if there was an error. */
1110 /* WATCHOUT: This can get called multiple times before a write, so
1111  * it should still work when this happens.
1112  */
1113 /* WATCHOUT: Make sure to also update the logic in
1114  * FLAC__metadata_chain_check_if_tempfile_needed() if the logic here changes.
1115  */
1116 static off_t chain_prepare_for_write_(FLAC__Metadata_Chain *chain, FLAC__bool use_padding)
1117 {
1118         off_t current_length = chain_calculate_length_(chain);
1119
1120         if(use_padding) {
1121                 /* if the metadata shrank and the last block is padding, we just extend the last padding block */
1122                 if(current_length < chain->initial_length && chain->tail->data->type == FLAC__METADATA_TYPE_PADDING) {
1123                         const off_t delta = chain->initial_length - current_length;
1124                         chain->tail->data->length += delta;
1125                         current_length += delta;
1126                         FLAC__ASSERT(current_length == chain->initial_length);
1127                 }
1128                 /* if the metadata shrank more than 4 bytes then there's room to add another padding block */
1129                 else if(current_length + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH <= chain->initial_length) {
1130                         FLAC__StreamMetadata *padding;
1131                         FLAC__Metadata_Node *node;
1132                         if(0 == (padding = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING))) {
1133                                 chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
1134                                 return 0;
1135                         }
1136                         padding->length = chain->initial_length - (FLAC__STREAM_METADATA_HEADER_LENGTH + current_length);
1137                         if(0 == (node = node_new_())) {
1138                                 FLAC__metadata_object_delete(padding);
1139                                 chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
1140                                 return 0;
1141                         }
1142                         node->data = padding;
1143                         chain_append_node_(chain, node);
1144                         current_length = chain_calculate_length_(chain);
1145                         FLAC__ASSERT(current_length == chain->initial_length);
1146                 }
1147                 /* if the metadata grew but the last block is padding, try cutting the padding to restore the original length so we don't have to rewrite the whole file */
1148                 else if(current_length > chain->initial_length) {
1149                         const off_t delta = current_length - chain->initial_length;
1150                         if(chain->tail->data->type == FLAC__METADATA_TYPE_PADDING) {
1151                                 /* if the delta is exactly the size of the last padding block, remove the padding block */
1152                                 if((off_t)chain->tail->data->length + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH == delta) {
1153                                         chain_delete_node_(chain, chain->tail);
1154                                         current_length = chain_calculate_length_(chain);
1155                                         FLAC__ASSERT(current_length == chain->initial_length);
1156                                 }
1157                                 /* if there is at least 'delta' bytes of padding, trim the padding down */
1158                                 else if((off_t)chain->tail->data->length >= delta) {
1159                                         chain->tail->data->length -= delta;
1160                                         current_length -= delta;
1161                                         FLAC__ASSERT(current_length == chain->initial_length);
1162                                 }
1163                         }
1164                 }
1165         }
1166
1167         return current_length;
1168 }
1169
1170 static FLAC__bool chain_read_cb_(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Seek seek_cb, FLAC__IOCallback_Tell tell_cb)
1171 {
1172         FLAC__Metadata_Node *node;
1173
1174         FLAC__ASSERT(0 != chain);
1175
1176         /* we assume we're already at the beginning of the file */
1177
1178         switch(seek_to_first_metadata_block_cb_(handle, read_cb, seek_cb)) {
1179                 case 0:
1180                         break;
1181                 case 1:
1182                         chain->status = FLAC__METADATA_CHAIN_STATUS_READ_ERROR;
1183                         return false;
1184                 case 2:
1185                         chain->status = FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR;
1186                         return false;
1187                 case 3:
1188                         chain->status = FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE;
1189                         return false;
1190                 default:
1191                         FLAC__ASSERT(0);
1192                         return false;
1193         }
1194
1195         {
1196                 FLAC__int64 pos = tell_cb(handle);
1197                 if(pos < 0) {
1198                         chain->status = FLAC__METADATA_CHAIN_STATUS_READ_ERROR;
1199                         return false;
1200                 }
1201                 chain->first_offset = (off_t)pos;
1202         }
1203
1204         {
1205                 FLAC__bool is_last;
1206                 FLAC__MetadataType type;
1207                 unsigned length;
1208
1209                 do {
1210                         node = node_new_();
1211                         if(0 == node) {
1212                                 chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
1213                                 return false;
1214                         }
1215
1216                         if(!read_metadata_block_header_cb_(handle, read_cb, &is_last, &type, &length)) {
1217                                 node_delete_(node);
1218                                 chain->status = FLAC__METADATA_CHAIN_STATUS_READ_ERROR;
1219                                 return false;
1220                         }
1221
1222                         node->data = FLAC__metadata_object_new(type);
1223                         if(0 == node->data) {
1224                                 node_delete_(node);
1225                                 chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
1226                                 return false;
1227                         }
1228
1229                         node->data->is_last = is_last;
1230                         node->data->length = length;
1231
1232                         chain->status = get_equivalent_status_(read_metadata_block_data_cb_(handle, read_cb, seek_cb, node->data));
1233                         if(chain->status != FLAC__METADATA_CHAIN_STATUS_OK) {
1234                                 node_delete_(node);
1235                                 return false;
1236                         }
1237                         chain_append_node_(chain, node);
1238                 } while(!is_last);
1239         }
1240
1241         {
1242                 FLAC__int64 pos = tell_cb(handle);
1243                 if(pos < 0) {
1244                         chain->status = FLAC__METADATA_CHAIN_STATUS_READ_ERROR;
1245                         return false;
1246                 }
1247                 chain->last_offset = (off_t)pos;
1248         }
1249
1250         chain->initial_length = chain_calculate_length_(chain);
1251
1252         return true;
1253 }
1254
1255 static FLAC__StreamDecoderReadStatus chain_read_ogg_read_cb_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
1256 {
1257         FLAC__Metadata_Chain *chain = (FLAC__Metadata_Chain*)client_data;
1258         (void)decoder;
1259         if(*bytes > 0 && chain->status == FLAC__METADATA_CHAIN_STATUS_OK) {
1260                 *bytes = chain->read_cb(buffer, sizeof(FLAC__byte), *bytes, chain->handle);
1261                 if(*bytes == 0)
1262                         return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
1263                 else
1264                         return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
1265         }
1266         else
1267                 return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
1268 }
1269
1270 static FLAC__StreamDecoderWriteStatus chain_read_ogg_write_cb_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
1271 {
1272         (void)decoder, (void)frame, (void)buffer, (void)client_data;
1273         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
1274 }
1275
1276 static void chain_read_ogg_metadata_cb_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
1277 {
1278         FLAC__Metadata_Chain *chain = (FLAC__Metadata_Chain*)client_data;
1279         FLAC__Metadata_Node *node;
1280
1281         (void)decoder;
1282
1283         node = node_new_();
1284         if(0 == node) {
1285                 chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
1286                 return;
1287         }
1288
1289         node->data = FLAC__metadata_object_clone(metadata);
1290         if(0 == node->data) {
1291                 node_delete_(node);
1292                 chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
1293                 return;
1294         }
1295
1296         chain_append_node_(chain, node);
1297 }
1298
1299 static void chain_read_ogg_error_cb_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
1300 {
1301         FLAC__Metadata_Chain *chain = (FLAC__Metadata_Chain*)client_data;
1302         (void)decoder, (void)status;
1303         chain->status = FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR; /*@@@ maybe needs better error code */
1304 }
1305
1306 static FLAC__bool chain_read_ogg_cb_(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb)
1307 {
1308         FLAC__StreamDecoder *decoder;
1309
1310         FLAC__ASSERT(0 != chain);
1311
1312         /* we assume we're already at the beginning of the file */
1313
1314         chain->handle = handle;
1315         chain->read_cb = read_cb;
1316         if(0 == (decoder = FLAC__stream_decoder_new())) {
1317                 chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
1318                 return false;
1319         }
1320         FLAC__stream_decoder_set_metadata_respond_all(decoder);
1321         if(FLAC__stream_decoder_init_ogg_stream(decoder, chain_read_ogg_read_cb_, /*seek_callback=*/0, /*tell_callback=*/0, /*length_callback=*/0, /*eof_callback=*/0, chain_read_ogg_write_cb_, chain_read_ogg_metadata_cb_, chain_read_ogg_error_cb_, chain) != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
1322                 FLAC__stream_decoder_delete(decoder);
1323                 chain->status = FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR; /*@@@ maybe needs better error code */
1324                 return false;
1325         }
1326
1327         chain->first_offset = 0; /*@@@ wrong; will need to be set correctly to implement metadata writing for Ogg FLAC */
1328
1329         if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder))
1330                 chain->status = FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR; /*@@@ maybe needs better error code */
1331         if(chain->status != FLAC__METADATA_CHAIN_STATUS_OK) {
1332                 FLAC__stream_decoder_delete(decoder);
1333                 return false;
1334         }
1335
1336         FLAC__stream_decoder_delete(decoder);
1337
1338         chain->last_offset = 0; /*@@@ wrong; will need to be set correctly to implement metadata writing for Ogg FLAC */
1339
1340         chain->initial_length = chain_calculate_length_(chain);
1341
1342         return true;
1343 }
1344
1345 static FLAC__bool chain_rewrite_metadata_in_place_cb_(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, FLAC__IOCallback_Seek seek_cb)
1346 {
1347         FLAC__Metadata_Node *node;
1348
1349         FLAC__ASSERT(0 != chain);
1350         FLAC__ASSERT(0 != chain->head);
1351
1352         if(0 != seek_cb(handle, chain->first_offset, SEEK_SET)) {
1353                 chain->status = FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR;
1354                 return false;
1355         }
1356
1357         for(node = chain->head; node; node = node->next) {
1358                 if(!write_metadata_block_header_cb_(handle, write_cb, node->data)) {
1359                         chain->status = FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR;
1360                         return false;
1361                 }
1362                 if(!write_metadata_block_data_cb_(handle, write_cb, node->data)) {
1363                         chain->status = FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR;
1364                         return false;
1365                 }
1366         }
1367
1368         /*FLAC__ASSERT(fflush(), ftello() == chain->last_offset);*/
1369
1370         chain->status = FLAC__METADATA_CHAIN_STATUS_OK;
1371         return true;
1372 }
1373
1374 static FLAC__bool chain_rewrite_metadata_in_place_(FLAC__Metadata_Chain *chain)
1375 {
1376         FILE *file;
1377         FLAC__bool ret;
1378
1379         FLAC__ASSERT(0 != chain->filename);
1380
1381         if(0 == (file = fopen(chain->filename, "r+b"))) {
1382                 chain->status = FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE;
1383                 return false;
1384         }
1385
1386         /* chain_rewrite_metadata_in_place_cb_() sets chain->status for us */
1387         ret = chain_rewrite_metadata_in_place_cb_(chain, (FLAC__IOHandle)file, (FLAC__IOCallback_Write)fwrite, fseek_wrapper_);
1388
1389         fclose(file);
1390
1391         return ret;
1392 }
1393
1394 static FLAC__bool chain_rewrite_file_(FLAC__Metadata_Chain *chain, const char *tempfile_path_prefix)
1395 {
1396         FILE *f, *tempfile;
1397         char *tempfilename;
1398         FLAC__Metadata_SimpleIteratorStatus status;
1399         const FLAC__Metadata_Node *node;
1400
1401         FLAC__ASSERT(0 != chain);
1402         FLAC__ASSERT(0 != chain->filename);
1403         FLAC__ASSERT(0 != chain->head);
1404
1405         /* copy the file prefix (data up to first metadata block */
1406         if(0 == (f = fopen(chain->filename, "rb"))) {
1407                 chain->status = FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE;
1408                 return false;
1409         }
1410         if(!open_tempfile_(chain->filename, tempfile_path_prefix, &tempfile, &tempfilename, &status)) {
1411                 chain->status = get_equivalent_status_(status);
1412                 goto err;
1413         }
1414         if(!copy_n_bytes_from_file_(f, tempfile, chain->first_offset, &status)) {
1415                 chain->status = get_equivalent_status_(status);
1416                 goto err;
1417         }
1418
1419         /* write the metadata */
1420         for(node = chain->head; node; node = node->next) {
1421                 if(!write_metadata_block_header_(tempfile, &status, node->data)) {
1422                         chain->status = get_equivalent_status_(status);
1423                         goto err;
1424                 }
1425                 if(!write_metadata_block_data_(tempfile, &status, node->data)) {
1426                         chain->status = get_equivalent_status_(status);
1427                         goto err;
1428                 }
1429         }
1430         /*FLAC__ASSERT(fflush(), ftello() == chain->last_offset);*/
1431
1432         /* copy the file postfix (everything after the metadata) */
1433         if(0 != fseeko(f, chain->last_offset, SEEK_SET)) {
1434                 chain->status = FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR;
1435                 goto err;
1436         }
1437         if(!copy_remaining_bytes_from_file_(f, tempfile, &status)) {
1438                 chain->status = get_equivalent_status_(status);
1439                 goto err;
1440         }
1441
1442         /* move the tempfile on top of the original */
1443         (void)fclose(f);
1444         if(!transport_tempfile_(chain->filename, &tempfile, &tempfilename, &status))
1445                 return false;
1446
1447         return true;
1448
1449 err:
1450         (void)fclose(f);
1451         cleanup_tempfile_(&tempfile, &tempfilename);
1452         return false;
1453 }
1454
1455 /* assumes 'handle' is already at beginning of file */
1456 static FLAC__bool chain_rewrite_file_cb_(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Seek seek_cb, FLAC__IOCallback_Eof eof_cb, FLAC__IOHandle temp_handle, FLAC__IOCallback_Write temp_write_cb)
1457 {
1458         FLAC__Metadata_SimpleIteratorStatus status;
1459         const FLAC__Metadata_Node *node;
1460
1461         FLAC__ASSERT(0 != chain);
1462         FLAC__ASSERT(0 == chain->filename);
1463         FLAC__ASSERT(0 != chain->head);
1464
1465         /* copy the file prefix (data up to first metadata block */
1466         if(!copy_n_bytes_from_file_cb_(handle, read_cb, temp_handle, temp_write_cb, chain->first_offset, &status)) {
1467                 chain->status = get_equivalent_status_(status);
1468                 return false;
1469         }
1470
1471         /* write the metadata */
1472         for(node = chain->head; node; node = node->next) {
1473                 if(!write_metadata_block_header_cb_(temp_handle, temp_write_cb, node->data)) {
1474                         chain->status = FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR;
1475                         return false;
1476                 }
1477                 if(!write_metadata_block_data_cb_(temp_handle, temp_write_cb, node->data)) {
1478                         chain->status = FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR;
1479                         return false;
1480                 }
1481         }
1482         /*FLAC__ASSERT(fflush(), ftello() == chain->last_offset);*/
1483
1484         /* copy the file postfix (everything after the metadata) */
1485         if(0 != seek_cb(handle, chain->last_offset, SEEK_SET)) {
1486                 chain->status = FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR;
1487                 return false;
1488         }
1489         if(!copy_remaining_bytes_from_file_cb_(handle, read_cb, eof_cb, temp_handle, temp_write_cb, &status)) {
1490                 chain->status = get_equivalent_status_(status);
1491                 return false;
1492         }
1493
1494         return true;
1495 }
1496
1497 FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void)
1498 {
1499         FLAC__Metadata_Chain *chain = calloc(1, sizeof(FLAC__Metadata_Chain));
1500
1501         if(0 != chain)
1502                 chain_init_(chain);
1503
1504         return chain;
1505 }
1506
1507 FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain)
1508 {
1509         FLAC__ASSERT(0 != chain);
1510
1511         chain_clear_(chain);
1512
1513         free(chain);
1514 }
1515
1516 FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain)
1517 {
1518         FLAC__Metadata_ChainStatus status;
1519
1520         FLAC__ASSERT(0 != chain);
1521
1522         status = chain->status;
1523         chain->status = FLAC__METADATA_CHAIN_STATUS_OK;
1524         return status;
1525 }
1526
1527 static FLAC__bool chain_read_(FLAC__Metadata_Chain *chain, const char *filename, FLAC__bool is_ogg)
1528 {
1529         FILE *file;
1530         FLAC__bool ret;
1531
1532         FLAC__ASSERT(0 != chain);
1533         FLAC__ASSERT(0 != filename);
1534
1535         chain_clear_(chain);
1536
1537         if(0 == (chain->filename = strdup(filename))) {
1538                 chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
1539                 return false;
1540         }
1541
1542         chain->is_ogg = is_ogg;
1543
1544         if(0 == (file = fopen(filename, "rb"))) {
1545                 chain->status = FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE;
1546                 return false;
1547         }
1548
1549         /* the function also sets chain->status for us */
1550         ret = is_ogg?
1551                 chain_read_ogg_cb_(chain, file, (FLAC__IOCallback_Read)fread) :
1552                 chain_read_cb_(chain, file, (FLAC__IOCallback_Read)fread, fseek_wrapper_, ftell_wrapper_)
1553         ;
1554
1555         fclose(file);
1556
1557         return ret;
1558 }
1559
1560 FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename)
1561 {
1562         return chain_read_(chain, filename, /*is_ogg=*/false);
1563 }
1564
1565 /*@@@@add to tests*/
1566 FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename)
1567 {
1568         return chain_read_(chain, filename, /*is_ogg=*/true);
1569 }
1570
1571 static FLAC__bool chain_read_with_callbacks_(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks, FLAC__bool is_ogg)
1572 {
1573         FLAC__bool ret;
1574
1575         FLAC__ASSERT(0 != chain);
1576
1577         chain_clear_(chain);
1578
1579         if (0 == callbacks.read || 0 == callbacks.seek || 0 == callbacks.tell) {
1580                 chain->status = FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS;
1581                 return false;
1582         }
1583
1584         chain->is_ogg = is_ogg;
1585
1586         /* rewind */
1587         if(0 != callbacks.seek(handle, 0, SEEK_SET)) {
1588                 chain->status = FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR;
1589                 return false;
1590         }
1591
1592         /* the function also sets chain->status for us */
1593         ret = is_ogg?
1594                 chain_read_ogg_cb_(chain, handle, callbacks.read) :
1595                 chain_read_cb_(chain, handle, callbacks.read, callbacks.seek, callbacks.tell)
1596         ;
1597
1598         return ret;
1599 }
1600
1601 FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks)
1602 {
1603         return chain_read_with_callbacks_(chain, handle, callbacks, /*is_ogg=*/false);
1604 }
1605
1606 /*@@@@add to tests*/
1607 FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks)
1608 {
1609         return chain_read_with_callbacks_(chain, handle, callbacks, /*is_ogg=*/true);
1610 }
1611
1612 FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding)
1613 {
1614         /* This does all the same checks that are in chain_prepare_for_write_()
1615          * but doesn't actually alter the chain.  Make sure to update the logic
1616          * here if chain_prepare_for_write_() changes.
1617          */
1618         const off_t current_length = chain_calculate_length_(chain);
1619
1620         FLAC__ASSERT(0 != chain);
1621
1622         if(use_padding) {
1623                 /* if the metadata shrank and the last block is padding, we just extend the last padding block */
1624                 if(current_length < chain->initial_length && chain->tail->data->type == FLAC__METADATA_TYPE_PADDING)
1625                         return false;
1626                 /* if the metadata shrank more than 4 bytes then there's room to add another padding block */
1627                 else if(current_length + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH <= chain->initial_length)
1628                         return false;
1629                 /* if the metadata grew but the last block is padding, try cutting the padding to restore the original length so we don't have to rewrite the whole file */
1630                 else if(current_length > chain->initial_length) {
1631                         const off_t delta = current_length - chain->initial_length;
1632                         if(chain->tail->data->type == FLAC__METADATA_TYPE_PADDING) {
1633                                 /* if the delta is exactly the size of the last padding block, remove the padding block */
1634                                 if((off_t)chain->tail->data->length + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH == delta)
1635                                         return false;
1636                                 /* if there is at least 'delta' bytes of padding, trim the padding down */
1637                                 else if((off_t)chain->tail->data->length >= delta)
1638                                         return false;
1639                         }
1640                 }
1641         }
1642
1643         return (current_length != chain->initial_length);
1644 }
1645
1646 FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats)
1647 {
1648         struct stat stats;
1649         const char *tempfile_path_prefix = 0;
1650         off_t current_length;
1651
1652         FLAC__ASSERT(0 != chain);
1653
1654         if (chain->is_ogg) { /* cannot write back to Ogg FLAC yet */
1655                 chain->status = FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR;
1656                 return false;
1657         }
1658
1659         if (0 == chain->filename) {
1660                 chain->status = FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH;
1661                 return false;
1662         }
1663
1664         current_length = chain_prepare_for_write_(chain, use_padding);
1665
1666         /* a return value of 0 means there was an error; chain->status is already set */
1667         if (0 == current_length)
1668                 return false;
1669
1670         if(preserve_file_stats)
1671                 get_file_stats_(chain->filename, &stats);
1672
1673         if(current_length == chain->initial_length) {
1674                 if(!chain_rewrite_metadata_in_place_(chain))
1675                         return false;
1676         }
1677         else {
1678                 if(!chain_rewrite_file_(chain, tempfile_path_prefix))
1679                         return false;
1680
1681                 /* recompute lengths and offsets */
1682                 {
1683                         const FLAC__Metadata_Node *node;
1684                         chain->initial_length = current_length;
1685                         chain->last_offset = chain->first_offset;
1686                         for(node = chain->head; node; node = node->next)
1687                                 chain->last_offset += (FLAC__STREAM_METADATA_HEADER_LENGTH + node->data->length);
1688                 }
1689         }
1690
1691         if(preserve_file_stats)
1692                 set_file_stats_(chain->filename, &stats);
1693
1694         return true;
1695 }
1696
1697 FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks)
1698 {
1699         off_t current_length;
1700
1701         FLAC__ASSERT(0 != chain);
1702
1703         if (chain->is_ogg) { /* cannot write back to Ogg FLAC yet */
1704                 chain->status = FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR;
1705                 return false;
1706         }
1707
1708         if (0 != chain->filename) {
1709                 chain->status = FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH;
1710                 return false;
1711         }
1712
1713         if (0 == callbacks.write || 0 == callbacks.seek) {
1714                 chain->status = FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS;
1715                 return false;
1716         }
1717
1718         if (FLAC__metadata_chain_check_if_tempfile_needed(chain, use_padding)) {
1719                 chain->status = FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL;
1720                 return false;
1721         }
1722
1723         current_length = chain_prepare_for_write_(chain, use_padding);
1724
1725         /* a return value of 0 means there was an error; chain->status is already set */
1726         if (0 == current_length)
1727                 return false;
1728
1729         FLAC__ASSERT(current_length == chain->initial_length);
1730
1731         return chain_rewrite_metadata_in_place_cb_(chain, handle, callbacks.write, callbacks.seek);
1732 }
1733
1734 FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks_and_tempfile(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks, FLAC__IOHandle temp_handle, FLAC__IOCallbacks temp_callbacks)
1735 {
1736         off_t current_length;
1737
1738         FLAC__ASSERT(0 != chain);
1739
1740         if (chain->is_ogg) { /* cannot write back to Ogg FLAC yet */
1741                 chain->status = FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR;
1742                 return false;
1743         }
1744
1745         if (0 != chain->filename) {
1746                 chain->status = FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH;
1747                 return false;
1748         }
1749
1750         if (0 == callbacks.read || 0 == callbacks.seek || 0 == callbacks.eof) {
1751                 chain->status = FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS;
1752                 return false;
1753         }
1754         if (0 == temp_callbacks.write) {
1755                 chain->status = FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS;
1756                 return false;
1757         }
1758
1759         if (!FLAC__metadata_chain_check_if_tempfile_needed(chain, use_padding)) {
1760                 chain->status = FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL;
1761                 return false;
1762         }
1763
1764         current_length = chain_prepare_for_write_(chain, use_padding);
1765
1766         /* a return value of 0 means there was an error; chain->status is already set */
1767         if (0 == current_length)
1768                 return false;
1769
1770         FLAC__ASSERT(current_length != chain->initial_length);
1771
1772         /* rewind */
1773         if(0 != callbacks.seek(handle, 0, SEEK_SET)) {
1774                 chain->status = FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR;
1775                 return false;
1776         }
1777
1778         if(!chain_rewrite_file_cb_(chain, handle, callbacks.read, callbacks.seek, callbacks.eof, temp_handle, temp_callbacks.write))
1779                 return false;
1780
1781         /* recompute lengths and offsets */
1782         {
1783                 const FLAC__Metadata_Node *node;
1784                 chain->initial_length = current_length;
1785                 chain->last_offset = chain->first_offset;
1786                 for(node = chain->head; node; node = node->next)
1787                         chain->last_offset += (FLAC__STREAM_METADATA_HEADER_LENGTH + node->data->length);
1788         }
1789
1790         return true;
1791 }
1792
1793 FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain)
1794 {
1795         FLAC__Metadata_Node *node;
1796
1797         FLAC__ASSERT(0 != chain);
1798
1799         for(node = chain->head; node; ) {
1800                 if(!chain_merge_adjacent_padding_(chain, node))
1801                         node = node->next;
1802         }
1803 }
1804
1805 FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain)
1806 {
1807         FLAC__Metadata_Node *node, *save;
1808         unsigned i;
1809
1810         FLAC__ASSERT(0 != chain);
1811
1812         /*
1813          * Don't try and be too smart... this simple algo is good enough for
1814          * the small number of nodes that we deal with.
1815          */
1816         for(i = 0, node = chain->head; i < chain->nodes; i++) {
1817                 if(node->data->type == FLAC__METADATA_TYPE_PADDING) {
1818                         save = node->next;
1819                         chain_remove_node_(chain, node);
1820                         chain_append_node_(chain, node);
1821                         node = save;
1822                 }
1823                 else {
1824                         node = node->next;
1825                 }
1826         }
1827
1828         FLAC__metadata_chain_merge_padding(chain);
1829 }
1830
1831
1832 FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void)
1833 {
1834         FLAC__Metadata_Iterator *iterator = calloc(1, sizeof(FLAC__Metadata_Iterator));
1835
1836         /* calloc() implies:
1837                 iterator->current = 0;
1838                 iterator->chain = 0;
1839         */
1840
1841         return iterator;
1842 }
1843
1844 FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator)
1845 {
1846         FLAC__ASSERT(0 != iterator);
1847
1848         free(iterator);
1849 }
1850
1851 FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain)
1852 {
1853         FLAC__ASSERT(0 != iterator);
1854         FLAC__ASSERT(0 != chain);
1855         FLAC__ASSERT(0 != chain->head);
1856
1857         iterator->chain = chain;
1858         iterator->current = chain->head;
1859 }
1860
1861 FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator)
1862 {
1863         FLAC__ASSERT(0 != iterator);
1864
1865         if(0 == iterator->current || 0 == iterator->current->next)
1866                 return false;
1867
1868         iterator->current = iterator->current->next;
1869         return true;
1870 }
1871
1872 FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator)
1873 {
1874         FLAC__ASSERT(0 != iterator);
1875
1876         if(0 == iterator->current || 0 == iterator->current->prev)
1877                 return false;
1878
1879         iterator->current = iterator->current->prev;
1880         return true;
1881 }
1882
1883 FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator)
1884 {
1885         FLAC__ASSERT(0 != iterator);
1886         FLAC__ASSERT(0 != iterator->current);
1887         FLAC__ASSERT(0 != iterator->current->data);
1888
1889         return iterator->current->data->type;
1890 }
1891
1892 FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator)
1893 {
1894         FLAC__ASSERT(0 != iterator);
1895         FLAC__ASSERT(0 != iterator->current);
1896
1897         return iterator->current->data;
1898 }
1899
1900 FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block)
1901 {
1902         FLAC__ASSERT(0 != iterator);
1903         FLAC__ASSERT(0 != block);
1904         return FLAC__metadata_iterator_delete_block(iterator, false) && FLAC__metadata_iterator_insert_block_after(iterator, block);
1905 }
1906
1907 FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding)
1908 {
1909         FLAC__Metadata_Node *save;
1910
1911         FLAC__ASSERT(0 != iterator);
1912         FLAC__ASSERT(0 != iterator->current);
1913
1914         if(0 == iterator->current->prev) {
1915                 FLAC__ASSERT(iterator->current->data->type == FLAC__METADATA_TYPE_STREAMINFO);
1916                 return false;
1917         }
1918
1919         save = iterator->current->prev;
1920
1921         if(replace_with_padding) {
1922                 FLAC__metadata_object_delete_data(iterator->current->data);
1923                 iterator->current->data->type = FLAC__METADATA_TYPE_PADDING;
1924         }
1925         else {
1926                 chain_delete_node_(iterator->chain, iterator->current);
1927         }
1928
1929         iterator->current = save;
1930         return true;
1931 }
1932
1933 FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block)
1934 {
1935         FLAC__Metadata_Node *node;
1936
1937         FLAC__ASSERT(0 != iterator);
1938         FLAC__ASSERT(0 != iterator->current);
1939         FLAC__ASSERT(0 != block);
1940
1941         if(block->type == FLAC__METADATA_TYPE_STREAMINFO)
1942                 return false;
1943
1944         if(0 == iterator->current->prev) {
1945                 FLAC__ASSERT(iterator->current->data->type == FLAC__METADATA_TYPE_STREAMINFO);
1946                 return false;
1947         }
1948
1949         if(0 == (node = node_new_()))
1950                 return false;
1951
1952         node->data = block;
1953         iterator_insert_node_(iterator, node);
1954         iterator->current = node;
1955         return true;
1956 }
1957
1958 FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block)
1959 {
1960         FLAC__Metadata_Node *node;
1961
1962         FLAC__ASSERT(0 != iterator);
1963         FLAC__ASSERT(0 != iterator->current);
1964         FLAC__ASSERT(0 != block);
1965
1966         if(block->type == FLAC__METADATA_TYPE_STREAMINFO)
1967                 return false;
1968
1969         if(0 == (node = node_new_()))
1970                 return false;
1971
1972         node->data = block;
1973         iterator_insert_node_after_(iterator, node);
1974         iterator->current = node;
1975         return true;
1976 }
1977
1978
1979 /****************************************************************************
1980  *
1981  * Local function definitions
1982  *
1983  ***************************************************************************/
1984
1985 void pack_uint32_(FLAC__uint32 val, FLAC__byte *b, unsigned bytes)
1986 {
1987         unsigned i;
1988
1989         b += bytes;
1990
1991         for(i = 0; i < bytes; i++) {
1992                 *(--b) = (FLAC__byte)(val & 0xff);
1993                 val >>= 8;
1994         }
1995 }
1996
1997 void pack_uint32_little_endian_(FLAC__uint32 val, FLAC__byte *b, unsigned bytes)
1998 {
1999         unsigned i;
2000
2001         for(i = 0; i < bytes; i++) {
2002                 *(b++) = (FLAC__byte)(val & 0xff);
2003                 val >>= 8;
2004         }
2005 }
2006
2007 void pack_uint64_(FLAC__uint64 val, FLAC__byte *b, unsigned bytes)
2008 {
2009         unsigned i;
2010
2011         b += bytes;
2012
2013         for(i = 0; i < bytes; i++) {
2014                 *(--b) = (FLAC__byte)(val & 0xff);
2015                 val >>= 8;
2016         }
2017 }
2018
2019 FLAC__uint32 unpack_uint32_(FLAC__byte *b, unsigned bytes)
2020 {
2021         FLAC__uint32 ret = 0;
2022         unsigned i;
2023
2024         for(i = 0; i < bytes; i++)
2025                 ret = (ret << 8) | (FLAC__uint32)(*b++);
2026
2027         return ret;
2028 }
2029
2030 FLAC__uint32 unpack_uint32_little_endian_(FLAC__byte *b, unsigned bytes)
2031 {
2032         FLAC__uint32 ret = 0;
2033         unsigned i;
2034
2035         b += bytes;
2036
2037         for(i = 0; i < bytes; i++)
2038                 ret = (ret << 8) | (FLAC__uint32)(*--b);
2039
2040         return ret;
2041 }
2042
2043 FLAC__uint64 unpack_uint64_(FLAC__byte *b, unsigned bytes)
2044 {
2045         FLAC__uint64 ret = 0;
2046         unsigned i;
2047
2048         for(i = 0; i < bytes; i++)
2049                 ret = (ret << 8) | (FLAC__uint64)(*b++);
2050
2051         return ret;
2052 }
2053
2054 FLAC__bool read_metadata_block_header_(FLAC__Metadata_SimpleIterator *iterator)
2055 {
2056         FLAC__ASSERT(0 != iterator);
2057         FLAC__ASSERT(0 != iterator->file);
2058
2059         if(!read_metadata_block_header_cb_((FLAC__IOHandle)iterator->file, (FLAC__IOCallback_Read)fread, &iterator->is_last, &iterator->type, &iterator->length)) {
2060                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2061                 return false;
2062         }
2063
2064         return true;
2065 }
2066
2067 FLAC__bool read_metadata_block_data_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block)
2068 {
2069         FLAC__ASSERT(0 != iterator);
2070         FLAC__ASSERT(0 != iterator->file);
2071
2072         iterator->status = read_metadata_block_data_cb_((FLAC__IOHandle)iterator->file, (FLAC__IOCallback_Read)fread, fseek_wrapper_, block);
2073
2074         return (iterator->status == FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK);
2075 }
2076
2077 FLAC__bool read_metadata_block_header_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__bool *is_last, FLAC__MetadataType *type, unsigned *length)
2078 {
2079         FLAC__byte raw_header[FLAC__STREAM_METADATA_HEADER_LENGTH];
2080
2081         if(read_cb(raw_header, 1, FLAC__STREAM_METADATA_HEADER_LENGTH, handle) != FLAC__STREAM_METADATA_HEADER_LENGTH)
2082                 return false;
2083
2084         *is_last = raw_header[0] & 0x80? true : false;
2085         *type = (FLAC__MetadataType)(raw_header[0] & 0x7f);
2086         *length = unpack_uint32_(raw_header + 1, 3);
2087
2088         /* Note that we don't check:
2089          *    if(iterator->type >= FLAC__METADATA_TYPE_UNDEFINED)
2090          * we just will read in an opaque block
2091          */
2092
2093         return true;
2094 }
2095
2096 FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Seek seek_cb, FLAC__StreamMetadata *block)
2097 {
2098         switch(block->type) {
2099                 case FLAC__METADATA_TYPE_STREAMINFO:
2100                         return read_metadata_block_data_streaminfo_cb_(handle, read_cb, &block->data.stream_info);
2101                 case FLAC__METADATA_TYPE_PADDING:
2102                         return read_metadata_block_data_padding_cb_(handle, seek_cb, &block->data.padding, block->length);
2103                 case FLAC__METADATA_TYPE_APPLICATION:
2104                         return read_metadata_block_data_application_cb_(handle, read_cb, &block->data.application, block->length);
2105                 case FLAC__METADATA_TYPE_SEEKTABLE:
2106                         return read_metadata_block_data_seektable_cb_(handle, read_cb, &block->data.seek_table, block->length);
2107                 case FLAC__METADATA_TYPE_VORBIS_COMMENT:
2108                         return read_metadata_block_data_vorbis_comment_cb_(handle, read_cb, &block->data.vorbis_comment);
2109                 case FLAC__METADATA_TYPE_CUESHEET:
2110                         return read_metadata_block_data_cuesheet_cb_(handle, read_cb, &block->data.cue_sheet);
2111                 case FLAC__METADATA_TYPE_PICTURE:
2112                         return read_metadata_block_data_picture_cb_(handle, read_cb, &block->data.picture);
2113                 default:
2114                         return read_metadata_block_data_unknown_cb_(handle, read_cb, &block->data.unknown, block->length);
2115         }
2116 }
2117
2118 FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_streaminfo_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_StreamInfo *block)
2119 {
2120         FLAC__byte buffer[FLAC__STREAM_METADATA_STREAMINFO_LENGTH], *b;
2121
2122         if(read_cb(buffer, 1, FLAC__STREAM_METADATA_STREAMINFO_LENGTH, handle) != FLAC__STREAM_METADATA_STREAMINFO_LENGTH)
2123                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2124
2125         b = buffer;
2126
2127         /* we are using hardcoded numbers for simplicity but we should
2128          * probably eventually write a bit-level unpacker and use the
2129          * _STREAMINFO_ constants.
2130          */
2131         block->min_blocksize = unpack_uint32_(b, 2); b += 2;
2132         block->max_blocksize = unpack_uint32_(b, 2); b += 2;
2133         block->min_framesize = unpack_uint32_(b, 3); b += 3;
2134         block->max_framesize = unpack_uint32_(b, 3); b += 3;
2135         block->sample_rate = (unpack_uint32_(b, 2) << 4) | ((unsigned)(b[2] & 0xf0) >> 4);
2136         block->channels = (unsigned)((b[2] & 0x0e) >> 1) + 1;
2137         block->bits_per_sample = ((((unsigned)(b[2] & 0x01)) << 4) | (((unsigned)(b[3] & 0xf0)) >> 4)) + 1;
2138         block->total_samples = (((FLAC__uint64)(b[3] & 0x0f)) << 32) | unpack_uint64_(b+4, 4);
2139         memcpy(block->md5sum, b+8, 16);
2140
2141         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
2142 }
2143
2144 FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_padding_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Seek seek_cb, FLAC__StreamMetadata_Padding *block, unsigned block_length)
2145 {
2146         (void)block; /* nothing to do; we don't care about reading the padding bytes */
2147
2148         if(0 != seek_cb(handle, block_length, SEEK_CUR))
2149                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
2150
2151         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
2152 }
2153
2154 FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_application_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_Application *block, unsigned block_length)
2155 {
2156         const unsigned id_bytes = FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8;
2157
2158         if(read_cb(block->id, 1, id_bytes, handle) != id_bytes)
2159                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2160
2161         if(block_length < id_bytes)
2162                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2163
2164         block_length -= id_bytes;
2165
2166         if(block_length == 0) {
2167                 block->data = 0;
2168         }
2169         else {
2170                 if(0 == (block->data = malloc(block_length)))
2171                         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
2172
2173                 if(read_cb(block->data, 1, block_length, handle) != block_length)
2174                         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2175         }
2176
2177         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
2178 }
2179
2180 FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_seektable_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_SeekTable *block, unsigned block_length)
2181 {
2182         unsigned i;
2183         FLAC__byte buffer[FLAC__STREAM_METADATA_SEEKPOINT_LENGTH];
2184
2185         FLAC__ASSERT(block_length % FLAC__STREAM_METADATA_SEEKPOINT_LENGTH == 0);
2186
2187         block->num_points = block_length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
2188
2189         if(block->num_points == 0)
2190                 block->points = 0;
2191         else if(0 == (block->points = safe_malloc_mul_2op_(block->num_points, /*times*/sizeof(FLAC__StreamMetadata_SeekPoint))))
2192                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
2193
2194         for(i = 0; i < block->num_points; i++) {
2195                 if(read_cb(buffer, 1, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH, handle) != FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)
2196                         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2197                 /* some MAGIC NUMBERs here */
2198                 block->points[i].sample_number = unpack_uint64_(buffer, 8);
2199                 block->points[i].stream_offset = unpack_uint64_(buffer+8, 8);
2200                 block->points[i].frame_samples = unpack_uint32_(buffer+16, 2);
2201         }
2202
2203         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
2204 }
2205
2206 FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_vorbis_comment_entry_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_VorbisComment_Entry *entry)
2207 {
2208         const unsigned entry_length_len = FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN / 8;
2209         FLAC__byte buffer[4]; /* magic number is asserted below */
2210
2211         FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN / 8 == sizeof(buffer));
2212
2213         if(read_cb(buffer, 1, entry_length_len, handle) != entry_length_len)
2214                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2215         entry->length = unpack_uint32_little_endian_(buffer, entry_length_len);
2216
2217         if(0 != entry->entry)
2218                 free(entry->entry);
2219
2220         if(entry->length == 0) {
2221                 entry->entry = 0;
2222         }
2223         else {
2224                 if(0 == (entry->entry = safe_malloc_add_2op_(entry->length, /*+*/1)))
2225                         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
2226
2227                 if(read_cb(entry->entry, 1, entry->length, handle) != entry->length)
2228                         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2229
2230                 entry->entry[entry->length] = '\0';
2231         }
2232
2233         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
2234 }
2235
2236 FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_vorbis_comment_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_VorbisComment *block)
2237 {
2238         unsigned i;
2239         FLAC__Metadata_SimpleIteratorStatus status;
2240         const unsigned num_comments_len = FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN / 8;
2241         FLAC__byte buffer[4]; /* magic number is asserted below */
2242
2243         FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN / 8 == sizeof(buffer));
2244
2245         if(FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK != (status = read_metadata_block_data_vorbis_comment_entry_cb_(handle, read_cb, &(block->vendor_string))))
2246                 return status;
2247
2248         if(read_cb(buffer, 1, num_comments_len, handle) != num_comments_len)
2249                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2250         block->num_comments = unpack_uint32_little_endian_(buffer, num_comments_len);
2251
2252         if(block->num_comments == 0) {
2253                 block->comments = 0;
2254         }
2255         else if(0 == (block->comments = calloc(block->num_comments, sizeof(FLAC__StreamMetadata_VorbisComment_Entry))))
2256                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
2257
2258         for(i = 0; i < block->num_comments; i++) {
2259                 if(FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK != (status = read_metadata_block_data_vorbis_comment_entry_cb_(handle, read_cb, block->comments + i)))
2260                         return status;
2261         }
2262
2263         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
2264 }
2265
2266 FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_cuesheet_track_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_CueSheet_Track *track)
2267 {
2268         unsigned i, len;
2269         FLAC__byte buffer[32]; /* asserted below that this is big enough */
2270
2271         FLAC__ASSERT(sizeof(buffer) >= sizeof(FLAC__uint64));
2272         FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN/8);
2273         FLAC__ASSERT(sizeof(buffer) >= (FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN) / 8);
2274
2275         FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN % 8 == 0);
2276         len = FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN / 8;
2277         if(read_cb(buffer, 1, len, handle) != len)
2278                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2279         track->offset = unpack_uint64_(buffer, len);
2280
2281         FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN % 8 == 0);
2282         len = FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN / 8;
2283         if(read_cb(buffer, 1, len, handle) != len)
2284                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2285         track->number = (FLAC__byte)unpack_uint32_(buffer, len);
2286
2287         FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
2288         len = FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN / 8;
2289         if(read_cb(track->isrc, 1, len, handle) != len)
2290                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2291
2292         FLAC__ASSERT((FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN) % 8 == 0);
2293         len = (FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN) / 8;
2294         if(read_cb(buffer, 1, len, handle) != len)
2295                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2296         FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN == 1);
2297         FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN == 1);
2298         track->type = buffer[0] >> 7;
2299         track->pre_emphasis = (buffer[0] >> 6) & 1;
2300
2301         FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN % 8 == 0);
2302         len = FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN / 8;
2303         if(read_cb(buffer, 1, len, handle) != len)
2304                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2305         track->num_indices = (FLAC__byte)unpack_uint32_(buffer, len);
2306
2307         if(track->num_indices == 0) {
2308                 track->indices = 0;
2309         }
2310         else if(0 == (track->indices = calloc(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index))))
2311                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
2312
2313         for(i = 0; i < track->num_indices; i++) {
2314                 FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN % 8 == 0);
2315                 len = FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN / 8;
2316                 if(read_cb(buffer, 1, len, handle) != len)
2317                         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2318                 track->indices[i].offset = unpack_uint64_(buffer, len);
2319
2320                 FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN % 8 == 0);
2321                 len = FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN / 8;
2322                 if(read_cb(buffer, 1, len, handle) != len)
2323                         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2324                 track->indices[i].number = (FLAC__byte)unpack_uint32_(buffer, len);
2325
2326                 FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN % 8 == 0);
2327                 len = FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN / 8;
2328                 if(read_cb(buffer, 1, len, handle) != len)
2329                         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2330         }
2331
2332         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
2333 }
2334
2335 FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_cuesheet_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_CueSheet *block)
2336 {
2337         unsigned i, len;
2338         FLAC__Metadata_SimpleIteratorStatus status;
2339         FLAC__byte buffer[1024]; /* MSVC needs a constant expression so we put a magic number and assert */
2340
2341         FLAC__ASSERT((FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN + FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN)/8 <= sizeof(buffer));
2342         FLAC__ASSERT(sizeof(FLAC__uint64) <= sizeof(buffer));
2343
2344         FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
2345         len = FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN / 8;
2346         if(read_cb(block->media_catalog_number, 1, len, handle) != len)
2347                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2348
2349         FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN % 8 == 0);
2350         len = FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN / 8;
2351         if(read_cb(buffer, 1, len, handle) != len)
2352                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2353         block->lead_in = unpack_uint64_(buffer, len);
2354
2355         FLAC__ASSERT((FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN + FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN) % 8 == 0);
2356         len = (FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN + FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN) / 8;
2357         if(read_cb(buffer, 1, len, handle) != len)
2358                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2359         block->is_cd = buffer[0]&0x80? true : false;
2360
2361         FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN % 8 == 0);
2362         len = FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN / 8;
2363         if(read_cb(buffer, 1, len, handle) != len)
2364                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2365         block->num_tracks = unpack_uint32_(buffer, len);
2366
2367         if(block->num_tracks == 0) {
2368                 block->tracks = 0;
2369         }
2370         else if(0 == (block->tracks = calloc(block->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track))))
2371                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
2372
2373         for(i = 0; i < block->num_tracks; i++) {
2374                 if(FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK != (status = read_metadata_block_data_cuesheet_track_cb_(handle, read_cb, block->tracks + i)))
2375                         return status;
2376         }
2377
2378         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
2379 }
2380
2381 static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_picture_cstring_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__byte **data, FLAC__uint32 *length, FLAC__uint32 length_len)
2382 {
2383         FLAC__byte buffer[sizeof(FLAC__uint32)];
2384
2385         FLAC__ASSERT(0 != data);
2386         FLAC__ASSERT(length_len%8 == 0);
2387
2388         length_len /= 8; /* convert to bytes */
2389
2390         FLAC__ASSERT(sizeof(buffer) >= length_len);
2391
2392         if(read_cb(buffer, 1, length_len, handle) != length_len)
2393                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2394         *length = unpack_uint32_(buffer, length_len);
2395
2396         if(0 != *data)
2397                 free(*data);
2398
2399         if(0 == (*data = safe_malloc_add_2op_(*length, /*+*/1)))
2400                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
2401
2402         if(*length > 0) {
2403                 if(read_cb(*data, 1, *length, handle) != *length)
2404                         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2405         }
2406
2407         (*data)[*length] = '\0';
2408
2409         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
2410 }
2411
2412 FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_picture_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_Picture *block)
2413 {
2414         FLAC__Metadata_SimpleIteratorStatus status;
2415         FLAC__byte buffer[4]; /* asserted below that this is big enough */
2416         FLAC__uint32 len;
2417
2418         FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_TYPE_LEN/8);
2419         FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN/8);
2420         FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN/8);
2421         FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN/8);
2422         FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_COLORS_LEN/8);
2423
2424         FLAC__ASSERT(FLAC__STREAM_METADATA_PICTURE_TYPE_LEN % 8 == 0);
2425         len = FLAC__STREAM_METADATA_PICTURE_TYPE_LEN / 8;
2426         if(read_cb(buffer, 1, len, handle) != len)
2427                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2428         block->type = (FLAC__StreamMetadata_Picture_Type)unpack_uint32_(buffer, len);
2429
2430         if((status = read_metadata_block_data_picture_cstring_cb_(handle, read_cb, (FLAC__byte**)(&(block->mime_type)), &len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN)) != FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK)
2431                 return status;
2432
2433         if((status = read_metadata_block_data_picture_cstring_cb_(handle, read_cb, &(block->description), &len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN)) != FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK)
2434                 return status;
2435
2436         FLAC__ASSERT(FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN % 8 == 0);
2437         len = FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN / 8;
2438         if(read_cb(buffer, 1, len, handle) != len)
2439                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2440         block->width = unpack_uint32_(buffer, len);
2441
2442         FLAC__ASSERT(FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN % 8 == 0);
2443         len = FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN / 8;
2444         if(read_cb(buffer, 1, len, handle) != len)
2445                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2446         block->height = unpack_uint32_(buffer, len);
2447
2448         FLAC__ASSERT(FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN % 8 == 0);
2449         len = FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN / 8;
2450         if(read_cb(buffer, 1, len, handle) != len)
2451                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2452         block->depth = unpack_uint32_(buffer, len);
2453
2454         FLAC__ASSERT(FLAC__STREAM_METADATA_PICTURE_COLORS_LEN % 8 == 0);
2455         len = FLAC__STREAM_METADATA_PICTURE_COLORS_LEN / 8;
2456         if(read_cb(buffer, 1, len, handle) != len)
2457                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2458         block->colors = unpack_uint32_(buffer, len);
2459
2460         /* for convenience we use read_metadata_block_data_picture_cstring_cb_() even though it adds an extra terminating NUL we don't use */
2461         if((status = read_metadata_block_data_picture_cstring_cb_(handle, read_cb, &(block->data), &(block->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN)) != FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK)
2462                 return status;
2463
2464         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
2465 }
2466
2467 FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_unknown_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__StreamMetadata_Unknown *block, unsigned block_length)
2468 {
2469         if(block_length == 0) {
2470                 block->data = 0;
2471         }
2472         else {
2473                 if(0 == (block->data = malloc(block_length)))
2474                         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
2475
2476                 if(read_cb(block->data, 1, block_length, handle) != block_length)
2477                         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2478         }
2479
2480         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
2481 }
2482
2483 FLAC__bool write_metadata_block_header_(FILE *file, FLAC__Metadata_SimpleIteratorStatus *status, const FLAC__StreamMetadata *block)
2484 {
2485         FLAC__ASSERT(0 != file);
2486         FLAC__ASSERT(0 != status);
2487
2488         if(!write_metadata_block_header_cb_((FLAC__IOHandle)file, (FLAC__IOCallback_Write)fwrite, block)) {
2489                 *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
2490                 return false;
2491         }
2492
2493         return true;
2494 }
2495
2496 FLAC__bool write_metadata_block_data_(FILE *file, FLAC__Metadata_SimpleIteratorStatus *status, const FLAC__StreamMetadata *block)
2497 {
2498         FLAC__ASSERT(0 != file);
2499         FLAC__ASSERT(0 != status);
2500
2501         if (write_metadata_block_data_cb_((FLAC__IOHandle)file, (FLAC__IOCallback_Write)fwrite, block)) {
2502                 *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
2503                 return true;
2504         }
2505         else {
2506                 *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
2507                 return false;
2508         }
2509 }
2510
2511 FLAC__bool write_metadata_block_header_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata *block)
2512 {
2513         FLAC__byte buffer[FLAC__STREAM_METADATA_HEADER_LENGTH];
2514
2515         FLAC__ASSERT(block->length < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
2516
2517         buffer[0] = (block->is_last? 0x80 : 0) | (FLAC__byte)block->type;
2518         pack_uint32_(block->length, buffer + 1, 3);
2519
2520         if(write_cb(buffer, 1, FLAC__STREAM_METADATA_HEADER_LENGTH, handle) != FLAC__STREAM_METADATA_HEADER_LENGTH)
2521                 return false;
2522
2523         return true;
2524 }
2525
2526 FLAC__bool write_metadata_block_data_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata *block)
2527 {
2528         FLAC__ASSERT(0 != block);
2529
2530         switch(block->type) {
2531                 case FLAC__METADATA_TYPE_STREAMINFO:
2532                         return write_metadata_block_data_streaminfo_cb_(handle, write_cb, &block->data.stream_info);
2533                 case FLAC__METADATA_TYPE_PADDING:
2534                         return write_metadata_block_data_padding_cb_(handle, write_cb, &block->data.padding, block->length);
2535                 case FLAC__METADATA_TYPE_APPLICATION:
2536                         return write_metadata_block_data_application_cb_(handle, write_cb, &block->data.application, block->length);
2537                 case FLAC__METADATA_TYPE_SEEKTABLE:
2538                         return write_metadata_block_data_seektable_cb_(handle, write_cb, &block->data.seek_table);
2539                 case FLAC__METADATA_TYPE_VORBIS_COMMENT:
2540                         return write_metadata_block_data_vorbis_comment_cb_(handle, write_cb, &block->data.vorbis_comment);
2541                 case FLAC__METADATA_TYPE_CUESHEET:
2542                         return write_metadata_block_data_cuesheet_cb_(handle, write_cb, &block->data.cue_sheet);
2543                 case FLAC__METADATA_TYPE_PICTURE:
2544                         return write_metadata_block_data_picture_cb_(handle, write_cb, &block->data.picture);
2545                 default:
2546                         return write_metadata_block_data_unknown_cb_(handle, write_cb, &block->data.unknown, block->length);
2547         }
2548 }
2549
2550 FLAC__bool write_metadata_block_data_streaminfo_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_StreamInfo *block)
2551 {
2552         FLAC__byte buffer[FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
2553         const unsigned channels1 = block->channels - 1;
2554         const unsigned bps1 = block->bits_per_sample - 1;
2555
2556         /* we are using hardcoded numbers for simplicity but we should
2557          * probably eventually write a bit-level packer and use the
2558          * _STREAMINFO_ constants.
2559          */
2560         pack_uint32_(block->min_blocksize, buffer, 2);
2561         pack_uint32_(block->max_blocksize, buffer+2, 2);
2562         pack_uint32_(block->min_framesize, buffer+4, 3);
2563         pack_uint32_(block->max_framesize, buffer+7, 3);
2564         buffer[10] = (block->sample_rate >> 12) & 0xff;
2565         buffer[11] = (block->sample_rate >> 4) & 0xff;
2566         buffer[12] = ((block->sample_rate & 0x0f) << 4) | (channels1 << 1) | (bps1 >> 4);
2567         buffer[13] = (FLAC__byte)(((bps1 & 0x0f) << 4) | ((block->total_samples >> 32) & 0x0f));
2568         pack_uint32_((FLAC__uint32)block->total_samples, buffer+14, 4);
2569         memcpy(buffer+18, block->md5sum, 16);
2570
2571         if(write_cb(buffer, 1, FLAC__STREAM_METADATA_STREAMINFO_LENGTH, handle) != FLAC__STREAM_METADATA_STREAMINFO_LENGTH)
2572                 return false;
2573
2574         return true;
2575 }
2576
2577 FLAC__bool write_metadata_block_data_padding_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Padding *block, unsigned block_length)
2578 {
2579         unsigned i, n = block_length;
2580         FLAC__byte buffer[1024];
2581
2582         (void)block;
2583
2584         memset(buffer, 0, 1024);
2585
2586         for(i = 0; i < n/1024; i++)
2587                 if(write_cb(buffer, 1, 1024, handle) != 1024)
2588                         return false;
2589
2590         n %= 1024;
2591
2592         if(write_cb(buffer, 1, n, handle) != n)
2593                 return false;
2594
2595         return true;
2596 }
2597
2598 FLAC__bool write_metadata_block_data_application_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Application *block, unsigned block_length)
2599 {
2600         const unsigned id_bytes = FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8;
2601
2602         if(write_cb(block->id, 1, id_bytes, handle) != id_bytes)
2603                 return false;
2604
2605         block_length -= id_bytes;
2606
2607         if(write_cb(block->data, 1, block_length, handle) != block_length)
2608                 return false;
2609
2610         return true;
2611 }
2612
2613 FLAC__bool write_metadata_block_data_seektable_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_SeekTable *block)
2614 {
2615         unsigned i;
2616         FLAC__byte buffer[FLAC__STREAM_METADATA_SEEKPOINT_LENGTH];
2617
2618         for(i = 0; i < block->num_points; i++) {
2619                 /* some MAGIC NUMBERs here */
2620                 pack_uint64_(block->points[i].sample_number, buffer, 8);
2621                 pack_uint64_(block->points[i].stream_offset, buffer+8, 8);
2622                 pack_uint32_(block->points[i].frame_samples, buffer+16, 2);
2623                 if(write_cb(buffer, 1, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH, handle) != FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)
2624                         return false;
2625         }
2626
2627         return true;
2628 }
2629
2630 FLAC__bool write_metadata_block_data_vorbis_comment_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_VorbisComment *block)
2631 {
2632         unsigned i;
2633         const unsigned entry_length_len = FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN / 8;
2634         const unsigned num_comments_len = FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN / 8;
2635         FLAC__byte buffer[4]; /* magic number is asserted below */
2636
2637         FLAC__ASSERT(max(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN, FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN) / 8 == sizeof(buffer));
2638
2639         pack_uint32_little_endian_(block->vendor_string.length, buffer, entry_length_len);
2640         if(write_cb(buffer, 1, entry_length_len, handle) != entry_length_len)
2641                 return false;
2642         if(write_cb(block->vendor_string.entry, 1, block->vendor_string.length, handle) != block->vendor_string.length)
2643                 return false;
2644
2645         pack_uint32_little_endian_(block->num_comments, buffer, num_comments_len);
2646         if(write_cb(buffer, 1, num_comments_len, handle) != num_comments_len)
2647                 return false;
2648
2649         for(i = 0; i < block->num_comments; i++) {
2650                 pack_uint32_little_endian_(block->comments[i].length, buffer, entry_length_len);
2651                 if(write_cb(buffer, 1, entry_length_len, handle) != entry_length_len)
2652                         return false;
2653                 if(write_cb(block->comments[i].entry, 1, block->comments[i].length, handle) != block->comments[i].length)
2654                         return false;
2655         }
2656
2657         return true;
2658 }
2659
2660 FLAC__bool write_metadata_block_data_cuesheet_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_CueSheet *block)
2661 {
2662         unsigned i, j, len;
2663         FLAC__byte buffer[1024]; /* asserted below that this is big enough */
2664
2665         FLAC__ASSERT(sizeof(buffer) >= sizeof(FLAC__uint64));
2666         FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN/8);
2667         FLAC__ASSERT(sizeof(buffer) >= (FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN + FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN)/8);
2668         FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN/8);
2669
2670         FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
2671         len = FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN / 8;
2672         if(write_cb(block->media_catalog_number, 1, len, handle) != len)
2673                 return false;
2674
2675         FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN % 8 == 0);
2676         len = FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN / 8;
2677         pack_uint64_(block->lead_in, buffer, len);
2678         if(write_cb(buffer, 1, len, handle) != len)
2679                 return false;
2680
2681         FLAC__ASSERT((FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN + FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN) % 8 == 0);
2682         len = (FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN + FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN) / 8;
2683         memset(buffer, 0, len);
2684         if(block->is_cd)
2685                 buffer[0] |= 0x80;
2686         if(write_cb(buffer, 1, len, handle) != len)
2687                 return false;
2688
2689         FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN % 8 == 0);
2690         len = FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN / 8;
2691         pack_uint32_(block->num_tracks, buffer, len);
2692         if(write_cb(buffer, 1, len, handle) != len)
2693                 return false;
2694
2695         for(i = 0; i < block->num_tracks; i++) {
2696                 FLAC__StreamMetadata_CueSheet_Track *track = block->tracks + i;
2697
2698                 FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN % 8 == 0);
2699                 len = FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN / 8;
2700                 pack_uint64_(track->offset, buffer, len);
2701                 if(write_cb(buffer, 1, len, handle) != len)
2702                         return false;
2703
2704                 FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN % 8 == 0);
2705                 len = FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN / 8;
2706                 pack_uint32_(track->number, buffer, len);
2707                 if(write_cb(buffer, 1, len, handle) != len)
2708                         return false;
2709
2710                 FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
2711                 len = FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN / 8;
2712                 if(write_cb(track->isrc, 1, len, handle) != len)
2713                         return false;
2714
2715                 FLAC__ASSERT((FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN) % 8 == 0);
2716                 len = (FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN + FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN) / 8;
2717                 memset(buffer, 0, len);
2718                 buffer[0] = (track->type << 7) | (track->pre_emphasis << 6);
2719                 if(write_cb(buffer, 1, len, handle) != len)
2720                         return false;
2721
2722                 FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN % 8 == 0);
2723                 len = FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN / 8;
2724                 pack_uint32_(track->num_indices, buffer, len);
2725                 if(write_cb(buffer, 1, len, handle) != len)
2726                         return false;
2727
2728                 for(j = 0; j < track->num_indices; j++) {
2729                         FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
2730
2731                         FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN % 8 == 0);
2732                         len = FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN / 8;
2733                         pack_uint64_(index->offset, buffer, len);
2734                         if(write_cb(buffer, 1, len, handle) != len)
2735                                 return false;
2736
2737                         FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN % 8 == 0);
2738                         len = FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN / 8;
2739                         pack_uint32_(index->number, buffer, len);
2740                         if(write_cb(buffer, 1, len, handle) != len)
2741                                 return false;
2742
2743                         FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN % 8 == 0);
2744                         len = FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN / 8;
2745                         memset(buffer, 0, len);
2746                         if(write_cb(buffer, 1, len, handle) != len)
2747                                 return false;
2748                 }
2749         }
2750
2751         return true;
2752 }
2753
2754 FLAC__bool write_metadata_block_data_picture_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Picture *block)
2755 {
2756         unsigned len;
2757         size_t slen;
2758         FLAC__byte buffer[4]; /* magic number is asserted below */
2759
2760         FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_TYPE_LEN%8);
2761         FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN%8);
2762         FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN%8);
2763         FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN%8);
2764         FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN%8);
2765         FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN%8);
2766         FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_COLORS_LEN%8);
2767         FLAC__ASSERT(0 == FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN%8);
2768         FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_TYPE_LEN/8);
2769         FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN/8);
2770         FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN/8);
2771         FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN/8);
2772         FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN/8);
2773         FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN/8);
2774         FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_COLORS_LEN/8);
2775         FLAC__ASSERT(sizeof(buffer) >= FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN/8);
2776
2777         len = FLAC__STREAM_METADATA_PICTURE_TYPE_LEN/8;
2778         pack_uint32_(block->type, buffer, len);
2779         if(write_cb(buffer, 1, len, handle) != len)
2780                 return false;
2781
2782         len = FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN/8;
2783         slen = strlen(block->mime_type);
2784         pack_uint32_(slen, buffer, len);
2785         if(write_cb(buffer, 1, len, handle) != len)
2786                 return false;
2787         if(write_cb(block->mime_type, 1, slen, handle) != slen)
2788                 return false;
2789
2790         len = FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN/8;
2791         slen = strlen((const char *)block->description);
2792         pack_uint32_(slen, buffer, len);
2793         if(write_cb(buffer, 1, len, handle) != len)
2794                 return false;
2795         if(write_cb(block->description, 1, slen, handle) != slen)
2796                 return false;
2797
2798         len = FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN/8;
2799         pack_uint32_(block->width, buffer, len);
2800         if(write_cb(buffer, 1, len, handle) != len)
2801                 return false;
2802
2803         len = FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN/8;
2804         pack_uint32_(block->height, buffer, len);
2805         if(write_cb(buffer, 1, len, handle) != len)
2806                 return false;
2807
2808         len = FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN/8;
2809         pack_uint32_(block->depth, buffer, len);
2810         if(write_cb(buffer, 1, len, handle) != len)
2811                 return false;
2812
2813         len = FLAC__STREAM_METADATA_PICTURE_COLORS_LEN/8;
2814         pack_uint32_(block->colors, buffer, len);
2815         if(write_cb(buffer, 1, len, handle) != len)
2816                 return false;
2817
2818         len = FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN/8;
2819         pack_uint32_(block->data_length, buffer, len);
2820         if(write_cb(buffer, 1, len, handle) != len)
2821                 return false;
2822         if(write_cb(block->data, 1, block->data_length, handle) != block->data_length)
2823                 return false;
2824
2825         return true;
2826 }
2827
2828 FLAC__bool write_metadata_block_data_unknown_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Write write_cb, const FLAC__StreamMetadata_Unknown *block, unsigned block_length)
2829 {
2830         if(write_cb(block->data, 1, block_length, handle) != block_length)
2831                 return false;
2832
2833         return true;
2834 }
2835
2836 FLAC__bool write_metadata_block_stationary_(FLAC__Metadata_SimpleIterator *iterator, const FLAC__StreamMetadata *block)
2837 {
2838         if(0 != fseeko(iterator->file, iterator->offset[iterator->depth], SEEK_SET)) {
2839                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
2840                 return false;
2841         }
2842
2843         if(!write_metadata_block_header_(iterator->file, &iterator->status, block))
2844                 return false;
2845
2846         if(!write_metadata_block_data_(iterator->file, &iterator->status, block))
2847                 return false;
2848
2849         if(0 != fseeko(iterator->file, iterator->offset[iterator->depth], SEEK_SET)) {
2850                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
2851                 return false;
2852         }
2853
2854         return read_metadata_block_header_(iterator);
2855 }
2856
2857 FLAC__bool write_metadata_block_stationary_with_padding_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, unsigned padding_length, FLAC__bool padding_is_last)
2858 {
2859         FLAC__StreamMetadata *padding;
2860
2861         if(0 != fseeko(iterator->file, iterator->offset[iterator->depth], SEEK_SET)) {
2862                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
2863                 return false;
2864         }
2865
2866         block->is_last = false;
2867
2868         if(!write_metadata_block_header_(iterator->file, &iterator->status, block))
2869                 return false;
2870
2871         if(!write_metadata_block_data_(iterator->file, &iterator->status, block))
2872                 return false;
2873
2874         if(0 == (padding = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING)))
2875                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
2876
2877         padding->is_last = padding_is_last;
2878         padding->length = padding_length;
2879
2880         if(!write_metadata_block_header_(iterator->file, &iterator->status, padding)) {
2881                 FLAC__metadata_object_delete(padding);
2882                 return false;
2883         }
2884
2885         if(!write_metadata_block_data_(iterator->file, &iterator->status, padding)) {
2886                 FLAC__metadata_object_delete(padding);
2887                 return false;
2888         }
2889
2890         FLAC__metadata_object_delete(padding);
2891
2892         if(0 != fseeko(iterator->file, iterator->offset[iterator->depth], SEEK_SET)) {
2893                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
2894                 return false;
2895         }
2896
2897         return read_metadata_block_header_(iterator);
2898 }
2899
2900 FLAC__bool rewrite_whole_file_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool append)
2901 {
2902         FILE *tempfile = NULL;
2903         char *tempfilename = NULL;
2904         int fixup_is_last_code = 0; /* 0 => no need to change any is_last flags */
2905         off_t fixup_is_last_flag_offset = -1;
2906
2907         FLAC__ASSERT(0 != block || append == false);
2908
2909         if(iterator->is_last) {
2910                 if(append) {
2911                         fixup_is_last_code = 1; /* 1 => clear the is_last flag at the following offset */
2912                         fixup_is_last_flag_offset = iterator->offset[iterator->depth];
2913                 }
2914                 else if(0 == block) {
2915                         simple_iterator_push_(iterator);
2916                         if(!FLAC__metadata_simple_iterator_prev(iterator)) {
2917                                 (void)simple_iterator_pop_(iterator);
2918                                 return false;
2919                         }
2920                         fixup_is_last_code = -1; /* -1 => set the is_last the flag at the following offset */
2921                         fixup_is_last_flag_offset = iterator->offset[iterator->depth];
2922                         if(!simple_iterator_pop_(iterator))
2923                                 return false;
2924                 }
2925         }
2926
2927         if(!simple_iterator_copy_file_prefix_(iterator, &tempfile, &tempfilename, append))
2928                 return false;
2929
2930         if(0 != block) {
2931                 if(!write_metadata_block_header_(tempfile, &iterator->status, block)) {
2932                         cleanup_tempfile_(&tempfile, &tempfilename);
2933                         return false;
2934                 }
2935
2936                 if(!write_metadata_block_data_(tempfile, &iterator->status, block)) {
2937                         cleanup_tempfile_(&tempfile, &tempfilename);
2938                         return false;
2939                 }
2940         }
2941
2942         if(!simple_iterator_copy_file_postfix_(iterator, &tempfile, &tempfilename, fixup_is_last_code, fixup_is_last_flag_offset, block==0))
2943                 return false;
2944
2945         if(append)
2946                 return FLAC__metadata_simple_iterator_next(iterator);
2947
2948         return true;
2949 }
2950
2951 void simple_iterator_push_(FLAC__Metadata_SimpleIterator *iterator)
2952 {
2953         FLAC__ASSERT(iterator->depth+1 < SIMPLE_ITERATOR_MAX_PUSH_DEPTH);
2954         iterator->offset[iterator->depth+1] = iterator->offset[iterator->depth];
2955         iterator->depth++;
2956 }
2957
2958 FLAC__bool simple_iterator_pop_(FLAC__Metadata_SimpleIterator *iterator)
2959 {
2960         FLAC__ASSERT(iterator->depth > 0);
2961         iterator->depth--;
2962         if(0 != fseeko(iterator->file, iterator->offset[iterator->depth], SEEK_SET)) {
2963                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
2964                 return false;
2965         }
2966
2967         return read_metadata_block_header_(iterator);
2968 }
2969
2970 /* return meanings:
2971  * 0: ok
2972  * 1: read error
2973  * 2: seek error
2974  * 3: not a FLAC file
2975  */
2976 unsigned seek_to_first_metadata_block_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Seek seek_cb)
2977 {
2978         FLAC__byte buffer[4];
2979         size_t n;
2980         unsigned i;
2981
2982         FLAC__ASSERT(FLAC__STREAM_SYNC_LENGTH == sizeof(buffer));
2983
2984         /* skip any id3v2 tag */
2985         errno = 0;
2986         n = read_cb(buffer, 1, 4, handle);
2987         if(errno)
2988                 return 1;
2989         else if(n != 4)
2990                 return 3;
2991         else if(0 == memcmp(buffer, "ID3", 3)) {
2992                 unsigned tag_length = 0;
2993
2994                 /* skip to the tag length */
2995                 if(seek_cb(handle, 2, SEEK_CUR) < 0)
2996                         return 2;
2997
2998                 /* read the length */
2999                 for(i = 0; i < 4; i++) {
3000                         if(read_cb(buffer, 1, 1, handle) < 1 || buffer[0] & 0x80)
3001                                 return 1;
3002                         tag_length <<= 7;
3003                         tag_length |= (buffer[0] & 0x7f);
3004                 }
3005
3006                 /* skip the rest of the tag */
3007                 if(seek_cb(handle, tag_length, SEEK_CUR) < 0)
3008                         return 2;
3009
3010                 /* read the stream sync code */
3011                 errno = 0;
3012                 n = read_cb(buffer, 1, 4, handle);
3013                 if(errno)
3014                         return 1;
3015                 else if(n != 4)
3016                         return 3;
3017         }
3018
3019         /* check for the fLaC signature */
3020         if(0 == memcmp(FLAC__STREAM_SYNC_STRING, buffer, FLAC__STREAM_SYNC_LENGTH))
3021                 return 0;
3022         else
3023                 return 3;
3024 }
3025
3026 unsigned seek_to_first_metadata_block_(FILE *f)
3027 {
3028         return seek_to_first_metadata_block_cb_((FLAC__IOHandle)f, (FLAC__IOCallback_Read)fread, fseek_wrapper_);
3029 }
3030
3031 FLAC__bool simple_iterator_copy_file_prefix_(FLAC__Metadata_SimpleIterator *iterator, FILE **tempfile, char **tempfilename, FLAC__bool append)
3032 {
3033         const off_t offset_end = append? iterator->offset[iterator->depth] + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH + (off_t)iterator->length : iterator->offset[iterator->depth];
3034
3035         if(0 != fseeko(iterator->file, 0, SEEK_SET)) {
3036                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
3037                 return false;
3038         }
3039         if(!open_tempfile_(iterator->filename, iterator->tempfile_path_prefix, tempfile, tempfilename, &iterator->status)) {
3040                 cleanup_tempfile_(tempfile, tempfilename);
3041                 return false;
3042         }
3043         if(!copy_n_bytes_from_file_(iterator->file, *tempfile, offset_end, &iterator->status)) {
3044                 cleanup_tempfile_(tempfile, tempfilename);
3045                 return false;
3046         }
3047
3048         return true;
3049 }
3050
3051 FLAC__bool simple_iterator_copy_file_postfix_(FLAC__Metadata_SimpleIterator *iterator, FILE **tempfile, char **tempfilename, int fixup_is_last_code, off_t fixup_is_last_flag_offset, FLAC__bool backup)
3052 {
3053         off_t save_offset = iterator->offset[iterator->depth];
3054         FLAC__ASSERT(0 != *tempfile);
3055
3056         if(0 != fseeko(iterator->file, save_offset + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH + (off_t)iterator->length, SEEK_SET)) {
3057                 cleanup_tempfile_(tempfile, tempfilename);
3058                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
3059                 return false;
3060         }
3061         if(!copy_remaining_bytes_from_file_(iterator->file, *tempfile, &iterator->status)) {
3062                 cleanup_tempfile_(tempfile, tempfilename);
3063                 return false;
3064         }
3065
3066         if(fixup_is_last_code != 0) {
3067                 /*
3068                  * if code == 1, it means a block was appended to the end so
3069                  *   we have to clear the is_last flag of the previous block
3070                  * if code == -1, it means the last block was deleted so
3071                  *   we have to set the is_last flag of the previous block
3072                  */
3073                 /* MAGIC NUMBERs here; we know the is_last flag is the high bit of the byte at this location */
3074                 FLAC__byte x;
3075                 if(0 != fseeko(*tempfile, fixup_is_last_flag_offset, SEEK_SET)) {
3076                         cleanup_tempfile_(tempfile, tempfilename);
3077                         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
3078                         return false;
3079                 }
3080                 if(fread(&x, 1, 1, *tempfile) != 1) {
3081                         cleanup_tempfile_(tempfile, tempfilename);
3082                         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
3083                         return false;
3084                 }
3085                 if(fixup_is_last_code > 0) {
3086                         FLAC__ASSERT(x & 0x80);
3087                         x &= 0x7f;
3088                 }
3089                 else {
3090                         FLAC__ASSERT(!(x & 0x80));
3091                         x |= 0x80;
3092                 }
3093                 if(0 != fseeko(*tempfile, fixup_is_last_flag_offset, SEEK_SET)) {
3094                         cleanup_tempfile_(tempfile, tempfilename);
3095                         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
3096                         return false;
3097                 }
3098                 if(local__fwrite(&x, 1, 1, *tempfile) != 1) {
3099                         cleanup_tempfile_(tempfile, tempfilename);
3100                         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
3101                         return false;
3102                 }
3103         }
3104
3105         (void)fclose(iterator->file);
3106
3107         if(!transport_tempfile_(iterator->filename, tempfile, tempfilename, &iterator->status))
3108                 return false;
3109
3110         if(iterator->has_stats)
3111                 set_file_stats_(iterator->filename, &iterator->stats);
3112
3113         if(!simple_iterator_prime_input_(iterator, !iterator->is_writable))
3114                 return false;
3115         if(backup) {
3116                 while(iterator->offset[iterator->depth] + (off_t)FLAC__STREAM_METADATA_HEADER_LENGTH + (off_t)iterator->length < save_offset)
3117                         if(!FLAC__metadata_simple_iterator_next(iterator))
3118                                 return false;
3119                 return true;
3120         }
3121         else {
3122                 /* move the iterator to it's original block faster by faking a push, then doing a pop_ */
3123                 FLAC__ASSERT(iterator->depth == 0);
3124                 iterator->offset[0] = save_offset;
3125                 iterator->depth++;
3126                 return simple_iterator_pop_(iterator);
3127         }
3128 }
3129
3130 FLAC__bool copy_n_bytes_from_file_(FILE *file, FILE *tempfile, off_t bytes, FLAC__Metadata_SimpleIteratorStatus *status)
3131 {
3132         FLAC__byte buffer[8192];
3133         size_t n;
3134
3135         FLAC__ASSERT(bytes >= 0);
3136         while(bytes > 0) {
3137                 n = min(sizeof(buffer), (size_t)bytes);
3138                 if(fread(buffer, 1, n, file) != n) {
3139                         *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
3140                         return false;
3141                 }
3142                 if(local__fwrite(buffer, 1, n, tempfile) != n) {
3143                         *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
3144                         return false;
3145                 }
3146                 bytes -= n;
3147         }
3148
3149         return true;
3150 }
3151
3152 FLAC__bool copy_n_bytes_from_file_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOHandle temp_handle, FLAC__IOCallback_Write temp_write_cb, off_t bytes, FLAC__Metadata_SimpleIteratorStatus *status)
3153 {
3154         FLAC__byte buffer[8192];
3155         size_t n;
3156
3157         FLAC__ASSERT(bytes >= 0);
3158         while(bytes > 0) {
3159                 n = min(sizeof(buffer), (size_t)bytes);
3160                 if(read_cb(buffer, 1, n, handle) != n) {
3161                         *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
3162                         return false;
3163                 }
3164                 if(temp_write_cb(buffer, 1, n, temp_handle) != n) {
3165                         *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
3166                         return false;
3167                 }
3168                 bytes -= n;
3169         }
3170
3171         return true;
3172 }
3173
3174 FLAC__bool copy_remaining_bytes_from_file_(FILE *file, FILE *tempfile, FLAC__Metadata_SimpleIteratorStatus *status)
3175 {
3176         FLAC__byte buffer[8192];
3177         size_t n;
3178
3179         while(!feof(file)) {
3180                 n = fread(buffer, 1, sizeof(buffer), file);
3181                 if(n == 0 && !feof(file)) {
3182                         *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
3183                         return false;
3184                 }
3185                 if(n > 0 && local__fwrite(buffer, 1, n, tempfile) != n) {
3186                         *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
3187                         return false;
3188                 }
3189         }
3190
3191         return true;
3192 }
3193
3194 FLAC__bool copy_remaining_bytes_from_file_cb_(FLAC__IOHandle handle, FLAC__IOCallback_Read read_cb, FLAC__IOCallback_Eof eof_cb, FLAC__IOHandle temp_handle, FLAC__IOCallback_Write temp_write_cb, FLAC__Metadata_SimpleIteratorStatus *status)
3195 {
3196         FLAC__byte buffer[8192];
3197         size_t n;
3198
3199         while(!eof_cb(handle)) {
3200                 n = read_cb(buffer, 1, sizeof(buffer), handle);
3201                 if(n == 0 && !eof_cb(handle)) {
3202                         *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
3203                         return false;
3204                 }
3205                 if(n > 0 && temp_write_cb(buffer, 1, n, temp_handle) != n) {
3206                         *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
3207                         return false;
3208                 }
3209         }
3210
3211         return true;
3212 }
3213
3214 FLAC__bool open_tempfile_(const char *filename, const char *tempfile_path_prefix, FILE **tempfile, char **tempfilename, FLAC__Metadata_SimpleIteratorStatus *status)
3215 {
3216         static const char *tempfile_suffix = ".metadata_edit";
3217         if(0 == tempfile_path_prefix) {
3218                 if(0 == (*tempfilename = safe_malloc_add_3op_(strlen(filename), /*+*/strlen(tempfile_suffix), /*+*/1))) {
3219                         *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
3220                         return false;
3221                 }
3222                 strcpy(*tempfilename, filename);
3223                 strcat(*tempfilename, tempfile_suffix);
3224         }
3225         else {
3226                 const char *p = strrchr(filename, '/');
3227                 if(0 == p)
3228                         p = filename;
3229                 else
3230                         p++;
3231
3232                 if(0 == (*tempfilename = safe_malloc_add_4op_(strlen(tempfile_path_prefix), /*+*/strlen(p), /*+*/strlen(tempfile_suffix), /*+*/2))) {
3233                         *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
3234                         return false;
3235                 }
3236                 strcpy(*tempfilename, tempfile_path_prefix);
3237                 strcat(*tempfilename, "/");
3238                 strcat(*tempfilename, p);
3239                 strcat(*tempfilename, tempfile_suffix);
3240         }
3241
3242         if(0 == (*tempfile = fopen(*tempfilename, "w+b"))) {
3243                 *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE;
3244                 return false;
3245         }
3246
3247         return true;
3248 }
3249
3250 FLAC__bool transport_tempfile_(const char *filename, FILE **tempfile, char **tempfilename, FLAC__Metadata_SimpleIteratorStatus *status)
3251 {
3252         FLAC__ASSERT(0 != filename);
3253         FLAC__ASSERT(0 != tempfile);
3254         FLAC__ASSERT(0 != *tempfile);
3255         FLAC__ASSERT(0 != tempfilename);
3256         FLAC__ASSERT(0 != *tempfilename);
3257         FLAC__ASSERT(0 != status);
3258
3259         (void)fclose(*tempfile);
3260         *tempfile = 0;
3261
3262 #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__ || defined __EMX__
3263         /* on some flavors of windows, rename() will fail if the destination already exists */
3264         if(unlink(filename) < 0) {
3265                 cleanup_tempfile_(tempfile, tempfilename);
3266                 *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR;
3267                 return false;
3268         }
3269 #endif
3270
3271         /*@@@ to fully support the tempfile_path_prefix we need to update this piece to actually copy across filesystems instead of just rename(): */
3272         if(0 != rename(*tempfilename, filename)) {
3273                 cleanup_tempfile_(tempfile, tempfilename);
3274                 *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR;
3275                 return false;
3276         }
3277
3278         cleanup_tempfile_(tempfile, tempfilename);
3279
3280         return true;
3281 }
3282
3283 void cleanup_tempfile_(FILE **tempfile, char **tempfilename)
3284 {
3285         if(0 != *tempfile) {
3286                 (void)fclose(*tempfile);
3287                 *tempfile = 0;
3288         }
3289
3290         if(0 != *tempfilename) {
3291                 (void)unlink(*tempfilename);
3292                 free(*tempfilename);
3293                 *tempfilename = 0;
3294         }
3295 }
3296
3297 FLAC__bool get_file_stats_(const char *filename, struct stat *stats)
3298 {
3299         FLAC__ASSERT(0 != filename);
3300         FLAC__ASSERT(0 != stats);
3301         return (0 == stat(filename, stats));
3302 }
3303
3304 void set_file_stats_(const char *filename, struct stat *stats)
3305 {
3306         struct utimbuf srctime;
3307
3308         FLAC__ASSERT(0 != filename);
3309         FLAC__ASSERT(0 != stats);
3310
3311         srctime.actime = stats->st_atime;
3312         srctime.modtime = stats->st_mtime;
3313         (void)chmod(filename, stats->st_mode);
3314         (void)utime(filename, &srctime);
3315 #if !defined _MSC_VER && !defined __BORLANDC__ && !defined __MINGW32__
3316         (void)chown(filename, stats->st_uid, -1);
3317         (void)chown(filename, -1, stats->st_gid);
3318 #endif
3319 }
3320
3321 int fseek_wrapper_(FLAC__IOHandle handle, FLAC__int64 offset, int whence)
3322 {
3323         return fseeko((FILE*)handle, (off_t)offset, whence);
3324 }
3325
3326 FLAC__int64 ftell_wrapper_(FLAC__IOHandle handle)
3327 {
3328         return ftello((FILE*)handle);
3329 }
3330
3331 FLAC__Metadata_ChainStatus get_equivalent_status_(FLAC__Metadata_SimpleIteratorStatus status)
3332 {
3333         switch(status) {
3334                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK:
3335                         return FLAC__METADATA_CHAIN_STATUS_OK;
3336                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT:
3337                         return FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT;
3338                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE:
3339                         return FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE;
3340                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE:
3341                         return FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE;
3342                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE:
3343                         return FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE;
3344                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA:
3345                         return FLAC__METADATA_CHAIN_STATUS_BAD_METADATA;
3346                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR:
3347                         return FLAC__METADATA_CHAIN_STATUS_READ_ERROR;
3348                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR:
3349                         return FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR;
3350                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR:
3351                         return FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR;
3352                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR:
3353                         return FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR;
3354                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR:
3355                         return FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR;
3356                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR:
3357                         return FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
3358                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR:
3359                 default:
3360                         return FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR;
3361         }
3362 }