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