switch malloc+memset(0) to calloc()
[flac.git] / src / libFLAC / metadata_iterators.c
1 /* libFLAC - Free Lossless Audio Codec library
2  * Copyright (C) 2001,2002  Josh Coalson
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA  02111-1307, USA.
18  */
19
20 #if !defined _MSC_VER && !defined __MINGW32__
21 /*@@@ don't know how to resolve errno without using LIBC.LIB; must use MSVCRT.LIB only for plugins */
22 #include <errno.h>
23 #endif
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27
28 #if defined _MSC_VER || defined __MINGW32__
29 #include <sys/utime.h> /* for utime() */
30 #include <io.h> /* for chmod() */
31 #else
32 #include <sys/types.h> /* some flavors of BSD (like OS X) require this to get time_t */
33 #include <utime.h> /* for utime() */
34 #include <unistd.h> /* for chown(), unlink() */
35 #endif
36 #include <sys/stat.h> /* for stat(), maybe chmod() */
37
38 #include "private/metadata.h"
39
40 #include "FLAC/assert.h"
41 #include "FLAC/file_decoder.h"
42
43 #ifdef max
44 #undef max
45 #endif
46 #define max(a,b) ((a)>(b)?(a):(b))
47 #ifdef min
48 #undef min
49 #endif
50 #define min(a,b) ((a)<(b)?(a):(b))
51
52
53 /****************************************************************************
54  *
55  * Local function declarations
56  *
57  ***************************************************************************/
58
59 static void pack_uint32_(FLAC__uint32 val, FLAC__byte *b, unsigned bytes);
60 static void pack_uint32_little_endian_(FLAC__uint32 val, FLAC__byte *b, unsigned bytes);
61 static void pack_uint64_(FLAC__uint64 val, FLAC__byte *b, unsigned bytes);
62 static FLAC__uint32 unpack_uint32_(FLAC__byte *b, unsigned bytes);
63 static FLAC__uint32 unpack_uint32_little_endian_(FLAC__byte *b, unsigned bytes);
64 static FLAC__uint64 unpack_uint64_(FLAC__byte *b, unsigned bytes);
65
66 static FLAC__bool read_metadata_block_header_(FLAC__Metadata_SimpleIterator *iterator);
67 static FLAC__bool read_metadata_block_data_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block);
68 static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_streaminfo_(FILE *file, FLAC__StreamMetadata_StreamInfo *block);
69 static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_padding_(FILE *file, FLAC__StreamMetadata_Padding *block, unsigned block_length);
70 static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_application_(FILE *file, FLAC__StreamMetadata_Application *block, unsigned block_length);
71 static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_seektable_(FILE *file, FLAC__StreamMetadata_SeekTable *block, unsigned block_length);
72 static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_vorbis_comment_entry_(FILE *file, FLAC__StreamMetadata_VorbisComment_Entry *entry);
73 static FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_vorbis_comment_(FILE *file, FLAC__StreamMetadata_VorbisComment *block);
74
75 static FLAC__bool write_metadata_block_header_(FILE *file, FLAC__Metadata_SimpleIteratorStatus *status, const FLAC__StreamMetadata *block);
76 static FLAC__bool write_metadata_block_data_(FILE *file, FLAC__Metadata_SimpleIteratorStatus *status, const FLAC__StreamMetadata *block);
77 static FLAC__Metadata_SimpleIteratorStatus write_metadata_block_data_streaminfo_(FILE *file, const FLAC__StreamMetadata_StreamInfo *block);
78 static FLAC__Metadata_SimpleIteratorStatus write_metadata_block_data_padding_(FILE *file, const FLAC__StreamMetadata_Padding *block, unsigned block_length);
79 static FLAC__Metadata_SimpleIteratorStatus write_metadata_block_data_application_(FILE *file, const FLAC__StreamMetadata_Application *block, unsigned block_length);
80 static FLAC__Metadata_SimpleIteratorStatus write_metadata_block_data_seektable_(FILE *file, const FLAC__StreamMetadata_SeekTable *block);
81 static FLAC__Metadata_SimpleIteratorStatus write_metadata_block_data_vorbis_comment_(FILE *file, const FLAC__StreamMetadata_VorbisComment *block);
82 static FLAC__bool write_metadata_block_stationary_(FLAC__Metadata_SimpleIterator *iterator, const FLAC__StreamMetadata *block);
83 static FLAC__bool write_metadata_block_stationary_with_padding_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, unsigned padding_length, FLAC__bool padding_is_last);
84 static FLAC__bool rewrite_whole_file_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool append);
85
86 static FLAC__bool chain_rewrite_chain_(FLAC__Metadata_Chain *chain);
87 static FLAC__bool chain_rewrite_file_(FLAC__Metadata_Chain *chain, const char *tempfile_path_prefix);
88
89 static void simple_iterator_push_(FLAC__Metadata_SimpleIterator *iterator);
90 static FLAC__bool simple_iterator_pop_(FLAC__Metadata_SimpleIterator *iterator);
91
92 /* return 0 if OK, 1 if read error, 2 if not a FLAC file */
93 static unsigned seek_to_first_metadata_block_(FILE *f);
94
95 static FLAC__bool simple_iterator_copy_file_prefix_(FLAC__Metadata_SimpleIterator *iterator, FILE **tempfile, char **tempfilename, FLAC__bool append);
96 static FLAC__bool simple_iterator_copy_file_postfix_(FLAC__Metadata_SimpleIterator *iterator, FILE **tempfile, char **tempfilename, int fixup_is_last_code, long fixup_is_last_flag_offset, FLAC__bool backup);
97
98 static FLAC__bool copy_n_bytes_from_file_(FILE *file, FILE *tempfile, unsigned bytes/*@@@ 4G limit*/, FLAC__Metadata_SimpleIteratorStatus *status);
99 static FLAC__bool copy_remaining_bytes_from_file_(FILE *file, FILE *tempfile, FLAC__Metadata_SimpleIteratorStatus *status);
100
101 static FLAC__bool open_tempfile_(const char *filename, const char *tempfile_path_prefix, FILE **tempfile, char **tempfilename, FLAC__Metadata_SimpleIteratorStatus *status);
102 static FLAC__bool transport_tempfile_(const char *filename, FILE **tempfile, char **tempfilename, FLAC__Metadata_SimpleIteratorStatus *status);
103 static void cleanup_tempfile_(FILE **tempfile, char **tempfilename);
104
105 static FLAC__bool get_file_stats_(const char *filename, struct stat *stats);
106 static void set_file_stats_(const char *filename, struct stat *stats);
107
108 static FLAC__Metadata_ChainStatus get_equivalent_status_(FLAC__Metadata_SimpleIteratorStatus status);
109
110
111 /****************************************************************************
112  *
113  * Level 0 implementation
114  *
115  ***************************************************************************/
116
117 static FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__FileDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
118 static void metadata_callback_(const FLAC__FileDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
119 static void error_callback_(const FLAC__FileDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
120
121 typedef struct {
122         FLAC__bool got_error;
123         FLAC__bool got_streaminfo;
124         FLAC__StreamMetadata *streaminfo;
125 } level0_client_data;
126
127 FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo)
128 {
129         level0_client_data cd;
130         FLAC__FileDecoder *decoder;
131
132         FLAC__ASSERT(0 != filename);
133         FLAC__ASSERT(0 != streaminfo);
134
135         decoder = FLAC__file_decoder_new();
136
137         if(0 == decoder)
138                 return false;
139
140         cd.got_error = false;
141         cd.got_streaminfo = false;
142         cd.streaminfo = streaminfo;
143
144         FLAC__file_decoder_set_md5_checking(decoder, false);
145         FLAC__file_decoder_set_filename(decoder, filename);
146         FLAC__file_decoder_set_metadata_ignore_all(decoder);
147         FLAC__file_decoder_set_metadata_respond(decoder, FLAC__METADATA_TYPE_STREAMINFO);
148         FLAC__file_decoder_set_write_callback(decoder, write_callback_);
149         FLAC__file_decoder_set_metadata_callback(decoder, metadata_callback_);
150         FLAC__file_decoder_set_error_callback(decoder, error_callback_);
151         FLAC__file_decoder_set_client_data(decoder, &cd);
152
153         if(FLAC__file_decoder_init(decoder) != FLAC__FILE_DECODER_OK || cd.got_error) {
154                 FLAC__file_decoder_finish(decoder);
155                 FLAC__file_decoder_delete(decoder);
156                 return false;
157         }
158
159         /* the first thing decoded must be the STREAMINFO block: */
160         if(!FLAC__file_decoder_process_until_end_of_metadata(decoder) || cd.got_error) {
161                 FLAC__file_decoder_finish(decoder);
162                 FLAC__file_decoder_delete(decoder);
163                 return false;
164         }
165
166         FLAC__file_decoder_finish(decoder);
167         FLAC__file_decoder_delete(decoder);
168
169         return !cd.got_error && cd.got_streaminfo;
170 }
171
172 FLAC__StreamDecoderWriteStatus write_callback_(const FLAC__FileDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
173 {
174         (void)decoder, (void)frame, (void)buffer, (void)client_data;
175
176         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
177 }
178
179 void metadata_callback_(const FLAC__FileDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
180 {
181         level0_client_data *cd = (level0_client_data *)client_data;
182         (void)decoder;
183
184         if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO && 0 != cd->streaminfo) {
185                 *(cd->streaminfo) = *metadata;
186                 cd->got_streaminfo = true;
187         }
188 }
189
190 void error_callback_(const FLAC__FileDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
191 {
192         level0_client_data *cd = (level0_client_data *)client_data;
193         (void)decoder;
194
195         if(status != FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC)
196                 cd->got_error = true;
197 }
198
199
200 /****************************************************************************
201  *
202  * Level 1 implementation
203  *
204  ***************************************************************************/
205
206 #define SIMPLE_ITERATOR_MAX_PUSH_DEPTH (1+4)
207 /* 1 for initial offset, +4 for our own personal use */
208
209 struct FLAC__Metadata_SimpleIterator {
210         FILE *file;
211         char *filename, *tempfile_path_prefix;
212         struct stat stats;
213         FLAC__bool has_stats;
214         FLAC__bool is_writable;
215         FLAC__Metadata_SimpleIteratorStatus status;
216         /*@@@ 2G limits here because of the offset type: */
217         long offset[SIMPLE_ITERATOR_MAX_PUSH_DEPTH];
218         long first_offset; /* this is the offset to the STREAMINFO block */
219         unsigned depth;
220         /* this is the metadata block header of the current block we are pointing to: */
221         FLAC__bool is_last;
222         FLAC__MetadataType type;
223         unsigned length;
224 };
225
226 FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[] = {
227         "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK",
228         "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT",
229         "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE",
230         "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE",
231         "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE",
232         "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA",
233         "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR",
234         "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR",
235         "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR",
236         "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR",
237         "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR",
238         "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR",
239         "FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR"
240 };
241
242
243 FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new()
244 {
245         FLAC__Metadata_SimpleIterator *iterator = calloc(1, sizeof(FLAC__Metadata_SimpleIterator));
246
247         if(0 != iterator) {
248                 iterator->file = 0;
249                 iterator->filename = 0;
250                 iterator->tempfile_path_prefix = 0;
251                 iterator->has_stats = false;
252                 iterator->is_writable = false;
253                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
254                 iterator->first_offset = iterator->offset[0] = -1;
255                 iterator->depth = 0;
256         }
257
258         return iterator;
259 }
260
261 static void simple_iterator_free_guts_(FLAC__Metadata_SimpleIterator *iterator)
262 {
263         FLAC__ASSERT(0 != iterator);
264
265         if(0 != iterator->file) {
266                 fclose(iterator->file);
267                 iterator->file = 0;
268                 if(iterator->has_stats)
269                         set_file_stats_(iterator->filename, &iterator->stats);
270         }
271         if(0 != iterator->filename) {
272                 free(iterator->filename);
273                 iterator->filename = 0;
274         }
275         if(0 != iterator->tempfile_path_prefix) {
276                 free(iterator->tempfile_path_prefix);
277                 iterator->tempfile_path_prefix = 0;
278         }
279 }
280
281 FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator)
282 {
283         FLAC__ASSERT(0 != iterator);
284
285         simple_iterator_free_guts_(iterator);
286         free(iterator);
287 }
288
289 FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator)
290 {
291         FLAC__Metadata_SimpleIteratorStatus status;
292
293         FLAC__ASSERT(0 != iterator);
294
295         status = iterator->status;
296         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
297         return status;
298 }
299
300 static FLAC__bool simple_iterator_prime_input_(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool read_only)
301 {
302         unsigned ret;
303
304         FLAC__ASSERT(0 != iterator);
305
306         if(read_only || 0 == (iterator->file = fopen(iterator->filename, "r+b"))) {
307                 iterator->is_writable = false;
308 #if !defined _MSC_VER && !defined __MINGW32__
309 /*@@@ don't know how to resolve errno without using LIBC.LIB; must use MSVCRT.LIB only for plugins */
310                 if(read_only || errno == EACCES) {
311 #endif
312                         if(0 == (iterator->file = fopen(iterator->filename, "rb"))) {
313                                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE;
314                                 return false;
315                         }
316 #if !defined _MSC_VER && !defined __MINGW32__
317                 }
318                 else {
319                         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE;
320                         return false;
321                 }
322 #endif
323         }
324         else {
325                 iterator->is_writable = true;
326         }
327
328         ret = seek_to_first_metadata_block_(iterator->file);
329         switch(ret) {
330                 case 0:
331                         iterator->depth = 0;
332                         iterator->first_offset = iterator->offset[iterator->depth] = ftell(iterator->file);
333                         return read_metadata_block_header_(iterator);
334                 case 1:
335                         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
336                         return false;
337                 case 2:
338                         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE;
339                         return false;
340                 default:
341                         FLAC__ASSERT(0);
342                         return false;
343         }
344 }
345
346 #if 0
347 @@@ If we decide to finish implementing this, put this comment back in metadata.h
348 /*
349  * The 'tempfile_path_prefix' allows you to specify a directory where
350  * tempfiles should go.  Remember that if your metadata edits cause the
351  * FLAC file to grow, the entire file will have to be rewritten.  If
352  * 'tempfile_path_prefix' is NULL, the temp file will be written in the
353  * same directory as the original FLAC file.  This makes replacing the
354  * original with the tempfile fast but requires extra space in the same
355  * partition for the tempfile.  If space is a problem, you can pass a
356  * directory name belonging to a different partition in
357  * 'tempfile_path_prefix'.  Note that you should use the forward slash
358  * '/' as the directory separator.  A trailing slash is not needed; it
359  * will be added automatically.
360  */
361 FLAC__bool FLAC__metadata_simple_iterator_init(FLAC__Metadata_SimpleIterator *iterator, const char *filename, FLAC__bool preserve_file_stats, const char *tempfile_path_prefix);
362 #endif
363
364 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)
365 {
366         const char *tempfile_path_prefix = 0; /*@@@ search for comments near 'rename(...)' for what it will take to finish implementing this */
367
368         FLAC__ASSERT(0 != iterator);
369         FLAC__ASSERT(0 != filename);
370
371         simple_iterator_free_guts_(iterator);
372
373         if(!read_only && preserve_file_stats)
374                 iterator->has_stats = get_file_stats_(filename, &iterator->stats);
375
376         if(0 == (iterator->filename = strdup(filename))) {
377                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
378                 return false;
379         }
380         if(0 != tempfile_path_prefix && 0 == (iterator->tempfile_path_prefix = strdup(tempfile_path_prefix))) {
381                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
382                 return false;
383         }
384
385         return simple_iterator_prime_input_(iterator, read_only);
386 }
387
388 FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator)
389 {
390         FLAC__ASSERT(0 != iterator);
391         FLAC__ASSERT(0 != iterator->file);
392
393         return iterator->is_writable;
394 }
395
396 FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator)
397 {
398         FLAC__ASSERT(0 != iterator);
399         FLAC__ASSERT(0 != iterator->file);
400
401         if(iterator->is_last)
402                 return false;
403
404         if(0 != fseek(iterator->file, iterator->length, SEEK_CUR)) {
405                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
406                 return false;
407         }
408
409         iterator->offset[iterator->depth] = ftell(iterator->file);
410
411         return read_metadata_block_header_(iterator);
412 }
413
414 FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator)
415 {
416         long this_offset;
417
418         FLAC__ASSERT(0 != iterator);
419         FLAC__ASSERT(0 != iterator->file);
420
421         if(iterator->offset[iterator->depth] == iterator->first_offset)
422                 return false;
423
424         if(0 != fseek(iterator->file, iterator->first_offset, SEEK_SET)) {
425                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
426                 return false;
427         }
428         this_offset = iterator->first_offset;
429         if(!read_metadata_block_header_(iterator))
430                 return false;
431
432         /* we ignore any error from ftell() and catch it in fseek() */
433         while(ftell(iterator->file) + (long)iterator->length < iterator->offset[iterator->depth]) {
434                 if(0 != fseek(iterator->file, iterator->length, SEEK_CUR)) {
435                         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
436                         return false;
437                 }
438                 this_offset = ftell(iterator->file);
439                 if(!read_metadata_block_header_(iterator))
440                         return false;
441         }
442
443         iterator->offset[iterator->depth] = this_offset;
444
445         return true;
446 }
447
448 FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator)
449 {
450         FLAC__ASSERT(0 != iterator);
451         FLAC__ASSERT(0 != iterator->file);
452
453         return iterator->type;
454 }
455
456 FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator)
457 {
458         FLAC__StreamMetadata *block = FLAC__metadata_object_new(iterator->type);
459
460         FLAC__ASSERT(0 != iterator);
461         FLAC__ASSERT(0 != iterator->file);
462
463         if(0 != block) {
464                 block->is_last = iterator->is_last;
465                 block->length = iterator->length;
466
467                 if(!read_metadata_block_data_(iterator, block)) {
468                         FLAC__metadata_object_delete(block);
469                         return 0;
470                 }
471
472                 /* back up to the beginning of the block data to stay consistent */
473                 if(0 != fseek(iterator->file, iterator->offset[iterator->depth] + FLAC__STREAM_METADATA_HEADER_LENGTH, SEEK_SET)) {
474                         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
475                         FLAC__metadata_object_delete(block);
476                         return 0;
477                 }
478         }
479         else
480                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
481
482         return block;
483 }
484
485 FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding)
486 {
487         FLAC__ASSERT_DECLARATION(long debug_target_offset = iterator->offset[iterator->depth];)
488         FLAC__bool ret;
489
490         FLAC__ASSERT(0 != iterator);
491         FLAC__ASSERT(0 != iterator->file);
492         FLAC__ASSERT(0 != block);
493
494         if(!iterator->is_writable) {
495                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE;
496                 return false;
497         }
498
499         if(iterator->type == FLAC__METADATA_TYPE_STREAMINFO || block->type == FLAC__METADATA_TYPE_STREAMINFO) {
500                 if(iterator->type != block->type) {
501                         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT;
502                         return false;
503                 }
504         }
505
506         block->is_last = iterator->is_last;
507
508         if(iterator->length == block->length)
509                 return write_metadata_block_stationary_(iterator, block);
510         else if(iterator->length > block->length) {
511                 if(use_padding && iterator->length >= FLAC__STREAM_METADATA_HEADER_LENGTH + block->length) {
512                         ret =  write_metadata_block_stationary_with_padding_(iterator, block, iterator->length - FLAC__STREAM_METADATA_HEADER_LENGTH - block->length, block->is_last);
513                         FLAC__ASSERT(iterator->offset[iterator->depth] == debug_target_offset);
514                         FLAC__ASSERT(ftell(iterator->file) == debug_target_offset + (long)FLAC__STREAM_METADATA_HEADER_LENGTH);
515                         return ret;
516                 }
517                 else {
518                         ret = rewrite_whole_file_(iterator, block, /*append=*/false);
519                         FLAC__ASSERT(iterator->offset[iterator->depth] == debug_target_offset);
520                         FLAC__ASSERT(ftell(iterator->file) == debug_target_offset + (long)FLAC__STREAM_METADATA_HEADER_LENGTH);
521                         return ret;
522                 }
523         }
524         else /* iterator->length < block->length */ {
525                 unsigned padding_leftover = 0;
526                 FLAC__bool padding_is_last = false;
527                 if(use_padding) {
528                         /* first see if we can even use padding */
529                         if(iterator->is_last) {
530                                 use_padding = false;
531                         }
532                         else {
533                                 const unsigned extra_padding_bytes_required = block->length - iterator->length;
534                                 simple_iterator_push_(iterator);
535                                 if(!FLAC__metadata_simple_iterator_next(iterator)) {
536                                         (void)simple_iterator_pop_(iterator);
537                                         return false;
538                                 }
539                                 if(iterator->type != FLAC__METADATA_TYPE_PADDING) {
540                                         use_padding = false;
541                                 }
542                                 else {
543                                         if(FLAC__STREAM_METADATA_HEADER_LENGTH + iterator->length == extra_padding_bytes_required) {
544                                                 padding_leftover = 0;
545                                                 block->is_last = iterator->is_last;
546                                         }
547                                         else if(iterator->length < extra_padding_bytes_required)
548                                                 use_padding = false;
549                                         else {
550                                                 padding_leftover = FLAC__STREAM_METADATA_HEADER_LENGTH + iterator->length - extra_padding_bytes_required;
551                                                 padding_is_last = iterator->is_last;
552                                                 block->is_last = false;
553                                         }
554                                 }
555                                 if(!simple_iterator_pop_(iterator))
556                                         return false;
557                         }
558                 }
559                 if(use_padding) {
560                         if(padding_leftover == 0) {
561                                 ret = write_metadata_block_stationary_(iterator, block);
562                                 FLAC__ASSERT(iterator->offset[iterator->depth] == debug_target_offset);
563                                 FLAC__ASSERT(ftell(iterator->file) == debug_target_offset + (long)FLAC__STREAM_METADATA_HEADER_LENGTH);
564                                 return ret;
565                         }
566                         else {
567                                 FLAC__ASSERT(padding_leftover >= FLAC__STREAM_METADATA_HEADER_LENGTH);
568                                 ret = write_metadata_block_stationary_with_padding_(iterator, block, padding_leftover - FLAC__STREAM_METADATA_HEADER_LENGTH, padding_is_last);
569                                 FLAC__ASSERT(iterator->offset[iterator->depth] == debug_target_offset);
570                                 FLAC__ASSERT(ftell(iterator->file) == debug_target_offset + (long)FLAC__STREAM_METADATA_HEADER_LENGTH);
571                                 return ret;
572                         }
573                 }
574                 else {
575                         ret = rewrite_whole_file_(iterator, block, /*append=*/false);
576                         FLAC__ASSERT(iterator->offset[iterator->depth] == debug_target_offset);
577                         FLAC__ASSERT(ftell(iterator->file) == debug_target_offset + (long)FLAC__STREAM_METADATA_HEADER_LENGTH);
578                         return ret;
579                 }
580         }
581 }
582
583 FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding)
584 {
585         unsigned padding_leftover = 0;
586         FLAC__bool padding_is_last = false;
587
588         FLAC__ASSERT_DECLARATION(long debug_target_offset = iterator->offset[iterator->depth] + FLAC__STREAM_METADATA_HEADER_LENGTH + iterator->length;)
589         FLAC__bool ret;
590
591         FLAC__ASSERT(0 != iterator);
592         FLAC__ASSERT(0 != iterator->file);
593         FLAC__ASSERT(0 != block);
594
595         if(!iterator->is_writable)
596                 return false;
597
598         if(block->type == FLAC__METADATA_TYPE_STREAMINFO) {
599                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT;
600                 return false;
601         }
602
603         block->is_last = iterator->is_last;
604
605         if(use_padding) {
606                 /* first see if we can even use padding */
607                 if(iterator->is_last) {
608                         use_padding = false;
609                 }
610                 else {
611                         simple_iterator_push_(iterator);
612                         if(!FLAC__metadata_simple_iterator_next(iterator)) {
613                                 (void)simple_iterator_pop_(iterator);
614                                 return false;
615                         }
616                         if(iterator->type != FLAC__METADATA_TYPE_PADDING) {
617                                 use_padding = false;
618                         }
619                         else {
620                                 if(iterator->length == block->length) {
621                                         padding_leftover = 0;
622                                         block->is_last = iterator->is_last;
623                                 }
624                                 else if(iterator->length < FLAC__STREAM_METADATA_HEADER_LENGTH + block->length)
625                                         use_padding = false;
626                                 else {
627                                         padding_leftover = iterator->length - block->length;
628                                         padding_is_last = iterator->is_last;
629                                         block->is_last = false;
630                                 }
631                         }
632                         if(!simple_iterator_pop_(iterator))
633                                 return false;
634                 }
635         }
636         if(use_padding) {
637                 /* move to the next block, which is suitable padding */
638                 if(!FLAC__metadata_simple_iterator_next(iterator))
639                         return false;
640                 if(padding_leftover == 0) {
641                         ret = write_metadata_block_stationary_(iterator, block);
642                         FLAC__ASSERT(iterator->offset[iterator->depth] == debug_target_offset);
643                         FLAC__ASSERT(ftell(iterator->file) == debug_target_offset + (long)FLAC__STREAM_METADATA_HEADER_LENGTH);
644                         return ret;
645                 }
646                 else {
647                         FLAC__ASSERT(padding_leftover >= FLAC__STREAM_METADATA_HEADER_LENGTH);
648                         ret = write_metadata_block_stationary_with_padding_(iterator, block, padding_leftover - FLAC__STREAM_METADATA_HEADER_LENGTH, padding_is_last);
649                         FLAC__ASSERT(iterator->offset[iterator->depth] == debug_target_offset);
650                         FLAC__ASSERT(ftell(iterator->file) == debug_target_offset + (long)FLAC__STREAM_METADATA_HEADER_LENGTH);
651                         return ret;
652                 }
653         }
654         else {
655                 ret = rewrite_whole_file_(iterator, block, /*append=*/true);
656                 FLAC__ASSERT(iterator->offset[iterator->depth] == debug_target_offset);
657                 FLAC__ASSERT(ftell(iterator->file) == debug_target_offset + (long)FLAC__STREAM_METADATA_HEADER_LENGTH);
658                 return ret;
659         }
660 }
661
662 FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding)
663 {
664         FLAC__ASSERT_DECLARATION(long debug_target_offset = iterator->offset[iterator->depth];)
665         FLAC__bool ret;
666
667         if(iterator->type == FLAC__METADATA_TYPE_STREAMINFO) {
668                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT;
669                 return false;
670         }
671
672         if(use_padding) {
673                 FLAC__StreamMetadata *padding = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING);
674                 if(0 == padding) {
675                         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
676                         return false;
677                 }
678                 padding->length = iterator->length;
679                 if(!FLAC__metadata_simple_iterator_set_block(iterator, padding, false)) {
680                         FLAC__metadata_object_delete(padding);
681                         return false;
682                 }
683                 FLAC__metadata_object_delete(padding);
684                 if(!FLAC__metadata_simple_iterator_prev(iterator))
685                         return false;
686                 FLAC__ASSERT(iterator->offset[iterator->depth] + (long)FLAC__STREAM_METADATA_HEADER_LENGTH + (long)iterator->length == debug_target_offset);
687                 FLAC__ASSERT(ftell(iterator->file) + (long)iterator->length == debug_target_offset);
688                 return true;
689         }
690         else {
691                 ret = rewrite_whole_file_(iterator, 0, /*append=*/false);
692                 FLAC__ASSERT(iterator->offset[iterator->depth] + (long)FLAC__STREAM_METADATA_HEADER_LENGTH + (long)iterator->length == debug_target_offset);
693                 FLAC__ASSERT(ftell(iterator->file) + (long)iterator->length == debug_target_offset);
694                 return ret;
695         }
696 }
697
698
699
700 /****************************************************************************
701  *
702  * Level 2 implementation
703  *
704  ***************************************************************************/
705
706
707 typedef struct FLAC__Metadata_Node {
708         FLAC__StreamMetadata *data;
709         struct FLAC__Metadata_Node *prev, *next;
710 } FLAC__Metadata_Node;
711
712 struct FLAC__Metadata_Chain {
713         char *filename;
714         FLAC__Metadata_Node *head;
715         FLAC__Metadata_Node *tail;
716         unsigned nodes;
717         FLAC__Metadata_ChainStatus status;
718         long first_offset, last_offset; /*@@@ 2G limit */
719         /*
720          * This is the length of the chain initially read from the FLAC file.
721          * it is used to compare against the current length to decide whether
722          * or not the whole file has to be rewritten.
723          */
724         unsigned initial_length; /*@@@ 4G limit */
725 };
726
727 struct FLAC__Metadata_Iterator {
728         FLAC__Metadata_Chain *chain;
729         FLAC__Metadata_Node *current;
730 };
731
732 FLAC_API const char * const FLAC__Metadata_ChainStatusString[] = {
733         "FLAC__METADATA_CHAIN_STATUS_OK",
734         "FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT",
735         "FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE",
736         "FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE",
737         "FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE",
738         "FLAC__METADATA_CHAIN_STATUS_BAD_METADATA",
739         "FLAC__METADATA_CHAIN_STATUS_READ_ERROR",
740         "FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR",
741         "FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR",
742         "FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR",
743         "FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR",
744         "FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR",
745         "FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR"
746 };
747
748
749 static FLAC__Metadata_Node *node_new_()
750 {
751         return (FLAC__Metadata_Node*)calloc(1, sizeof(FLAC__Metadata_Node));
752 }
753
754 static void node_delete_(FLAC__Metadata_Node *node)
755 {
756         FLAC__ASSERT(0 != node);
757         if(0 != node->data)
758                 FLAC__metadata_object_delete(node->data);
759         free(node);
760 }
761
762 static void chain_append_node_(FLAC__Metadata_Chain *chain, FLAC__Metadata_Node *node)
763 {
764         FLAC__ASSERT(0 != chain);
765         FLAC__ASSERT(0 != node);
766         FLAC__ASSERT(0 != node->data);
767
768         node->next = node->prev = 0;
769         node->data->is_last = true;
770         if(0 != chain->tail)
771                 chain->tail->data->is_last = false;
772
773         if(0 == chain->head)
774                 chain->head = node;
775         else {
776                 FLAC__ASSERT(0 != chain->tail);
777                 chain->tail->next = node;
778                 node->prev = chain->tail;
779         }
780         chain->tail = node;
781         chain->nodes++;
782 }
783
784 static void chain_remove_node_(FLAC__Metadata_Chain *chain, FLAC__Metadata_Node *node)
785 {
786         FLAC__ASSERT(0 != chain);
787         FLAC__ASSERT(0 != node);
788
789         if(node == chain->head)
790                 chain->head = node->next;
791         else
792                 node->prev->next = node->next;
793
794         if(node == chain->tail)
795                 chain->tail = node->prev;
796         else
797                 node->next->prev = node->prev;
798
799         if(0 != chain->tail)
800                 chain->tail->data->is_last = true;
801
802         chain->nodes--;
803 }
804
805 static void chain_delete_node_(FLAC__Metadata_Chain *chain, FLAC__Metadata_Node *node)
806 {
807         chain_remove_node_(chain, node);
808         node_delete_(node);
809 }
810
811 static unsigned chain_calculate_length_(FLAC__Metadata_Chain *chain)
812 {
813         const FLAC__Metadata_Node *node;
814         unsigned length = 0;
815         for(node = chain->head; node; node = node->next)
816                 length += (FLAC__STREAM_METADATA_HEADER_LENGTH + node->data->length);
817         return length;
818 }
819
820 static void iterator_insert_node_(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Node *node)
821 {
822         FLAC__ASSERT(0 != node);
823         FLAC__ASSERT(0 != node->data);
824         FLAC__ASSERT(0 != iterator);
825         FLAC__ASSERT(0 != iterator->current);
826         FLAC__ASSERT(0 != iterator->chain);
827         FLAC__ASSERT(0 != iterator->chain->head);
828         FLAC__ASSERT(0 != iterator->chain->tail);
829
830         node->data->is_last = false;
831
832         node->prev = iterator->current->prev;
833         node->next = iterator->current;
834
835         if(0 == node->prev)
836                 iterator->chain->head = node;
837         else
838                 node->prev->next = node;
839
840         iterator->current->prev = node;
841
842         iterator->chain->nodes++;
843 }
844
845 static void iterator_insert_node_after_(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Node *node)
846 {
847         FLAC__ASSERT(0 != node);
848         FLAC__ASSERT(0 != node->data);
849         FLAC__ASSERT(0 != iterator);
850         FLAC__ASSERT(0 != iterator->current);
851         FLAC__ASSERT(0 != iterator->chain);
852         FLAC__ASSERT(0 != iterator->chain->head);
853         FLAC__ASSERT(0 != iterator->chain->tail);
854
855         iterator->current->data->is_last = false;
856
857         node->prev = iterator->current;
858         node->next = iterator->current->next;
859
860         if(0 == node->next)
861                 iterator->chain->tail = node;
862         else
863                 node->next->prev = node;
864
865         node->prev->next = node;
866
867         iterator->chain->tail->data->is_last = true;
868
869         iterator->chain->nodes++;
870 }
871
872 /* return true iff node and node->next are both padding */
873 static FLAC__bool chain_merge_adjacent_padding_(FLAC__Metadata_Chain *chain, FLAC__Metadata_Node *node)
874 {
875         if(node->data->type == FLAC__METADATA_TYPE_PADDING && 0 != node->next && node->next->data->type == FLAC__METADATA_TYPE_PADDING) {
876                 const unsigned growth = FLAC__STREAM_METADATA_HEADER_LENGTH + node->next->data->length;
877                 node->data->length += growth;
878
879                 chain_delete_node_(chain, node->next);
880                 return true;
881         }
882         else
883                 return false;
884 }
885
886 FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new()
887 {
888         FLAC__Metadata_Chain *chain = calloc(1, sizeof(FLAC__Metadata_Chain));
889
890         if(0 != chain) {
891                 chain->filename = 0;
892                 chain->head = chain->tail = 0;
893                 chain->nodes = 0;
894                 chain->status = FLAC__METADATA_CHAIN_STATUS_OK;
895                 chain->initial_length = 0;
896         }
897
898         return chain;
899 }
900
901 FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain)
902 {
903         FLAC__Metadata_Node *node, *next;
904
905         FLAC__ASSERT(0 != chain);
906
907         for(node = chain->head; node; ) {
908                 next = node->next;
909                 node_delete_(node);
910                 node = next;
911         }
912
913         if(0 != chain->filename)
914                 free(chain->filename);
915
916         free(chain);
917 }
918
919 FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain)
920 {
921         FLAC__Metadata_ChainStatus status;
922
923         FLAC__ASSERT(0 != chain);
924
925         status = chain->status;
926         chain->status = FLAC__METADATA_CHAIN_STATUS_OK;
927         return status;
928 }
929
930 FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename)
931 {
932         FLAC__Metadata_SimpleIterator *iterator;
933         FLAC__Metadata_Node *node;
934
935         FLAC__ASSERT(0 != chain);
936         FLAC__ASSERT(0 != filename);
937
938         if(0 == (chain->filename = strdup(filename))) {
939                 chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
940                 return false;
941         }
942
943         if(0 == (iterator = FLAC__metadata_simple_iterator_new())) {
944                 chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
945                 return false;
946         }
947
948         if(!FLAC__metadata_simple_iterator_init(iterator, filename, /*read_only=*/true, /*preserve_file_stats=*/false)) {
949                 chain->status = get_equivalent_status_(iterator->status);
950                 return false;
951         }
952
953         chain->first_offset = iterator->offset[iterator->depth];
954
955         do {
956                 node = node_new_();
957                 if(0 == node) {
958                         chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
959                         return false;
960                 }
961                 node->data = FLAC__metadata_simple_iterator_get_block(iterator);
962                 if(0 == node->data) {
963                         node_delete_(node);
964                         chain->status = get_equivalent_status_(iterator->status);
965                         return false;
966                 }
967                 chain_append_node_(chain, node);
968         } while(FLAC__metadata_simple_iterator_next(iterator));
969
970         if(!iterator->is_last || iterator->status != FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK) {
971                 chain->status = get_equivalent_status_(iterator->status);
972                 return false;
973         }
974
975         chain->last_offset = ftell(iterator->file) + iterator->length;
976         FLAC__metadata_simple_iterator_delete(iterator);
977
978         chain->initial_length = chain_calculate_length_(chain);
979         return true;
980 }
981
982 FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats)
983 {
984         struct stat stats;
985         const char *tempfile_path_prefix = 0;
986         unsigned current_length;
987
988         FLAC__ASSERT(0 != chain);
989
990         current_length = chain_calculate_length_(chain);
991
992         if(use_padding) {
993                 if(current_length < chain->initial_length && chain->tail->data->type == FLAC__METADATA_TYPE_PADDING) {
994                         const unsigned delta = chain->initial_length - current_length;
995                         chain->tail->data->length += delta;
996                         current_length += delta;
997                         FLAC__ASSERT(current_length == chain->initial_length);
998                 }
999                 else if(current_length + FLAC__STREAM_METADATA_HEADER_LENGTH <= chain->initial_length) {
1000                         FLAC__StreamMetadata *padding;
1001                         FLAC__Metadata_Node *node;
1002                         if(0 == (padding = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING))) {
1003                                 chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
1004                                 return false;
1005                         }
1006                         padding->length = chain->initial_length - (FLAC__STREAM_METADATA_HEADER_LENGTH + current_length);
1007                         if(0 == (node = node_new_())) {
1008                                 FLAC__metadata_object_delete(padding);
1009                                 chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
1010                                 return false;
1011                         }
1012                         node->data = padding;
1013                         chain_append_node_(chain, node);
1014                         current_length = chain_calculate_length_(chain);
1015                         FLAC__ASSERT(current_length == chain->initial_length);
1016                 }
1017                 else if(current_length > chain->initial_length) {
1018                         const unsigned delta = current_length - chain->initial_length;
1019                         if(chain->tail->data->type == FLAC__METADATA_TYPE_PADDING) {
1020                                 if(chain->tail->data->length + FLAC__STREAM_METADATA_HEADER_LENGTH == delta) {
1021                                         chain_delete_node_(chain, chain->tail);
1022                                         current_length = chain_calculate_length_(chain);
1023                                         FLAC__ASSERT(current_length == chain->initial_length);
1024                                 }
1025                                 else if(chain->tail->data->length >= delta) {
1026                                         chain->tail->data->length -= delta;
1027                                         current_length -= delta;
1028                                         FLAC__ASSERT(current_length == chain->initial_length);
1029                                 }
1030                         }
1031                 }
1032         }
1033
1034         if(preserve_file_stats)
1035                 get_file_stats_(chain->filename, &stats);
1036
1037         if(current_length == chain->initial_length) {
1038                 if(!chain_rewrite_chain_(chain))
1039                         return false;
1040         }
1041         else {
1042                 if(!chain_rewrite_file_(chain, tempfile_path_prefix))
1043                         return false;
1044         }
1045
1046         if(preserve_file_stats)
1047                 set_file_stats_(chain->filename, &stats);
1048
1049         /* recompute lengths and offsets if necessary */
1050         if(chain->initial_length != current_length) {
1051                 const FLAC__Metadata_Node *node;
1052                 chain->initial_length = current_length;
1053                 chain->last_offset = chain->first_offset;
1054                 for(node = chain->head; node; node = node->next)
1055                         chain->last_offset += (FLAC__STREAM_METADATA_HEADER_LENGTH + node->data->length);
1056         }
1057
1058         return true;
1059 }
1060
1061 FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain)
1062 {
1063         FLAC__Metadata_Node *node;
1064
1065         FLAC__ASSERT(0 != chain);
1066
1067         for(node = chain->head; node; ) {
1068                 if(!chain_merge_adjacent_padding_(chain, node))
1069                         node = node->next;
1070         }
1071 }
1072
1073 FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain)
1074 {
1075         FLAC__Metadata_Node *node, *save;
1076         unsigned i;
1077
1078         FLAC__ASSERT(0 != chain);
1079
1080         /*
1081          * Don't try and be too smart... this simple algo is good enough for
1082          * the small number of nodes that we deal with.
1083          */
1084         for(i = 0, node = chain->head; i < chain->nodes; i++) {
1085                 if(node->data->type == FLAC__METADATA_TYPE_PADDING) {
1086                         save = node->next;
1087                         chain_remove_node_(chain, node);
1088                         chain_append_node_(chain, node);
1089                         node = save;
1090                 }
1091                 else {
1092                         node = node->next;
1093                 }
1094         }
1095
1096         FLAC__metadata_chain_merge_padding(chain);
1097 }
1098
1099
1100 FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new()
1101 {
1102         FLAC__Metadata_Iterator *iterator = calloc(1, sizeof(FLAC__Metadata_Iterator));
1103
1104         /* calloc() implies:
1105                 iterator->current = 0;
1106                 iterator->chain = 0;
1107         */
1108
1109         return iterator;
1110 }
1111
1112 FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator)
1113 {
1114         FLAC__ASSERT(0 != iterator);
1115
1116         free(iterator);
1117 }
1118
1119 FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain)
1120 {
1121         FLAC__ASSERT(0 != iterator);
1122         FLAC__ASSERT(0 != chain);
1123         FLAC__ASSERT(0 != chain->head);
1124
1125         iterator->chain = chain;
1126         iterator->current = chain->head;
1127 }
1128
1129 FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator)
1130 {
1131         FLAC__ASSERT(0 != iterator);
1132
1133         if(0 == iterator->current || 0 == iterator->current->next)
1134                 return false;
1135
1136         iterator->current = iterator->current->next;
1137         return true;
1138 }
1139
1140 FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator)
1141 {
1142         FLAC__ASSERT(0 != iterator);
1143
1144         if(0 == iterator->current || 0 == iterator->current->prev)
1145                 return false;
1146
1147         iterator->current = iterator->current->prev;
1148         return true;
1149 }
1150
1151 FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator)
1152 {
1153         FLAC__ASSERT(0 != iterator);
1154         FLAC__ASSERT(0 != iterator->current);
1155         FLAC__ASSERT(0 != iterator->current->data);
1156
1157         return iterator->current->data->type;
1158 }
1159
1160 FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator)
1161 {
1162         FLAC__ASSERT(0 != iterator);
1163         FLAC__ASSERT(0 != iterator->current);
1164
1165         return iterator->current->data;
1166 }
1167
1168 FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block)
1169 {
1170         FLAC__ASSERT(0 != iterator);
1171         FLAC__ASSERT(0 != block);
1172         return FLAC__metadata_iterator_delete_block(iterator, false) && FLAC__metadata_iterator_insert_block_after(iterator, block);
1173 }
1174
1175 FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding)
1176 {
1177         FLAC__Metadata_Node *save;
1178
1179         FLAC__ASSERT(0 != iterator);
1180         FLAC__ASSERT(0 != iterator->current);
1181
1182         if(0 == iterator->current->prev) {
1183                 FLAC__ASSERT(iterator->current->data->type == FLAC__METADATA_TYPE_STREAMINFO);
1184                 return false;
1185         }
1186
1187         save = iterator->current->prev;
1188
1189         if(replace_with_padding) {
1190                 FLAC__metadata_object_delete_data(iterator->current->data);
1191                 iterator->current->data->type = FLAC__METADATA_TYPE_PADDING;
1192         }
1193         else {
1194                 chain_delete_node_(iterator->chain, iterator->current);
1195         }
1196
1197         iterator->current = save;
1198         return true;
1199 }
1200
1201 FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block)
1202 {
1203         FLAC__Metadata_Node *node;
1204
1205         FLAC__ASSERT(0 != iterator);
1206         FLAC__ASSERT(0 != iterator->current);
1207         FLAC__ASSERT(0 != block);
1208
1209         if(block->type == FLAC__METADATA_TYPE_STREAMINFO)
1210                 return false;
1211
1212         if(0 == iterator->current->prev) {
1213                 FLAC__ASSERT(iterator->current->data->type == FLAC__METADATA_TYPE_STREAMINFO);
1214                 return false;
1215         }
1216
1217         if(0 == (node = node_new_()))
1218                 return false;
1219
1220         node->data = block;
1221         iterator_insert_node_(iterator, node);
1222         iterator->current = node;
1223         return true;
1224 }
1225
1226 FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block)
1227 {
1228         FLAC__Metadata_Node *node;
1229
1230         FLAC__ASSERT(0 != iterator);
1231         FLAC__ASSERT(0 != iterator->current);
1232         FLAC__ASSERT(0 != block);
1233
1234         if(block->type == FLAC__METADATA_TYPE_STREAMINFO)
1235                 return false;
1236
1237         if(0 == (node = node_new_()))
1238                 return false;
1239
1240         node->data = block;
1241         iterator_insert_node_after_(iterator, node);
1242         iterator->current = node;
1243         return true;
1244 }
1245
1246
1247 /****************************************************************************
1248  *
1249  * Local function definitions
1250  *
1251  ***************************************************************************/
1252
1253 void pack_uint32_(FLAC__uint32 val, FLAC__byte *b, unsigned bytes)
1254 {
1255         unsigned i;
1256
1257         b += bytes;
1258
1259         for(i = 0; i < bytes; i++) {
1260                 *(--b) = (FLAC__byte)(val & 0xff);
1261                 val >>= 8;
1262         }
1263 }
1264
1265 void pack_uint32_little_endian_(FLAC__uint32 val, FLAC__byte *b, unsigned bytes)
1266 {
1267         unsigned i;
1268
1269         for(i = 0; i < bytes; i++) {
1270                 *(b++) = (FLAC__byte)(val & 0xff);
1271                 val >>= 8;
1272         }
1273 }
1274
1275 void pack_uint64_(FLAC__uint64 val, FLAC__byte *b, unsigned bytes)
1276 {
1277         unsigned i;
1278
1279         b += bytes;
1280
1281         for(i = 0; i < bytes; i++) {
1282                 *(--b) = (FLAC__byte)(val & 0xff);
1283                 val >>= 8;
1284         }
1285 }
1286
1287 FLAC__uint32 unpack_uint32_(FLAC__byte *b, unsigned bytes)
1288 {
1289         FLAC__uint32 ret = 0;
1290         unsigned i;
1291
1292         for(i = 0; i < bytes; i++)
1293                 ret = (ret << 8) | (FLAC__uint32)(*b++);
1294
1295         return ret;
1296 }
1297
1298 FLAC__uint32 unpack_uint32_little_endian_(FLAC__byte *b, unsigned bytes)
1299 {
1300         FLAC__uint32 ret = 0;
1301         unsigned i;
1302
1303         b += bytes;
1304
1305         for(i = 0; i < bytes; i++)
1306                 ret = (ret << 8) | (FLAC__uint32)(*--b);
1307
1308         return ret;
1309 }
1310
1311 FLAC__uint64 unpack_uint64_(FLAC__byte *b, unsigned bytes)
1312 {
1313         FLAC__uint64 ret = 0;
1314         unsigned i;
1315
1316         for(i = 0; i < bytes; i++)
1317                 ret = (ret << 8) | (FLAC__uint64)(*b++);
1318
1319         return ret;
1320 }
1321
1322 FLAC__bool read_metadata_block_header_(FLAC__Metadata_SimpleIterator *iterator)
1323 {
1324         FLAC__byte raw_header[FLAC__STREAM_METADATA_HEADER_LENGTH];
1325
1326         FLAC__ASSERT(0 != iterator);
1327         FLAC__ASSERT(0 != iterator->file);
1328
1329         if(fread(raw_header, 1, FLAC__STREAM_METADATA_HEADER_LENGTH, iterator->file) != FLAC__STREAM_METADATA_HEADER_LENGTH) {
1330                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
1331                 return false;
1332         }
1333
1334         iterator->is_last = raw_header[0] & 0x80? true : false;
1335         iterator->type = (FLAC__MetadataType)(raw_header[0] & 0x7f);
1336         iterator->length = unpack_uint32_(raw_header + 1, 3);
1337
1338         /* do some checking */
1339         if(iterator->type > FLAC__METADATA_TYPE_VORBIS_COMMENT) {
1340                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA;
1341                 return false;
1342         }
1343
1344         return true;
1345 }
1346
1347 FLAC__bool read_metadata_block_data_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block)
1348 {
1349         FLAC__ASSERT(0 != iterator);
1350         FLAC__ASSERT(0 != iterator->file);
1351
1352         switch(block->type) {
1353                 case FLAC__METADATA_TYPE_STREAMINFO:
1354                         iterator->status = read_metadata_block_data_streaminfo_(iterator->file, &block->data.stream_info);
1355                         break;
1356                 case FLAC__METADATA_TYPE_PADDING:
1357                         iterator->status = read_metadata_block_data_padding_(iterator->file, &block->data.padding, block->length);
1358                         break;
1359                 case FLAC__METADATA_TYPE_APPLICATION:
1360                         iterator->status = read_metadata_block_data_application_(iterator->file, &block->data.application, block->length);
1361                         break;
1362                 case FLAC__METADATA_TYPE_SEEKTABLE:
1363                         iterator->status = read_metadata_block_data_seektable_(iterator->file, &block->data.seek_table, block->length);
1364                         break;
1365                 case FLAC__METADATA_TYPE_VORBIS_COMMENT:
1366                         iterator->status = read_metadata_block_data_vorbis_comment_(iterator->file, &block->data.vorbis_comment);
1367                         break;
1368                 default:
1369                         FLAC__ASSERT(0);
1370                         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR;
1371         }
1372
1373         return (iterator->status == FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK);
1374 }
1375
1376 FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_streaminfo_(FILE *file, FLAC__StreamMetadata_StreamInfo *block)
1377 {
1378         FLAC__byte buffer[FLAC__STREAM_METADATA_STREAMINFO_LENGTH], *b;
1379
1380         FLAC__ASSERT(0 != file);
1381
1382         if(fread(buffer, 1, FLAC__STREAM_METADATA_STREAMINFO_LENGTH, file) != FLAC__STREAM_METADATA_STREAMINFO_LENGTH)
1383                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
1384
1385         b = buffer;
1386
1387         /* @@@ we are using hardcoded numbers for simplicity but we should
1388          * probably eventually write a bit-level unpacker and use the
1389          * _STREAMINFO_ constants.
1390          */
1391         block->min_blocksize = unpack_uint32_(b, 2); b += 2;
1392         block->max_blocksize = unpack_uint32_(b, 2); b += 2;
1393         block->min_framesize = unpack_uint32_(b, 3); b += 3;
1394         block->max_framesize = unpack_uint32_(b, 3); b += 3;
1395         block->sample_rate = (unpack_uint32_(b, 2) << 4) | ((unsigned)(b[2] & 0xf0) >> 4);
1396         block->channels = (unsigned)((b[2] & 0x0e) >> 1) + 1;
1397         block->bits_per_sample = ((((unsigned)(b[2] & 0x01)) << 4) | (((unsigned)(b[3] & 0xf0)) >> 4)) + 1;
1398         block->total_samples = (((FLAC__uint64)(b[3] & 0x0f)) << 32) | unpack_uint64_(b+4, 4);
1399         memcpy(block->md5sum, b+8, 16);
1400
1401         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
1402 }
1403
1404
1405 FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_padding_(FILE *file, FLAC__StreamMetadata_Padding *block, unsigned block_length)
1406 {
1407         FLAC__ASSERT(0 != file);
1408
1409         (void)block; /* nothing to do; we don't care about reading the padding bytes */
1410
1411         if(0 != fseek(file, block_length, SEEK_CUR))
1412                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
1413
1414         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
1415 }
1416
1417 FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_application_(FILE *file, FLAC__StreamMetadata_Application *block, unsigned block_length)
1418 {
1419         const unsigned id_bytes = FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8;
1420
1421         FLAC__ASSERT(0 != file);
1422
1423         if(fread(block->id, 1, id_bytes, file) != id_bytes)
1424                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
1425
1426         block_length -= id_bytes;
1427
1428         if(block_length == 0) {
1429                 block->data = 0;
1430         }
1431         else {
1432                 if(0 == (block->data = malloc(block_length)))
1433                         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
1434
1435                 if(fread(block->data, 1, block_length, file) != block_length)
1436                         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
1437         }
1438
1439         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
1440 }
1441
1442 FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_seektable_(FILE *file, FLAC__StreamMetadata_SeekTable *block, unsigned block_length)
1443 {
1444         unsigned i;
1445         FLAC__byte buffer[FLAC__STREAM_METADATA_SEEKPOINT_LENGTH];
1446
1447         FLAC__ASSERT(0 != file);
1448         FLAC__ASSERT(block_length % FLAC__STREAM_METADATA_SEEKPOINT_LENGTH == 0);
1449
1450         block->num_points = block_length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
1451
1452         if(block->num_points == 0)
1453                 block->points = 0;
1454         else if(0 == (block->points = malloc(block->num_points * sizeof(FLAC__StreamMetadata_SeekPoint))))
1455                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
1456
1457         for(i = 0; i < block->num_points; i++) {
1458                 if(fread(buffer, 1, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH, file) != FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)
1459                         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
1460                 /*@@@ some MAGIC NUMBERs here */
1461                 block->points[i].sample_number = unpack_uint64_(buffer, 8);
1462                 block->points[i].stream_offset = unpack_uint64_(buffer+8, 8);
1463                 block->points[i].frame_samples = unpack_uint32_(buffer+16, 2);
1464         }
1465
1466         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
1467 }
1468
1469 FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_vorbis_comment_entry_(FILE *file, FLAC__StreamMetadata_VorbisComment_Entry *entry)
1470 {
1471         const unsigned entry_length_len = FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN / 8;
1472         FLAC__byte buffer[4]; /* magic number is asserted below */
1473
1474         FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN / 8 == 4);
1475         FLAC__ASSERT(0 != file);
1476
1477         if(fread(buffer, 1, entry_length_len, file) != entry_length_len)
1478                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
1479         entry->length = unpack_uint32_little_endian_(buffer, entry_length_len);
1480
1481         if(entry->length == 0) {
1482                 entry->entry = 0;
1483         }
1484         else {
1485                 if(0 == (entry->entry = malloc(entry->length)))
1486                         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
1487
1488                 if(fread(entry->entry, 1, entry->length, file) != entry->length)
1489                         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
1490         }
1491
1492         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
1493 }
1494
1495 FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_vorbis_comment_(FILE *file, FLAC__StreamMetadata_VorbisComment *block)
1496 {
1497         unsigned i;
1498         FLAC__Metadata_SimpleIteratorStatus status;
1499         const unsigned num_comments_len = FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN / 8;
1500         FLAC__byte buffer[4]; /* magic number is asserted below */
1501
1502         FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN / 8 == 4);
1503         FLAC__ASSERT(0 != file);
1504
1505         if(FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK != (status = read_metadata_block_data_vorbis_comment_entry_(file, &(block->vendor_string))))
1506                 return status;
1507
1508         if(fread(buffer, 1, num_comments_len, file) != num_comments_len)
1509                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
1510         block->num_comments = unpack_uint32_little_endian_(buffer, num_comments_len);
1511
1512         if(block->num_comments == 0) {
1513                 block->comments = 0;
1514         }
1515         else if(0 == (block->comments = malloc(block->num_comments * sizeof(FLAC__StreamMetadata_VorbisComment_Entry))))
1516                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
1517
1518         for(i = 0; i < block->num_comments; i++) {
1519                 if(FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK != (status = read_metadata_block_data_vorbis_comment_entry_(file, block->comments + i)))
1520                         return status;
1521         }
1522
1523         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
1524 }
1525
1526 FLAC__bool write_metadata_block_header_(FILE *file, FLAC__Metadata_SimpleIteratorStatus *status, const FLAC__StreamMetadata *block)
1527 {
1528         FLAC__byte buffer[FLAC__STREAM_METADATA_HEADER_LENGTH];
1529
1530         FLAC__ASSERT(0 != file);
1531         FLAC__ASSERT(0 != status);
1532         FLAC__ASSERT(block->length < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
1533
1534         buffer[0] = (block->is_last? 0x80 : 0) | (FLAC__byte)block->type;
1535         pack_uint32_(block->length, buffer + 1, 3);
1536
1537         if(fwrite(buffer, 1, FLAC__STREAM_METADATA_HEADER_LENGTH, file) != FLAC__STREAM_METADATA_HEADER_LENGTH) {
1538                 *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
1539                 return false;
1540         }
1541
1542         return true;
1543 }
1544
1545 FLAC__bool write_metadata_block_data_(FILE *file, FLAC__Metadata_SimpleIteratorStatus *status, const FLAC__StreamMetadata *block)
1546 {
1547         FLAC__ASSERT(0 != file);
1548         FLAC__ASSERT(0 != status);
1549
1550         switch(block->type) {
1551                 case FLAC__METADATA_TYPE_STREAMINFO:
1552                         *status = write_metadata_block_data_streaminfo_(file, &block->data.stream_info);
1553                         break;
1554                 case FLAC__METADATA_TYPE_PADDING:
1555                         *status = write_metadata_block_data_padding_(file, &block->data.padding, block->length);
1556                         break;
1557                 case FLAC__METADATA_TYPE_APPLICATION:
1558                         *status = write_metadata_block_data_application_(file, &block->data.application, block->length);
1559                         break;
1560                 case FLAC__METADATA_TYPE_SEEKTABLE:
1561                         *status = write_metadata_block_data_seektable_(file, &block->data.seek_table);
1562                         break;
1563                 case FLAC__METADATA_TYPE_VORBIS_COMMENT:
1564                         *status = write_metadata_block_data_vorbis_comment_(file, &block->data.vorbis_comment);
1565                         break;
1566                 default:
1567                         FLAC__ASSERT(0);
1568                         *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR;
1569         }
1570         return (*status == FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK);
1571 }
1572
1573 FLAC__Metadata_SimpleIteratorStatus write_metadata_block_data_streaminfo_(FILE *file, const FLAC__StreamMetadata_StreamInfo *block)
1574 {
1575         FLAC__byte buffer[FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
1576         const unsigned channels1 = block->channels - 1;
1577         const unsigned bps1 = block->bits_per_sample - 1;
1578
1579         FLAC__ASSERT(0 != file);
1580
1581         /* @@@ we are using hardcoded numbers for simplicity but we should
1582          * probably eventually write a bit-level packer and use the
1583          * _STREAMINFO_ constants.
1584          */
1585         pack_uint32_(block->min_blocksize, buffer, 2);
1586         pack_uint32_(block->max_blocksize, buffer+2, 2);
1587         pack_uint32_(block->min_framesize, buffer+4, 3);
1588         pack_uint32_(block->max_framesize, buffer+7, 3);
1589         buffer[10] = (block->sample_rate >> 12) & 0xff;
1590         buffer[11] = (block->sample_rate >> 4) & 0xff;
1591         buffer[12] = ((block->sample_rate & 0x0f) << 4) | (channels1 << 1) | (bps1 >> 4);
1592         buffer[13] = (FLAC__byte)(((bps1 & 0x0f) << 4) | ((block->total_samples >> 32) & 0x0f));
1593         pack_uint32_((FLAC__uint32)block->total_samples, buffer+14, 4);
1594         memcpy(buffer+18, block->md5sum, 16);
1595
1596         if(fwrite(buffer, 1, FLAC__STREAM_METADATA_STREAMINFO_LENGTH, file) != FLAC__STREAM_METADATA_STREAMINFO_LENGTH)
1597                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
1598
1599         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
1600 }
1601
1602 FLAC__Metadata_SimpleIteratorStatus write_metadata_block_data_padding_(FILE *file, const FLAC__StreamMetadata_Padding *block, unsigned block_length)
1603 {
1604         unsigned i, n = block_length;
1605         FLAC__byte buffer[1024];
1606
1607         FLAC__ASSERT(0 != file);
1608
1609         (void)block;
1610
1611         memset(buffer, 0, 1024);
1612
1613         for(i = 0; i < n/1024; i++)
1614                 if(fwrite(buffer, 1, 1024, file) != 1024)
1615                         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
1616
1617         n %= 1024;
1618
1619         if(fwrite(buffer, 1, n, file) != n)
1620                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
1621
1622         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
1623 }
1624
1625 FLAC__Metadata_SimpleIteratorStatus write_metadata_block_data_application_(FILE *file, const FLAC__StreamMetadata_Application *block, unsigned block_length)
1626 {
1627         const unsigned id_bytes = FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8;
1628
1629         FLAC__ASSERT(0 != file);
1630
1631         if(fwrite(block->id, 1, id_bytes, file) != id_bytes)
1632                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
1633
1634         block_length -= id_bytes;
1635
1636         if(fwrite(block->data, 1, block_length, file) != block_length)
1637                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
1638
1639         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
1640 }
1641
1642 FLAC__Metadata_SimpleIteratorStatus write_metadata_block_data_seektable_(FILE *file, const FLAC__StreamMetadata_SeekTable *block)
1643 {
1644         unsigned i;
1645         FLAC__byte buffer[FLAC__STREAM_METADATA_SEEKPOINT_LENGTH];
1646
1647         FLAC__ASSERT(0 != file);
1648
1649         for(i = 0; i < block->num_points; i++) {
1650                 /*@@@ some MAGIC NUMBERs here */
1651                 pack_uint64_(block->points[i].sample_number, buffer, 8);
1652                 pack_uint64_(block->points[i].stream_offset, buffer+8, 8);
1653                 pack_uint32_(block->points[i].frame_samples, buffer+16, 2);
1654                 if(fwrite(buffer, 1, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH, file) != FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)
1655                         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
1656         }
1657
1658         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
1659 }
1660
1661 FLAC__Metadata_SimpleIteratorStatus write_metadata_block_data_vorbis_comment_(FILE *file, const FLAC__StreamMetadata_VorbisComment *block)
1662 {
1663         unsigned i;
1664         const unsigned entry_length_len = FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN / 8;
1665         const unsigned num_comments_len = FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN / 8;
1666         FLAC__byte buffer[4]; /* magic number is asserted below */
1667
1668         FLAC__ASSERT(max(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN, FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN) / 8 == 4);
1669         FLAC__ASSERT(0 != file);
1670
1671         pack_uint32_little_endian_(block->vendor_string.length, buffer, entry_length_len);
1672         if(fwrite(buffer, 1, entry_length_len, file) != entry_length_len)
1673                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
1674         if(fwrite(block->vendor_string.entry, 1, block->vendor_string.length, file) != block->vendor_string.length)
1675                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
1676
1677         pack_uint32_little_endian_(block->num_comments, buffer, num_comments_len);
1678         if(fwrite(buffer, 1, num_comments_len, file) != num_comments_len)
1679                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
1680
1681         for(i = 0; i < block->num_comments; i++) {
1682                 pack_uint32_little_endian_(block->comments[i].length, buffer, entry_length_len);
1683                 if(fwrite(buffer, 1, entry_length_len, file) != entry_length_len)
1684                         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
1685                 if(fwrite(block->comments[i].entry, 1, block->comments[i].length, file) != block->comments[i].length)
1686                         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
1687         }
1688
1689         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
1690 }
1691
1692 FLAC__bool write_metadata_block_stationary_(FLAC__Metadata_SimpleIterator *iterator, const FLAC__StreamMetadata *block)
1693 {
1694         if(0 != fseek(iterator->file, iterator->offset[iterator->depth], SEEK_SET)) {
1695                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
1696                 return false;
1697         }
1698
1699         if(!write_metadata_block_header_(iterator->file, &iterator->status, block))
1700                 return false;
1701
1702         if(!write_metadata_block_data_(iterator->file, &iterator->status, block))
1703                 return false;
1704
1705         if(0 != fseek(iterator->file, iterator->offset[iterator->depth], SEEK_SET)) {
1706                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
1707                 return false;
1708         }
1709
1710         return read_metadata_block_header_(iterator);
1711 }
1712
1713 FLAC__bool write_metadata_block_stationary_with_padding_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, unsigned padding_length, FLAC__bool padding_is_last)
1714 {
1715         FLAC__StreamMetadata *padding;
1716
1717         if(0 != fseek(iterator->file, iterator->offset[iterator->depth], SEEK_SET)) {
1718                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
1719                 return false;
1720         }
1721
1722         block->is_last = false;
1723
1724         if(!write_metadata_block_header_(iterator->file, &iterator->status, block))
1725                 return false;
1726
1727         if(!write_metadata_block_data_(iterator->file, &iterator->status, block))
1728                 return false;
1729
1730         if(0 == (padding = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING)))
1731                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
1732
1733         padding->is_last = padding_is_last;
1734         padding->length = padding_length;
1735
1736         if(!write_metadata_block_header_(iterator->file, &iterator->status, padding)) {
1737                 FLAC__metadata_object_delete(padding);
1738                 return false;
1739         }
1740
1741         if(!write_metadata_block_data_(iterator->file, &iterator->status, padding)) {
1742                 FLAC__metadata_object_delete(padding);
1743                 return false;
1744         }
1745
1746         FLAC__metadata_object_delete(padding);
1747
1748         if(0 != fseek(iterator->file, iterator->offset[iterator->depth], SEEK_SET)) {
1749                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
1750                 return false;
1751         }
1752
1753         return read_metadata_block_header_(iterator);
1754 }
1755
1756 FLAC__bool rewrite_whole_file_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool append)
1757 {
1758         FILE *tempfile;
1759         char *tempfilename;
1760         int fixup_is_last_code = 0; /* 0 => no need to change any is_last flags */
1761         long fixup_is_last_flag_offset = -1;
1762
1763         FLAC__ASSERT(0 != block || append == false);
1764
1765         if(iterator->is_last) {
1766                 if(append) {
1767                         fixup_is_last_code = 1; /* 1 => clear the is_last flag at the following offset */
1768                         fixup_is_last_flag_offset = iterator->offset[iterator->depth];
1769                 }
1770                 else if(0 == block) {
1771                         simple_iterator_push_(iterator);
1772                         if(!FLAC__metadata_simple_iterator_prev(iterator)) {
1773                                 (void)simple_iterator_pop_(iterator);
1774                                 return false;
1775                         }
1776                         fixup_is_last_code = -1; /* -1 => set the is_last the flag at the following offset */
1777                         fixup_is_last_flag_offset = iterator->offset[iterator->depth];
1778                         if(!simple_iterator_pop_(iterator))
1779                                 return false;
1780                 }
1781         }
1782
1783         if(!simple_iterator_copy_file_prefix_(iterator, &tempfile, &tempfilename, append))
1784                 return false;
1785
1786         if(0 != block) {
1787                 if(!write_metadata_block_header_(tempfile, &iterator->status, block)) {
1788                         cleanup_tempfile_(&tempfile, &tempfilename);
1789                         return false;
1790                 }
1791
1792                 if(!write_metadata_block_data_(tempfile, &iterator->status, block)) {
1793                         cleanup_tempfile_(&tempfile, &tempfilename);
1794                         return false;
1795                 }
1796         }
1797
1798         if(!simple_iterator_copy_file_postfix_(iterator, &tempfile, &tempfilename, fixup_is_last_code, fixup_is_last_flag_offset, block==0))
1799                 return false;
1800
1801         if(append)
1802                 return FLAC__metadata_simple_iterator_next(iterator);
1803
1804         return true;
1805 }
1806
1807 FLAC__bool chain_rewrite_chain_(FLAC__Metadata_Chain *chain)
1808 {
1809         FILE *f;
1810         FLAC__Metadata_Node *node;
1811         FLAC__Metadata_SimpleIteratorStatus status;
1812
1813         FLAC__ASSERT(0 != chain);
1814         FLAC__ASSERT(0 != chain->filename);
1815         FLAC__ASSERT(0 != chain->head);
1816
1817         if(0 == (f = fopen(chain->filename, "r+b"))) {
1818                 chain->status = FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE;
1819                 return false;
1820         }
1821         if(0 != fseek(f, chain->first_offset, SEEK_SET)) {
1822                 chain->status = FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR;
1823                 return false;
1824         }
1825
1826         for(node = chain->head; node; node = node->next) {
1827                 if(!write_metadata_block_header_(f, &status, node->data)) {
1828                         chain->status = get_equivalent_status_(status);
1829                         return false;
1830                 }
1831                 if(!write_metadata_block_data_(f, &status, node->data)) {
1832                         chain->status = get_equivalent_status_(status);
1833                         return false;
1834                 }
1835         }
1836
1837         /*FLAC__ASSERT(fflush(), ftell() == chain->last_offset);*/
1838
1839         (void)fclose(f);
1840
1841         return true;
1842 }
1843
1844 FLAC__bool chain_rewrite_file_(FLAC__Metadata_Chain *chain, const char *tempfile_path_prefix)
1845 {
1846         FILE *f, *tempfile;
1847         char *tempfilename;
1848         FLAC__Metadata_SimpleIteratorStatus status;
1849         const FLAC__Metadata_Node *node;
1850
1851         FLAC__ASSERT(0 != chain);
1852         FLAC__ASSERT(0 != chain->filename);
1853         FLAC__ASSERT(0 != chain->head);
1854
1855         /* copy the file prefix (data up to first metadata block */
1856         if(0 == (f = fopen(chain->filename, "rb"))) {
1857                 chain->status = FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE;
1858                 return false;
1859         }
1860         if(!open_tempfile_(chain->filename, tempfile_path_prefix, &tempfile, &tempfilename, &status)) {
1861                 chain->status = get_equivalent_status_(status);
1862                 cleanup_tempfile_(&tempfile, &tempfilename);
1863                 return false;
1864         }
1865         if(!copy_n_bytes_from_file_(f, tempfile, chain->first_offset, &status)) {
1866                 chain->status = get_equivalent_status_(status);
1867                 cleanup_tempfile_(&tempfile, &tempfilename);
1868                 return false;
1869         }
1870
1871         /* write the metadata */
1872         for(node = chain->head; node; node = node->next) {
1873                 if(!write_metadata_block_header_(tempfile, &status, node->data)) {
1874                         chain->status = get_equivalent_status_(status);
1875                         return false;
1876                 }
1877                 if(!write_metadata_block_data_(tempfile, &status, node->data)) {
1878                         chain->status = get_equivalent_status_(status);
1879                         return false;
1880                 }
1881         }
1882         /*FLAC__ASSERT(fflush(), ftell() == chain->last_offset);*/
1883
1884         /* copy the file postfix (everything after the metadata) */
1885         if(0 != fseek(f, chain->last_offset, SEEK_SET)) {
1886                 cleanup_tempfile_(&tempfile, &tempfilename);
1887                 chain->status = FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR;
1888                 return false;
1889         }
1890         if(!copy_remaining_bytes_from_file_(f, tempfile, &status)) {
1891                 cleanup_tempfile_(&tempfile, &tempfilename);
1892                 chain->status = get_equivalent_status_(status);
1893                 return false;
1894         }
1895
1896         /* move the tempfile on top of the original */
1897         (void)fclose(f);
1898         if(!transport_tempfile_(chain->filename, &tempfile, &tempfilename, &status))
1899                 return false;
1900
1901         return true;
1902 }
1903
1904 void simple_iterator_push_(FLAC__Metadata_SimpleIterator *iterator)
1905 {
1906         FLAC__ASSERT(iterator->depth+1 < SIMPLE_ITERATOR_MAX_PUSH_DEPTH);
1907         iterator->offset[iterator->depth+1] = iterator->offset[iterator->depth];
1908         iterator->depth++;
1909 }
1910
1911 FLAC__bool simple_iterator_pop_(FLAC__Metadata_SimpleIterator *iterator)
1912 {
1913         FLAC__ASSERT(iterator->depth > 0);
1914         iterator->depth--;
1915         if(0 != fseek(iterator->file, iterator->offset[iterator->depth], SEEK_SET)) {
1916                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
1917                 return false;
1918         }
1919
1920         return read_metadata_block_header_(iterator);
1921 }
1922
1923 unsigned seek_to_first_metadata_block_(FILE *f)
1924 {
1925         FLAC__byte buffer[4];
1926         size_t n;
1927         unsigned i;
1928
1929         FLAC__ASSERT(0 != f);
1930         FLAC__ASSERT(FLAC__STREAM_SYNC_LENGTH == 4);
1931
1932         /* skip any id3v2 tag */
1933 #if !defined _MSC_VER && !defined __MINGW32__
1934 /*@@@ don't know how to resolve errno without using LIBC.LIB; must use MSVCRT.LIB only for plugins */
1935         errno = 0;
1936 #endif
1937         n = fread(buffer, 1, 4, f);
1938 #if !defined _MSC_VER && !defined __MINGW32__
1939 /*@@@ don't know how to resolve errno without using LIBC.LIB; must use MSVCRT.LIB only for plugins */
1940         if(errno)
1941                 return 1;
1942         else
1943 #endif
1944         if(n != 4)
1945                 return 2;
1946         else if(0 == memcmp(buffer, "ID3", 3)) {
1947                 unsigned tag_length = 0;
1948
1949                 /* skip to the tag length */
1950                 if(fseek(f, 2, SEEK_CUR) < 0)
1951                         return 1;
1952
1953                 /* read the length */
1954                 for(i = 0; i < 4; i++) {
1955                         if(fread(buffer, 1, 1, f) < 1 || buffer[0] & 0x80)
1956                                 return 1;
1957                         tag_length <<= 7;
1958                         tag_length |= (buffer[0] & 0x7f);
1959                 }
1960
1961                 /* skip the rest of the tag */
1962                 if(fseek(f, tag_length, SEEK_CUR) < 0)
1963                         return 1;
1964
1965                 /* read the stream sync code */
1966 #if !defined _MSC_VER && !defined __MINGW32__
1967 /*@@@ don't know how to resolve errno without using LIBC.LIB; must use MSVCRT.LIB only for plugins */
1968                 errno = 0;
1969 #endif
1970                 n = fread(buffer, 1, 4, f);
1971 #if !defined _MSC_VER && !defined __MINGW32__
1972 /*@@@ don't know how to resolve errno without using LIBC.LIB; must use MSVCRT.LIB only for plugins */
1973                 if(errno)
1974                         return 1;
1975                 else
1976 #endif
1977                 if(n != 4)
1978                         return 2;
1979         }
1980
1981         /* check for the fLaC signature */
1982         if(0 == memcmp(FLAC__STREAM_SYNC_STRING, buffer, FLAC__STREAM_SYNC_LENGTH))
1983                 return 0;
1984         else
1985                 return 2;
1986 }
1987
1988 FLAC__bool simple_iterator_copy_file_prefix_(FLAC__Metadata_SimpleIterator *iterator, FILE **tempfile, char **tempfilename, FLAC__bool append)
1989 {
1990         const long offset_end = append? iterator->offset[iterator->depth] + (long)FLAC__STREAM_METADATA_HEADER_LENGTH + (long)iterator->length : iterator->offset[iterator->depth];
1991
1992         if(0 != fseek(iterator->file, 0, SEEK_SET)) {
1993                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
1994                 return false;
1995         }
1996         if(!open_tempfile_(iterator->filename, iterator->tempfile_path_prefix, tempfile, tempfilename, &iterator->status)) {
1997                 cleanup_tempfile_(tempfile, tempfilename);
1998                 return false;
1999         }
2000         if(!copy_n_bytes_from_file_(iterator->file, *tempfile, offset_end, &iterator->status)) {
2001                 cleanup_tempfile_(tempfile, tempfilename);
2002                 return false;
2003         }
2004
2005         return true;
2006 }
2007
2008 FLAC__bool simple_iterator_copy_file_postfix_(FLAC__Metadata_SimpleIterator *iterator, FILE **tempfile, char **tempfilename, int fixup_is_last_code, long fixup_is_last_flag_offset, FLAC__bool backup)
2009 {
2010         long save_offset = iterator->offset[iterator->depth]; /*@@@ 2G limit */
2011         FLAC__ASSERT(0 != *tempfile);
2012
2013         if(0 != fseek(iterator->file, save_offset + FLAC__STREAM_METADATA_HEADER_LENGTH + iterator->length, SEEK_SET)) {
2014                 cleanup_tempfile_(tempfile, tempfilename);
2015                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
2016                 return false;
2017         }
2018         if(!copy_remaining_bytes_from_file_(iterator->file, *tempfile, &iterator->status)) {
2019                 cleanup_tempfile_(tempfile, tempfilename);
2020                 return false;
2021         }
2022
2023         if(fixup_is_last_code != 0) {
2024                 /*
2025                  * if code == 1, it means a block was appended to the end so
2026                  *   we have to clear the is_last flag of the previous block
2027                  * if code == -1, it means the last block was deleted so
2028                  *   we have to set the is_last flag of the previous block
2029                  */
2030                 /*@@@ MAGIC NUMBERs here; we know the is_last flag is the high bit of the byte at this location */
2031                 FLAC__byte x;
2032                 if(0 != fseek(*tempfile, fixup_is_last_flag_offset, SEEK_SET)) {
2033                         cleanup_tempfile_(tempfile, tempfilename);
2034                         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
2035                         return false;
2036                 }
2037                 if(fread(&x, 1, 1, *tempfile) != 1) {
2038                         cleanup_tempfile_(tempfile, tempfilename);
2039                         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2040                         return false;
2041                 }
2042                 if(fixup_is_last_code > 0) {
2043                         FLAC__ASSERT(x & 0x80);
2044                         x &= 0x7f;
2045                 }
2046                 else {
2047                         FLAC__ASSERT(!(x & 0x80));
2048                         x |= 0x80;
2049                 }
2050                 if(0 != fseek(*tempfile, fixup_is_last_flag_offset, SEEK_SET)) {
2051                         cleanup_tempfile_(tempfile, tempfilename);
2052                         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
2053                         return false;
2054                 }
2055                 if(fwrite(&x, 1, 1, *tempfile) != 1) {
2056                         cleanup_tempfile_(tempfile, tempfilename);
2057                         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
2058                         return false;
2059                 }
2060         }
2061
2062         (void)fclose(iterator->file);
2063
2064         if(!transport_tempfile_(iterator->filename, tempfile, tempfilename, &iterator->status))
2065                 return false;
2066
2067         if(iterator->has_stats)
2068                 set_file_stats_(iterator->filename, &iterator->stats);
2069
2070         if(!simple_iterator_prime_input_(iterator, !iterator->is_writable))
2071                 return false;
2072         if(backup) {
2073                 while(iterator->offset[iterator->depth] + (long)FLAC__STREAM_METADATA_HEADER_LENGTH + (long)iterator->length < save_offset)
2074                         if(!FLAC__metadata_simple_iterator_next(iterator))
2075                                 return false;
2076                 return true;
2077         }
2078         else {
2079                 /* move the iterator to it's original block faster by faking a push, then doing a pop_ */
2080                 FLAC__ASSERT(iterator->depth == 0);
2081                 iterator->offset[0] = save_offset;
2082                 iterator->depth++;
2083                 return simple_iterator_pop_(iterator);
2084         }
2085 }
2086
2087 FLAC__bool copy_n_bytes_from_file_(FILE *file, FILE *tempfile, unsigned bytes/*@@@ 4G limit*/, FLAC__Metadata_SimpleIteratorStatus *status)
2088 {
2089         FLAC__byte buffer[8192];
2090         unsigned n;
2091
2092         while(bytes > 0) {
2093                 n = min(sizeof(buffer), bytes);
2094                 if(fread(buffer, 1, n, file) != n) {
2095                         *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2096                         return false;
2097                 }
2098                 if(fwrite(buffer, 1, n, tempfile) != n) {
2099                         *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
2100                         return false;
2101                 }
2102                 bytes -= n;
2103         }
2104
2105         return true;
2106 }
2107
2108 FLAC__bool copy_remaining_bytes_from_file_(FILE *file, FILE *tempfile, FLAC__Metadata_SimpleIteratorStatus *status)
2109 {
2110         FLAC__byte buffer[8192];
2111         size_t n;
2112
2113         while(!feof(file)) {
2114                 n = fread(buffer, 1, sizeof(buffer), file);
2115                 if(n == 0 && !feof(file)) {
2116                         *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2117                         return false;
2118                 }
2119                 if(n > 0 && fwrite(buffer, 1, n, tempfile) != n) {
2120                         *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
2121                         return false;
2122                 }
2123         }
2124
2125         return true;
2126 }
2127
2128 FLAC__bool open_tempfile_(const char *filename, const char *tempfile_path_prefix, FILE **tempfile, char **tempfilename, FLAC__Metadata_SimpleIteratorStatus *status)
2129 {
2130         static const char *tempfile_suffix = ".metadata_edit";
2131         if(0 == tempfile_path_prefix) {
2132                 if(0 == (*tempfilename = malloc(strlen(filename) + strlen(tempfile_suffix) + 1))) {
2133                         *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
2134                         return false;
2135                 }
2136                 strcpy(*tempfilename, filename);
2137                 strcat(*tempfilename, tempfile_suffix);
2138         }
2139         else {
2140                 const char *p = strrchr(filename, '/');
2141                 if(0 == p)
2142                         p = filename;
2143                 else
2144                         p++;
2145
2146                 if(0 == (*tempfilename = malloc(strlen(tempfile_path_prefix) + 1 + strlen(p) + strlen(tempfile_suffix) + 1))) {
2147                         *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
2148                         return false;
2149                 }
2150                 strcpy(*tempfilename, tempfile_path_prefix);
2151                 strcat(*tempfilename, "/");
2152                 strcat(*tempfilename, p);
2153                 strcat(*tempfilename, tempfile_suffix);
2154         }
2155
2156         if(0 == (*tempfile = fopen(*tempfilename, "w+b"))) {
2157                 *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE;
2158                 return false;
2159         }
2160
2161         return true;
2162 }
2163
2164 FLAC__bool transport_tempfile_(const char *filename, FILE **tempfile, char **tempfilename, FLAC__Metadata_SimpleIteratorStatus *status)
2165 {
2166         FLAC__ASSERT(0 != filename);
2167         FLAC__ASSERT(0 != tempfile);
2168         FLAC__ASSERT(0 != *tempfile);
2169         FLAC__ASSERT(0 != tempfilename);
2170         FLAC__ASSERT(0 != *tempfilename);
2171         FLAC__ASSERT(0 != status);
2172
2173         (void)fclose(*tempfile);
2174         *tempfile = 0;
2175
2176 #if defined _MSC_VER || defined __MINGW32__
2177         if(unlink(filename) < 0) {
2178                 cleanup_tempfile_(tempfile, tempfilename);
2179                 *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR;
2180                 return false;
2181         }
2182 #endif
2183
2184         /*@@@ to fully support the tempfile_path_prefix we need to update this piece to actually copy across filesystems instead of just rename(): */
2185         if(0 != rename(*tempfilename, filename)) {
2186                 cleanup_tempfile_(tempfile, tempfilename);
2187                 *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR;
2188                 return false;
2189         }
2190
2191         cleanup_tempfile_(tempfile, tempfilename);
2192
2193         return true;
2194 }
2195
2196 void cleanup_tempfile_(FILE **tempfile, char **tempfilename)
2197 {
2198         if(0 != *tempfile) {
2199                 (void)fclose(*tempfile);
2200                 *tempfile = 0;
2201         }
2202
2203         if(0 != *tempfilename) {
2204                 (void)unlink(*tempfilename);
2205                 free(*tempfilename);
2206                 *tempfilename = 0;
2207         }
2208 }
2209
2210 FLAC__bool get_file_stats_(const char *filename, struct stat *stats)
2211 {
2212         FLAC__ASSERT(0 != filename);
2213         FLAC__ASSERT(0 != stats);
2214         return (0 == stat(filename, stats));
2215 }
2216
2217 void set_file_stats_(const char *filename, struct stat *stats)
2218 {
2219         struct utimbuf srctime;
2220
2221         FLAC__ASSERT(0 != filename);
2222         FLAC__ASSERT(0 != stats);
2223
2224         srctime.actime = stats->st_atime;
2225         srctime.modtime = stats->st_mtime;
2226         (void)chmod(filename, stats->st_mode);
2227         (void)utime(filename, &srctime);
2228 #if !defined _MSC_VER && !defined __MINGW32__
2229         (void)chown(filename, stats->st_uid, -1);
2230         (void)chown(filename, -1, stats->st_gid);
2231 #endif
2232 }
2233
2234 FLAC__Metadata_ChainStatus get_equivalent_status_(FLAC__Metadata_SimpleIteratorStatus status)
2235 {
2236         switch(status) {
2237                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK:
2238                         return FLAC__METADATA_CHAIN_STATUS_OK;
2239                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT:
2240                         return FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT;
2241                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE:
2242                         return FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE;
2243                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE:
2244                         return FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE;
2245                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE:
2246                         return FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE;
2247                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA:
2248                         return FLAC__METADATA_CHAIN_STATUS_BAD_METADATA;
2249                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR:
2250                         return FLAC__METADATA_CHAIN_STATUS_READ_ERROR;
2251                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR:
2252                         return FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR;
2253                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR:
2254                         return FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR;
2255                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR:
2256                         return FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR;
2257                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR:
2258                         return FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR;
2259                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR:
2260                         return FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
2261                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR:
2262                 default:
2263                         return FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR;
2264         }
2265 }