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