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