update to match new default vorbis comment implementation (now with vendor string)
[platform/upstream/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(0 != entry->entry)
1482                 free(entry->entry);
1483
1484         if(entry->length == 0) {
1485                 entry->entry = 0;
1486         }
1487         else {
1488                 if(0 == (entry->entry = malloc(entry->length)))
1489                         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
1490
1491                 if(fread(entry->entry, 1, entry->length, file) != entry->length)
1492                         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
1493         }
1494
1495         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
1496 }
1497
1498 FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_vorbis_comment_(FILE *file, FLAC__StreamMetadata_VorbisComment *block)
1499 {
1500         unsigned i;
1501         FLAC__Metadata_SimpleIteratorStatus status;
1502         const unsigned num_comments_len = FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN / 8;
1503         FLAC__byte buffer[4]; /* magic number is asserted below */
1504
1505         FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN / 8 == 4);
1506         FLAC__ASSERT(0 != file);
1507
1508         if(FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK != (status = read_metadata_block_data_vorbis_comment_entry_(file, &(block->vendor_string))))
1509                 return status;
1510
1511         if(fread(buffer, 1, num_comments_len, file) != num_comments_len)
1512                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
1513         block->num_comments = unpack_uint32_little_endian_(buffer, num_comments_len);
1514
1515         if(block->num_comments == 0) {
1516                 block->comments = 0;
1517         }
1518         else if(0 == (block->comments = calloc(sizeof(FLAC__StreamMetadata_VorbisComment_Entry), block->num_comments)))
1519                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
1520
1521         for(i = 0; i < block->num_comments; i++) {
1522                 if(FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK != (status = read_metadata_block_data_vorbis_comment_entry_(file, block->comments + i)))
1523                         return status;
1524         }
1525
1526         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
1527 }
1528
1529 FLAC__bool write_metadata_block_header_(FILE *file, FLAC__Metadata_SimpleIteratorStatus *status, const FLAC__StreamMetadata *block)
1530 {
1531         FLAC__byte buffer[FLAC__STREAM_METADATA_HEADER_LENGTH];
1532
1533         FLAC__ASSERT(0 != file);
1534         FLAC__ASSERT(0 != status);
1535         FLAC__ASSERT(block->length < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
1536
1537         buffer[0] = (block->is_last? 0x80 : 0) | (FLAC__byte)block->type;
1538         pack_uint32_(block->length, buffer + 1, 3);
1539
1540         if(fwrite(buffer, 1, FLAC__STREAM_METADATA_HEADER_LENGTH, file) != FLAC__STREAM_METADATA_HEADER_LENGTH) {
1541                 *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
1542                 return false;
1543         }
1544
1545         return true;
1546 }
1547
1548 FLAC__bool write_metadata_block_data_(FILE *file, FLAC__Metadata_SimpleIteratorStatus *status, const FLAC__StreamMetadata *block)
1549 {
1550         FLAC__ASSERT(0 != file);
1551         FLAC__ASSERT(0 != status);
1552
1553         switch(block->type) {
1554                 case FLAC__METADATA_TYPE_STREAMINFO:
1555                         *status = write_metadata_block_data_streaminfo_(file, &block->data.stream_info);
1556                         break;
1557                 case FLAC__METADATA_TYPE_PADDING:
1558                         *status = write_metadata_block_data_padding_(file, &block->data.padding, block->length);
1559                         break;
1560                 case FLAC__METADATA_TYPE_APPLICATION:
1561                         *status = write_metadata_block_data_application_(file, &block->data.application, block->length);
1562                         break;
1563                 case FLAC__METADATA_TYPE_SEEKTABLE:
1564                         *status = write_metadata_block_data_seektable_(file, &block->data.seek_table);
1565                         break;
1566                 case FLAC__METADATA_TYPE_VORBIS_COMMENT:
1567                         *status = write_metadata_block_data_vorbis_comment_(file, &block->data.vorbis_comment);
1568                         break;
1569                 default:
1570                         FLAC__ASSERT(0);
1571                         *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR;
1572         }
1573         return (*status == FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK);
1574 }
1575
1576 FLAC__Metadata_SimpleIteratorStatus write_metadata_block_data_streaminfo_(FILE *file, const FLAC__StreamMetadata_StreamInfo *block)
1577 {
1578         FLAC__byte buffer[FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
1579         const unsigned channels1 = block->channels - 1;
1580         const unsigned bps1 = block->bits_per_sample - 1;
1581
1582         FLAC__ASSERT(0 != file);
1583
1584         /* @@@ we are using hardcoded numbers for simplicity but we should
1585          * probably eventually write a bit-level packer and use the
1586          * _STREAMINFO_ constants.
1587          */
1588         pack_uint32_(block->min_blocksize, buffer, 2);
1589         pack_uint32_(block->max_blocksize, buffer+2, 2);
1590         pack_uint32_(block->min_framesize, buffer+4, 3);
1591         pack_uint32_(block->max_framesize, buffer+7, 3);
1592         buffer[10] = (block->sample_rate >> 12) & 0xff;
1593         buffer[11] = (block->sample_rate >> 4) & 0xff;
1594         buffer[12] = ((block->sample_rate & 0x0f) << 4) | (channels1 << 1) | (bps1 >> 4);
1595         buffer[13] = (FLAC__byte)(((bps1 & 0x0f) << 4) | ((block->total_samples >> 32) & 0x0f));
1596         pack_uint32_((FLAC__uint32)block->total_samples, buffer+14, 4);
1597         memcpy(buffer+18, block->md5sum, 16);
1598
1599         if(fwrite(buffer, 1, FLAC__STREAM_METADATA_STREAMINFO_LENGTH, file) != FLAC__STREAM_METADATA_STREAMINFO_LENGTH)
1600                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
1601
1602         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
1603 }
1604
1605 FLAC__Metadata_SimpleIteratorStatus write_metadata_block_data_padding_(FILE *file, const FLAC__StreamMetadata_Padding *block, unsigned block_length)
1606 {
1607         unsigned i, n = block_length;
1608         FLAC__byte buffer[1024];
1609
1610         FLAC__ASSERT(0 != file);
1611
1612         (void)block;
1613
1614         memset(buffer, 0, 1024);
1615
1616         for(i = 0; i < n/1024; i++)
1617                 if(fwrite(buffer, 1, 1024, file) != 1024)
1618                         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
1619
1620         n %= 1024;
1621
1622         if(fwrite(buffer, 1, n, file) != n)
1623                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
1624
1625         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
1626 }
1627
1628 FLAC__Metadata_SimpleIteratorStatus write_metadata_block_data_application_(FILE *file, const FLAC__StreamMetadata_Application *block, unsigned block_length)
1629 {
1630         const unsigned id_bytes = FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8;
1631
1632         FLAC__ASSERT(0 != file);
1633
1634         if(fwrite(block->id, 1, id_bytes, file) != id_bytes)
1635                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
1636
1637         block_length -= id_bytes;
1638
1639         if(fwrite(block->data, 1, block_length, file) != block_length)
1640                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
1641
1642         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
1643 }
1644
1645 FLAC__Metadata_SimpleIteratorStatus write_metadata_block_data_seektable_(FILE *file, const FLAC__StreamMetadata_SeekTable *block)
1646 {
1647         unsigned i;
1648         FLAC__byte buffer[FLAC__STREAM_METADATA_SEEKPOINT_LENGTH];
1649
1650         FLAC__ASSERT(0 != file);
1651
1652         for(i = 0; i < block->num_points; i++) {
1653                 /*@@@ some MAGIC NUMBERs here */
1654                 pack_uint64_(block->points[i].sample_number, buffer, 8);
1655                 pack_uint64_(block->points[i].stream_offset, buffer+8, 8);
1656                 pack_uint32_(block->points[i].frame_samples, buffer+16, 2);
1657                 if(fwrite(buffer, 1, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH, file) != FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)
1658                         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
1659         }
1660
1661         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
1662 }
1663
1664 FLAC__Metadata_SimpleIteratorStatus write_metadata_block_data_vorbis_comment_(FILE *file, const FLAC__StreamMetadata_VorbisComment *block)
1665 {
1666         unsigned i;
1667         const unsigned entry_length_len = FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN / 8;
1668         const unsigned num_comments_len = FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN / 8;
1669         FLAC__byte buffer[4]; /* magic number is asserted below */
1670
1671         FLAC__ASSERT(max(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN, FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN) / 8 == 4);
1672         FLAC__ASSERT(0 != file);
1673
1674         pack_uint32_little_endian_(block->vendor_string.length, buffer, entry_length_len);
1675         if(fwrite(buffer, 1, entry_length_len, file) != entry_length_len)
1676                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
1677         if(fwrite(block->vendor_string.entry, 1, block->vendor_string.length, file) != block->vendor_string.length)
1678                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
1679
1680         pack_uint32_little_endian_(block->num_comments, buffer, num_comments_len);
1681         if(fwrite(buffer, 1, num_comments_len, file) != num_comments_len)
1682                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
1683
1684         for(i = 0; i < block->num_comments; i++) {
1685                 pack_uint32_little_endian_(block->comments[i].length, buffer, entry_length_len);
1686                 if(fwrite(buffer, 1, entry_length_len, file) != entry_length_len)
1687                         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
1688                 if(fwrite(block->comments[i].entry, 1, block->comments[i].length, file) != block->comments[i].length)
1689                         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
1690         }
1691
1692         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
1693 }
1694
1695 FLAC__bool write_metadata_block_stationary_(FLAC__Metadata_SimpleIterator *iterator, const FLAC__StreamMetadata *block)
1696 {
1697         if(0 != fseek(iterator->file, iterator->offset[iterator->depth], SEEK_SET)) {
1698                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
1699                 return false;
1700         }
1701
1702         if(!write_metadata_block_header_(iterator->file, &iterator->status, block))
1703                 return false;
1704
1705         if(!write_metadata_block_data_(iterator->file, &iterator->status, block))
1706                 return false;
1707
1708         if(0 != fseek(iterator->file, iterator->offset[iterator->depth], SEEK_SET)) {
1709                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
1710                 return false;
1711         }
1712
1713         return read_metadata_block_header_(iterator);
1714 }
1715
1716 FLAC__bool write_metadata_block_stationary_with_padding_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, unsigned padding_length, FLAC__bool padding_is_last)
1717 {
1718         FLAC__StreamMetadata *padding;
1719
1720         if(0 != fseek(iterator->file, iterator->offset[iterator->depth], SEEK_SET)) {
1721                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
1722                 return false;
1723         }
1724
1725         block->is_last = false;
1726
1727         if(!write_metadata_block_header_(iterator->file, &iterator->status, block))
1728                 return false;
1729
1730         if(!write_metadata_block_data_(iterator->file, &iterator->status, block))
1731                 return false;
1732
1733         if(0 == (padding = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING)))
1734                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
1735
1736         padding->is_last = padding_is_last;
1737         padding->length = padding_length;
1738
1739         if(!write_metadata_block_header_(iterator->file, &iterator->status, padding)) {
1740                 FLAC__metadata_object_delete(padding);
1741                 return false;
1742         }
1743
1744         if(!write_metadata_block_data_(iterator->file, &iterator->status, padding)) {
1745                 FLAC__metadata_object_delete(padding);
1746                 return false;
1747         }
1748
1749         FLAC__metadata_object_delete(padding);
1750
1751         if(0 != fseek(iterator->file, iterator->offset[iterator->depth], SEEK_SET)) {
1752                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
1753                 return false;
1754         }
1755
1756         return read_metadata_block_header_(iterator);
1757 }
1758
1759 FLAC__bool rewrite_whole_file_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool append)
1760 {
1761         FILE *tempfile;
1762         char *tempfilename;
1763         int fixup_is_last_code = 0; /* 0 => no need to change any is_last flags */
1764         long fixup_is_last_flag_offset = -1;
1765
1766         FLAC__ASSERT(0 != block || append == false);
1767
1768         if(iterator->is_last) {
1769                 if(append) {
1770                         fixup_is_last_code = 1; /* 1 => clear the is_last flag at the following offset */
1771                         fixup_is_last_flag_offset = iterator->offset[iterator->depth];
1772                 }
1773                 else if(0 == block) {
1774                         simple_iterator_push_(iterator);
1775                         if(!FLAC__metadata_simple_iterator_prev(iterator)) {
1776                                 (void)simple_iterator_pop_(iterator);
1777                                 return false;
1778                         }
1779                         fixup_is_last_code = -1; /* -1 => set the is_last the flag at the following offset */
1780                         fixup_is_last_flag_offset = iterator->offset[iterator->depth];
1781                         if(!simple_iterator_pop_(iterator))
1782                                 return false;
1783                 }
1784         }
1785
1786         if(!simple_iterator_copy_file_prefix_(iterator, &tempfile, &tempfilename, append))
1787                 return false;
1788
1789         if(0 != block) {
1790                 if(!write_metadata_block_header_(tempfile, &iterator->status, block)) {
1791                         cleanup_tempfile_(&tempfile, &tempfilename);
1792                         return false;
1793                 }
1794
1795                 if(!write_metadata_block_data_(tempfile, &iterator->status, block)) {
1796                         cleanup_tempfile_(&tempfile, &tempfilename);
1797                         return false;
1798                 }
1799         }
1800
1801         if(!simple_iterator_copy_file_postfix_(iterator, &tempfile, &tempfilename, fixup_is_last_code, fixup_is_last_flag_offset, block==0))
1802                 return false;
1803
1804         if(append)
1805                 return FLAC__metadata_simple_iterator_next(iterator);
1806
1807         return true;
1808 }
1809
1810 FLAC__bool chain_rewrite_chain_(FLAC__Metadata_Chain *chain)
1811 {
1812         FILE *f;
1813         FLAC__Metadata_Node *node;
1814         FLAC__Metadata_SimpleIteratorStatus status;
1815
1816         FLAC__ASSERT(0 != chain);
1817         FLAC__ASSERT(0 != chain->filename);
1818         FLAC__ASSERT(0 != chain->head);
1819
1820         if(0 == (f = fopen(chain->filename, "r+b"))) {
1821                 chain->status = FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE;
1822                 return false;
1823         }
1824         if(0 != fseek(f, chain->first_offset, SEEK_SET)) {
1825                 chain->status = FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR;
1826                 return false;
1827         }
1828
1829         for(node = chain->head; node; node = node->next) {
1830                 if(!write_metadata_block_header_(f, &status, node->data)) {
1831                         chain->status = get_equivalent_status_(status);
1832                         return false;
1833                 }
1834                 if(!write_metadata_block_data_(f, &status, node->data)) {
1835                         chain->status = get_equivalent_status_(status);
1836                         return false;
1837                 }
1838         }
1839
1840         /*FLAC__ASSERT(fflush(), ftell() == chain->last_offset);*/
1841
1842         (void)fclose(f);
1843
1844         return true;
1845 }
1846
1847 FLAC__bool chain_rewrite_file_(FLAC__Metadata_Chain *chain, const char *tempfile_path_prefix)
1848 {
1849         FILE *f, *tempfile;
1850         char *tempfilename;
1851         FLAC__Metadata_SimpleIteratorStatus status;
1852         const FLAC__Metadata_Node *node;
1853
1854         FLAC__ASSERT(0 != chain);
1855         FLAC__ASSERT(0 != chain->filename);
1856         FLAC__ASSERT(0 != chain->head);
1857
1858         /* copy the file prefix (data up to first metadata block */
1859         if(0 == (f = fopen(chain->filename, "rb"))) {
1860                 chain->status = FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE;
1861                 return false;
1862         }
1863         if(!open_tempfile_(chain->filename, tempfile_path_prefix, &tempfile, &tempfilename, &status)) {
1864                 chain->status = get_equivalent_status_(status);
1865                 cleanup_tempfile_(&tempfile, &tempfilename);
1866                 return false;
1867         }
1868         if(!copy_n_bytes_from_file_(f, tempfile, chain->first_offset, &status)) {
1869                 chain->status = get_equivalent_status_(status);
1870                 cleanup_tempfile_(&tempfile, &tempfilename);
1871                 return false;
1872         }
1873
1874         /* write the metadata */
1875         for(node = chain->head; node; node = node->next) {
1876                 if(!write_metadata_block_header_(tempfile, &status, node->data)) {
1877                         chain->status = get_equivalent_status_(status);
1878                         return false;
1879                 }
1880                 if(!write_metadata_block_data_(tempfile, &status, node->data)) {
1881                         chain->status = get_equivalent_status_(status);
1882                         return false;
1883                 }
1884         }
1885         /*FLAC__ASSERT(fflush(), ftell() == chain->last_offset);*/
1886
1887         /* copy the file postfix (everything after the metadata) */
1888         if(0 != fseek(f, chain->last_offset, SEEK_SET)) {
1889                 cleanup_tempfile_(&tempfile, &tempfilename);
1890                 chain->status = FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR;
1891                 return false;
1892         }
1893         if(!copy_remaining_bytes_from_file_(f, tempfile, &status)) {
1894                 cleanup_tempfile_(&tempfile, &tempfilename);
1895                 chain->status = get_equivalent_status_(status);
1896                 return false;
1897         }
1898
1899         /* move the tempfile on top of the original */
1900         (void)fclose(f);
1901         if(!transport_tempfile_(chain->filename, &tempfile, &tempfilename, &status))
1902                 return false;
1903
1904         return true;
1905 }
1906
1907 void simple_iterator_push_(FLAC__Metadata_SimpleIterator *iterator)
1908 {
1909         FLAC__ASSERT(iterator->depth+1 < SIMPLE_ITERATOR_MAX_PUSH_DEPTH);
1910         iterator->offset[iterator->depth+1] = iterator->offset[iterator->depth];
1911         iterator->depth++;
1912 }
1913
1914 FLAC__bool simple_iterator_pop_(FLAC__Metadata_SimpleIterator *iterator)
1915 {
1916         FLAC__ASSERT(iterator->depth > 0);
1917         iterator->depth--;
1918         if(0 != fseek(iterator->file, iterator->offset[iterator->depth], SEEK_SET)) {
1919                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
1920                 return false;
1921         }
1922
1923         return read_metadata_block_header_(iterator);
1924 }
1925
1926 unsigned seek_to_first_metadata_block_(FILE *f)
1927 {
1928         FLAC__byte buffer[4];
1929         size_t n;
1930         unsigned i;
1931
1932         FLAC__ASSERT(0 != f);
1933         FLAC__ASSERT(FLAC__STREAM_SYNC_LENGTH == 4);
1934
1935         /* skip any id3v2 tag */
1936 #if !defined _MSC_VER && !defined __MINGW32__
1937 /*@@@ don't know how to resolve errno without using LIBC.LIB; must use MSVCRT.LIB only for plugins */
1938         errno = 0;
1939 #endif
1940         n = fread(buffer, 1, 4, f);
1941 #if !defined _MSC_VER && !defined __MINGW32__
1942 /*@@@ don't know how to resolve errno without using LIBC.LIB; must use MSVCRT.LIB only for plugins */
1943         if(errno)
1944                 return 1;
1945         else
1946 #endif
1947         if(n != 4)
1948                 return 2;
1949         else if(0 == memcmp(buffer, "ID3", 3)) {
1950                 unsigned tag_length = 0;
1951
1952                 /* skip to the tag length */
1953                 if(fseek(f, 2, SEEK_CUR) < 0)
1954                         return 1;
1955
1956                 /* read the length */
1957                 for(i = 0; i < 4; i++) {
1958                         if(fread(buffer, 1, 1, f) < 1 || buffer[0] & 0x80)
1959                                 return 1;
1960                         tag_length <<= 7;
1961                         tag_length |= (buffer[0] & 0x7f);
1962                 }
1963
1964                 /* skip the rest of the tag */
1965                 if(fseek(f, tag_length, SEEK_CUR) < 0)
1966                         return 1;
1967
1968                 /* read the stream sync code */
1969 #if !defined _MSC_VER && !defined __MINGW32__
1970 /*@@@ don't know how to resolve errno without using LIBC.LIB; must use MSVCRT.LIB only for plugins */
1971                 errno = 0;
1972 #endif
1973                 n = fread(buffer, 1, 4, f);
1974 #if !defined _MSC_VER && !defined __MINGW32__
1975 /*@@@ don't know how to resolve errno without using LIBC.LIB; must use MSVCRT.LIB only for plugins */
1976                 if(errno)
1977                         return 1;
1978                 else
1979 #endif
1980                 if(n != 4)
1981                         return 2;
1982         }
1983
1984         /* check for the fLaC signature */
1985         if(0 == memcmp(FLAC__STREAM_SYNC_STRING, buffer, FLAC__STREAM_SYNC_LENGTH))
1986                 return 0;
1987         else
1988                 return 2;
1989 }
1990
1991 FLAC__bool simple_iterator_copy_file_prefix_(FLAC__Metadata_SimpleIterator *iterator, FILE **tempfile, char **tempfilename, FLAC__bool append)
1992 {
1993         const long offset_end = append? iterator->offset[iterator->depth] + (long)FLAC__STREAM_METADATA_HEADER_LENGTH + (long)iterator->length : iterator->offset[iterator->depth];
1994
1995         if(0 != fseek(iterator->file, 0, SEEK_SET)) {
1996                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
1997                 return false;
1998         }
1999         if(!open_tempfile_(iterator->filename, iterator->tempfile_path_prefix, tempfile, tempfilename, &iterator->status)) {
2000                 cleanup_tempfile_(tempfile, tempfilename);
2001                 return false;
2002         }
2003         if(!copy_n_bytes_from_file_(iterator->file, *tempfile, offset_end, &iterator->status)) {
2004                 cleanup_tempfile_(tempfile, tempfilename);
2005                 return false;
2006         }
2007
2008         return true;
2009 }
2010
2011 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)
2012 {
2013         long save_offset = iterator->offset[iterator->depth]; /*@@@ 2G limit */
2014         FLAC__ASSERT(0 != *tempfile);
2015
2016         if(0 != fseek(iterator->file, save_offset + FLAC__STREAM_METADATA_HEADER_LENGTH + iterator->length, SEEK_SET)) {
2017                 cleanup_tempfile_(tempfile, tempfilename);
2018                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
2019                 return false;
2020         }
2021         if(!copy_remaining_bytes_from_file_(iterator->file, *tempfile, &iterator->status)) {
2022                 cleanup_tempfile_(tempfile, tempfilename);
2023                 return false;
2024         }
2025
2026         if(fixup_is_last_code != 0) {
2027                 /*
2028                  * if code == 1, it means a block was appended to the end so
2029                  *   we have to clear the is_last flag of the previous block
2030                  * if code == -1, it means the last block was deleted so
2031                  *   we have to set the is_last flag of the previous block
2032                  */
2033                 /*@@@ MAGIC NUMBERs here; we know the is_last flag is the high bit of the byte at this location */
2034                 FLAC__byte x;
2035                 if(0 != fseek(*tempfile, fixup_is_last_flag_offset, SEEK_SET)) {
2036                         cleanup_tempfile_(tempfile, tempfilename);
2037                         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
2038                         return false;
2039                 }
2040                 if(fread(&x, 1, 1, *tempfile) != 1) {
2041                         cleanup_tempfile_(tempfile, tempfilename);
2042                         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2043                         return false;
2044                 }
2045                 if(fixup_is_last_code > 0) {
2046                         FLAC__ASSERT(x & 0x80);
2047                         x &= 0x7f;
2048                 }
2049                 else {
2050                         FLAC__ASSERT(!(x & 0x80));
2051                         x |= 0x80;
2052                 }
2053                 if(0 != fseek(*tempfile, fixup_is_last_flag_offset, SEEK_SET)) {
2054                         cleanup_tempfile_(tempfile, tempfilename);
2055                         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
2056                         return false;
2057                 }
2058                 if(fwrite(&x, 1, 1, *tempfile) != 1) {
2059                         cleanup_tempfile_(tempfile, tempfilename);
2060                         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
2061                         return false;
2062                 }
2063         }
2064
2065         (void)fclose(iterator->file);
2066
2067         if(!transport_tempfile_(iterator->filename, tempfile, tempfilename, &iterator->status))
2068                 return false;
2069
2070         if(iterator->has_stats)
2071                 set_file_stats_(iterator->filename, &iterator->stats);
2072
2073         if(!simple_iterator_prime_input_(iterator, !iterator->is_writable))
2074                 return false;
2075         if(backup) {
2076                 while(iterator->offset[iterator->depth] + (long)FLAC__STREAM_METADATA_HEADER_LENGTH + (long)iterator->length < save_offset)
2077                         if(!FLAC__metadata_simple_iterator_next(iterator))
2078                                 return false;
2079                 return true;
2080         }
2081         else {
2082                 /* move the iterator to it's original block faster by faking a push, then doing a pop_ */
2083                 FLAC__ASSERT(iterator->depth == 0);
2084                 iterator->offset[0] = save_offset;
2085                 iterator->depth++;
2086                 return simple_iterator_pop_(iterator);
2087         }
2088 }
2089
2090 FLAC__bool copy_n_bytes_from_file_(FILE *file, FILE *tempfile, unsigned bytes/*@@@ 4G limit*/, FLAC__Metadata_SimpleIteratorStatus *status)
2091 {
2092         FLAC__byte buffer[8192];
2093         unsigned n;
2094
2095         while(bytes > 0) {
2096                 n = min(sizeof(buffer), bytes);
2097                 if(fread(buffer, 1, n, file) != n) {
2098                         *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2099                         return false;
2100                 }
2101                 if(fwrite(buffer, 1, n, tempfile) != n) {
2102                         *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
2103                         return false;
2104                 }
2105                 bytes -= n;
2106         }
2107
2108         return true;
2109 }
2110
2111 FLAC__bool copy_remaining_bytes_from_file_(FILE *file, FILE *tempfile, FLAC__Metadata_SimpleIteratorStatus *status)
2112 {
2113         FLAC__byte buffer[8192];
2114         size_t n;
2115
2116         while(!feof(file)) {
2117                 n = fread(buffer, 1, sizeof(buffer), file);
2118                 if(n == 0 && !feof(file)) {
2119                         *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
2120                         return false;
2121                 }
2122                 if(n > 0 && fwrite(buffer, 1, n, tempfile) != n) {
2123                         *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR;
2124                         return false;
2125                 }
2126         }
2127
2128         return true;
2129 }
2130
2131 FLAC__bool open_tempfile_(const char *filename, const char *tempfile_path_prefix, FILE **tempfile, char **tempfilename, FLAC__Metadata_SimpleIteratorStatus *status)
2132 {
2133         static const char *tempfile_suffix = ".metadata_edit";
2134         if(0 == tempfile_path_prefix) {
2135                 if(0 == (*tempfilename = malloc(strlen(filename) + strlen(tempfile_suffix) + 1))) {
2136                         *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
2137                         return false;
2138                 }
2139                 strcpy(*tempfilename, filename);
2140                 strcat(*tempfilename, tempfile_suffix);
2141         }
2142         else {
2143                 const char *p = strrchr(filename, '/');
2144                 if(0 == p)
2145                         p = filename;
2146                 else
2147                         p++;
2148
2149                 if(0 == (*tempfilename = malloc(strlen(tempfile_path_prefix) + 1 + strlen(p) + strlen(tempfile_suffix) + 1))) {
2150                         *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
2151                         return false;
2152                 }
2153                 strcpy(*tempfilename, tempfile_path_prefix);
2154                 strcat(*tempfilename, "/");
2155                 strcat(*tempfilename, p);
2156                 strcat(*tempfilename, tempfile_suffix);
2157         }
2158
2159         if(0 == (*tempfile = fopen(*tempfilename, "w+b"))) {
2160                 *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE;
2161                 return false;
2162         }
2163
2164         return true;
2165 }
2166
2167 FLAC__bool transport_tempfile_(const char *filename, FILE **tempfile, char **tempfilename, FLAC__Metadata_SimpleIteratorStatus *status)
2168 {
2169         FLAC__ASSERT(0 != filename);
2170         FLAC__ASSERT(0 != tempfile);
2171         FLAC__ASSERT(0 != *tempfile);
2172         FLAC__ASSERT(0 != tempfilename);
2173         FLAC__ASSERT(0 != *tempfilename);
2174         FLAC__ASSERT(0 != status);
2175
2176         (void)fclose(*tempfile);
2177         *tempfile = 0;
2178
2179 #if defined _MSC_VER || defined __MINGW32__
2180         if(unlink(filename) < 0) {
2181                 cleanup_tempfile_(tempfile, tempfilename);
2182                 *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR;
2183                 return false;
2184         }
2185 #endif
2186
2187         /*@@@ to fully support the tempfile_path_prefix we need to update this piece to actually copy across filesystems instead of just rename(): */
2188         if(0 != rename(*tempfilename, filename)) {
2189                 cleanup_tempfile_(tempfile, tempfilename);
2190                 *status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR;
2191                 return false;
2192         }
2193
2194         cleanup_tempfile_(tempfile, tempfilename);
2195
2196         return true;
2197 }
2198
2199 void cleanup_tempfile_(FILE **tempfile, char **tempfilename)
2200 {
2201         if(0 != *tempfile) {
2202                 (void)fclose(*tempfile);
2203                 *tempfile = 0;
2204         }
2205
2206         if(0 != *tempfilename) {
2207                 (void)unlink(*tempfilename);
2208                 free(*tempfilename);
2209                 *tempfilename = 0;
2210         }
2211 }
2212
2213 FLAC__bool get_file_stats_(const char *filename, struct stat *stats)
2214 {
2215         FLAC__ASSERT(0 != filename);
2216         FLAC__ASSERT(0 != stats);
2217         return (0 == stat(filename, stats));
2218 }
2219
2220 void set_file_stats_(const char *filename, struct stat *stats)
2221 {
2222         struct utimbuf srctime;
2223
2224         FLAC__ASSERT(0 != filename);
2225         FLAC__ASSERT(0 != stats);
2226
2227         srctime.actime = stats->st_atime;
2228         srctime.modtime = stats->st_mtime;
2229         (void)chmod(filename, stats->st_mode);
2230         (void)utime(filename, &srctime);
2231 #if !defined _MSC_VER && !defined __MINGW32__
2232         (void)chown(filename, stats->st_uid, -1);
2233         (void)chown(filename, -1, stats->st_gid);
2234 #endif
2235 }
2236
2237 FLAC__Metadata_ChainStatus get_equivalent_status_(FLAC__Metadata_SimpleIteratorStatus status)
2238 {
2239         switch(status) {
2240                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK:
2241                         return FLAC__METADATA_CHAIN_STATUS_OK;
2242                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT:
2243                         return FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT;
2244                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE:
2245                         return FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE;
2246                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE:
2247                         return FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE;
2248                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE:
2249                         return FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE;
2250                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA:
2251                         return FLAC__METADATA_CHAIN_STATUS_BAD_METADATA;
2252                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR:
2253                         return FLAC__METADATA_CHAIN_STATUS_READ_ERROR;
2254                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR:
2255                         return FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR;
2256                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR:
2257                         return FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR;
2258                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR:
2259                         return FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR;
2260                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR:
2261                         return FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR;
2262                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR:
2263                         return FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
2264                 case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR:
2265                 default:
2266                         return FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR;
2267         }
2268 }