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