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