9d9d58a4725d4884b38d4e9fe5990614547cdfaf
[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 = malloc(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         FLAC__Metadata_Node *node = (FLAC__Metadata_Node*)malloc(sizeof(FLAC__Metadata_Node));
752         if(0 != node)
753                 memset(node, 0, sizeof(FLAC__Metadata_Node));
754         return node;
755 }
756
757 static void node_delete_(FLAC__Metadata_Node *node)
758 {
759         FLAC__ASSERT(0 != node);
760         if(0 != node->data)
761                 FLAC__metadata_object_delete(node->data);
762         free(node);
763 }
764
765 static void chain_append_node_(FLAC__Metadata_Chain *chain, FLAC__Metadata_Node *node)
766 {
767         FLAC__ASSERT(0 != chain);
768         FLAC__ASSERT(0 != node);
769         FLAC__ASSERT(0 != node->data);
770
771         node->next = node->prev = 0;
772         node->data->is_last = true;
773         if(0 != chain->tail)
774                 chain->tail->data->is_last = false;
775
776         if(0 == chain->head)
777                 chain->head = node;
778         else {
779                 FLAC__ASSERT(0 != chain->tail);
780                 chain->tail->next = node;
781                 node->prev = chain->tail;
782         }
783         chain->tail = node;
784         chain->nodes++;
785 }
786
787 static void chain_remove_node_(FLAC__Metadata_Chain *chain, FLAC__Metadata_Node *node)
788 {
789         FLAC__ASSERT(0 != chain);
790         FLAC__ASSERT(0 != node);
791
792         if(node == chain->head)
793                 chain->head = node->next;
794         else
795                 node->prev->next = node->next;
796
797         if(node == chain->tail)
798                 chain->tail = node->prev;
799         else
800                 node->next->prev = node->prev;
801
802         if(0 != chain->tail)
803                 chain->tail->data->is_last = true;
804
805         chain->nodes--;
806 }
807
808 static void chain_delete_node_(FLAC__Metadata_Chain *chain, FLAC__Metadata_Node *node)
809 {
810         chain_remove_node_(chain, node);
811         node_delete_(node);
812 }
813
814 static unsigned chain_calculate_length_(FLAC__Metadata_Chain *chain)
815 {
816         const FLAC__Metadata_Node *node;
817         unsigned length = 0;
818         for(node = chain->head; node; node = node->next)
819                 length += (FLAC__STREAM_METADATA_HEADER_LENGTH + node->data->length);
820         return length;
821 }
822
823 static void iterator_insert_node_(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Node *node)
824 {
825         FLAC__ASSERT(0 != node);
826         FLAC__ASSERT(0 != node->data);
827         FLAC__ASSERT(0 != iterator);
828         FLAC__ASSERT(0 != iterator->current);
829         FLAC__ASSERT(0 != iterator->chain);
830         FLAC__ASSERT(0 != iterator->chain->head);
831         FLAC__ASSERT(0 != iterator->chain->tail);
832
833         node->data->is_last = false;
834
835         node->prev = iterator->current->prev;
836         node->next = iterator->current;
837
838         if(0 == node->prev)
839                 iterator->chain->head = node;
840         else
841                 node->prev->next = node;
842
843         iterator->current->prev = node;
844
845         iterator->chain->nodes++;
846 }
847
848 static void iterator_insert_node_after_(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Node *node)
849 {
850         FLAC__ASSERT(0 != node);
851         FLAC__ASSERT(0 != node->data);
852         FLAC__ASSERT(0 != iterator);
853         FLAC__ASSERT(0 != iterator->current);
854         FLAC__ASSERT(0 != iterator->chain);
855         FLAC__ASSERT(0 != iterator->chain->head);
856         FLAC__ASSERT(0 != iterator->chain->tail);
857
858         iterator->current->data->is_last = false;
859
860         node->prev = iterator->current;
861         node->next = iterator->current->next;
862
863         if(0 == node->next)
864                 iterator->chain->tail = node;
865         else
866                 node->next->prev = node;
867
868         node->prev->next = node;
869
870         iterator->chain->tail->data->is_last = true;
871
872         iterator->chain->nodes++;
873 }
874
875 /* return true iff node and node->next are both padding */
876 static FLAC__bool chain_merge_adjacent_padding_(FLAC__Metadata_Chain *chain, FLAC__Metadata_Node *node)
877 {
878         if(node->data->type == FLAC__METADATA_TYPE_PADDING && 0 != node->next && node->next->data->type == FLAC__METADATA_TYPE_PADDING) {
879                 const unsigned growth = FLAC__STREAM_METADATA_HEADER_LENGTH + node->next->data->length;
880                 node->data->length += growth;
881
882                 chain_delete_node_(chain, node->next);
883                 return true;
884         }
885         else
886                 return false;
887 }
888
889 FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new()
890 {
891         FLAC__Metadata_Chain *chain = malloc(sizeof(FLAC__Metadata_Chain));
892
893         if(0 != chain) {
894                 chain->filename = 0;
895                 chain->head = chain->tail = 0;
896                 chain->nodes = 0;
897                 chain->status = FLAC__METADATA_CHAIN_STATUS_OK;
898                 chain->initial_length = 0;
899         }
900
901         return chain;
902 }
903
904 FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain)
905 {
906         FLAC__Metadata_Node *node, *next;
907
908         FLAC__ASSERT(0 != chain);
909
910         for(node = chain->head; node; ) {
911                 next = node->next;
912                 node_delete_(node);
913                 node = next;
914         }
915
916         if(0 != chain->filename)
917                 free(chain->filename);
918
919         free(chain);
920 }
921
922 FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain)
923 {
924         FLAC__Metadata_ChainStatus status;
925
926         FLAC__ASSERT(0 != chain);
927
928         status = chain->status;
929         chain->status = FLAC__METADATA_CHAIN_STATUS_OK;
930         return status;
931 }
932
933 FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename)
934 {
935         FLAC__Metadata_SimpleIterator *iterator;
936         FLAC__Metadata_Node *node;
937
938         FLAC__ASSERT(0 != chain);
939         FLAC__ASSERT(0 != filename);
940
941         if(0 == (chain->filename = strdup(filename))) {
942                 chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
943                 return false;
944         }
945
946         if(0 == (iterator = FLAC__metadata_simple_iterator_new())) {
947                 chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
948                 return false;
949         }
950
951         if(!FLAC__metadata_simple_iterator_init(iterator, filename, /*read_only=*/true, /*preserve_file_stats=*/false)) {
952                 chain->status = get_equivalent_status_(iterator->status);
953                 return false;
954         }
955
956         chain->first_offset = iterator->offset[iterator->depth];
957
958         do {
959                 node = node_new_();
960                 if(0 == node) {
961                         chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
962                         return false;
963                 }
964                 node->data = FLAC__metadata_simple_iterator_get_block(iterator);
965                 if(0 == node->data) {
966                         node_delete_(node);
967                         chain->status = get_equivalent_status_(iterator->status);
968                         return false;
969                 }
970                 chain_append_node_(chain, node);
971         } while(FLAC__metadata_simple_iterator_next(iterator));
972
973         if(!iterator->is_last || iterator->status != FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK) {
974                 chain->status = get_equivalent_status_(iterator->status);
975                 return false;
976         }
977
978         chain->last_offset = ftell(iterator->file) + iterator->length;
979         FLAC__metadata_simple_iterator_delete(iterator);
980
981         chain->initial_length = chain_calculate_length_(chain);
982         return true;
983 }
984
985 FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats)
986 {
987         struct stat stats;
988         const char *tempfile_path_prefix = 0;
989         unsigned current_length;
990
991         FLAC__ASSERT(0 != chain);
992
993         current_length = chain_calculate_length_(chain);
994
995         if(use_padding) {
996                 if(current_length < chain->initial_length && chain->tail->data->type == FLAC__METADATA_TYPE_PADDING) {
997                         const unsigned delta = chain->initial_length - current_length;
998                         chain->tail->data->length += delta;
999                         current_length += delta;
1000                         FLAC__ASSERT(current_length == chain->initial_length);
1001                 }
1002                 else if(current_length + FLAC__STREAM_METADATA_HEADER_LENGTH <= chain->initial_length) {
1003                         FLAC__StreamMetadata *padding;
1004                         FLAC__Metadata_Node *node;
1005                         if(0 == (padding = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING))) {
1006                                 chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
1007                                 return false;
1008                         }
1009                         padding->length = chain->initial_length - (FLAC__STREAM_METADATA_HEADER_LENGTH + current_length);
1010                         if(0 == (node = node_new_())) {
1011                                 FLAC__metadata_object_delete(padding);
1012                                 chain->status = FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR;
1013                                 return false;
1014                         }
1015                         node->data = padding;
1016                         chain_append_node_(chain, node);
1017                         current_length = chain_calculate_length_(chain);
1018                         FLAC__ASSERT(current_length == chain->initial_length);
1019                 }
1020                 else if(current_length > chain->initial_length) {
1021                         const unsigned delta = current_length - chain->initial_length;
1022                         if(chain->tail->data->type == FLAC__METADATA_TYPE_PADDING) {
1023                                 if(chain->tail->data->length + FLAC__STREAM_METADATA_HEADER_LENGTH == delta) {
1024                                         chain_delete_node_(chain, chain->tail);
1025                                         current_length = chain_calculate_length_(chain);
1026                                         FLAC__ASSERT(current_length == chain->initial_length);
1027                                 }
1028                                 else if(chain->tail->data->length >= delta) {
1029                                         chain->tail->data->length -= delta;
1030                                         current_length -= delta;
1031                                         FLAC__ASSERT(current_length == chain->initial_length);
1032                                 }
1033                         }
1034                 }
1035         }
1036
1037         if(preserve_file_stats)
1038                 get_file_stats_(chain->filename, &stats);
1039
1040         if(current_length == chain->initial_length) {
1041                 if(!chain_rewrite_chain_(chain))
1042                         return false;
1043         }
1044         else {
1045                 if(!chain_rewrite_file_(chain, tempfile_path_prefix))
1046                         return false;
1047         }
1048
1049         if(preserve_file_stats)
1050                 set_file_stats_(chain->filename, &stats);
1051
1052         /* recompute lengths and offsets if necessary */
1053         if(chain->initial_length != current_length) {
1054                 const FLAC__Metadata_Node *node;
1055                 chain->initial_length = current_length;
1056                 chain->last_offset = chain->first_offset;
1057                 for(node = chain->head; node; node = node->next)
1058                         chain->last_offset += (FLAC__STREAM_METADATA_HEADER_LENGTH + node->data->length);
1059         }
1060
1061         return true;
1062 }
1063
1064 FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain)
1065 {
1066         FLAC__Metadata_Node *node;
1067
1068         FLAC__ASSERT(0 != chain);
1069
1070         for(node = chain->head; node; ) {
1071                 if(!chain_merge_adjacent_padding_(chain, node))
1072                         node = node->next;
1073         }
1074 }
1075
1076 FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain)
1077 {
1078         FLAC__Metadata_Node *node, *save;
1079         unsigned i;
1080
1081         FLAC__ASSERT(0 != chain);
1082
1083         /*
1084          * Don't try and be too smart... this simple algo is good enough for
1085          * the small number of nodes that we deal with.
1086          */
1087         for(i = 0, node = chain->head; i < chain->nodes; i++) {
1088                 if(node->data->type == FLAC__METADATA_TYPE_PADDING) {
1089                         save = node->next;
1090                         chain_remove_node_(chain, node);
1091                         chain_append_node_(chain, node);
1092                         node = save;
1093                 }
1094                 else {
1095                         node = node->next;
1096                 }
1097         }
1098
1099         FLAC__metadata_chain_merge_padding(chain);
1100 }
1101
1102
1103 FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new()
1104 {
1105         FLAC__Metadata_Iterator *iterator = malloc(sizeof(FLAC__Metadata_Iterator));
1106
1107         if(0 != iterator) {
1108                 iterator->current = 0;
1109                 iterator->chain = 0;
1110         }
1111
1112         return iterator;
1113 }
1114
1115 FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator)
1116 {
1117         FLAC__ASSERT(0 != iterator);
1118
1119         free(iterator);
1120 }
1121
1122 FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain)
1123 {
1124         FLAC__ASSERT(0 != iterator);
1125         FLAC__ASSERT(0 != chain);
1126         FLAC__ASSERT(0 != chain->head);
1127
1128         iterator->chain = chain;
1129         iterator->current = chain->head;
1130 }
1131
1132 FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator)
1133 {
1134         FLAC__ASSERT(0 != iterator);
1135
1136         if(0 == iterator->current || 0 == iterator->current->next)
1137                 return false;
1138
1139         iterator->current = iterator->current->next;
1140         return true;
1141 }
1142
1143 FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator)
1144 {
1145         FLAC__ASSERT(0 != iterator);
1146
1147         if(0 == iterator->current || 0 == iterator->current->prev)
1148                 return false;
1149
1150         iterator->current = iterator->current->prev;
1151         return true;
1152 }
1153
1154 FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator)
1155 {
1156         FLAC__ASSERT(0 != iterator);
1157         FLAC__ASSERT(0 != iterator->current);
1158         FLAC__ASSERT(0 != iterator->current->data);
1159
1160         return iterator->current->data->type;
1161 }
1162
1163 FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator)
1164 {
1165         FLAC__ASSERT(0 != iterator);
1166         FLAC__ASSERT(0 != iterator->current);
1167
1168         return iterator->current->data;
1169 }
1170
1171 FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block)
1172 {
1173         FLAC__ASSERT(0 != iterator);
1174         FLAC__ASSERT(0 != block);
1175         return FLAC__metadata_iterator_delete_block(iterator, false) && FLAC__metadata_iterator_insert_block_after(iterator, block);
1176 }
1177
1178 FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding)
1179 {
1180         FLAC__Metadata_Node *save;
1181
1182         FLAC__ASSERT(0 != iterator);
1183         FLAC__ASSERT(0 != iterator->current);
1184
1185         if(0 == iterator->current->prev) {
1186                 FLAC__ASSERT(iterator->current->data->type == FLAC__METADATA_TYPE_STREAMINFO);
1187                 return false;
1188         }
1189
1190         save = iterator->current->prev;
1191
1192         if(replace_with_padding) {
1193                 FLAC__metadata_object_delete_data(iterator->current->data);
1194                 iterator->current->data->type = FLAC__METADATA_TYPE_PADDING;
1195         }
1196         else {
1197                 chain_delete_node_(iterator->chain, iterator->current);
1198         }
1199
1200         iterator->current = save;
1201         return true;
1202 }
1203
1204 FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block)
1205 {
1206         FLAC__Metadata_Node *node;
1207
1208         FLAC__ASSERT(0 != iterator);
1209         FLAC__ASSERT(0 != iterator->current);
1210         FLAC__ASSERT(0 != block);
1211
1212         if(block->type == FLAC__METADATA_TYPE_STREAMINFO)
1213                 return false;
1214
1215         if(0 == iterator->current->prev) {
1216                 FLAC__ASSERT(iterator->current->data->type == FLAC__METADATA_TYPE_STREAMINFO);
1217                 return false;
1218         }
1219
1220         if(0 == (node = node_new_()))
1221                 return false;
1222
1223         node->data = block;
1224         iterator_insert_node_(iterator, node);
1225         iterator->current = node;
1226         return true;
1227 }
1228
1229 FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block)
1230 {
1231         FLAC__Metadata_Node *node;
1232
1233         FLAC__ASSERT(0 != iterator);
1234         FLAC__ASSERT(0 != iterator->current);
1235         FLAC__ASSERT(0 != block);
1236
1237         if(block->type == FLAC__METADATA_TYPE_STREAMINFO)
1238                 return false;
1239
1240         if(0 == (node = node_new_()))
1241                 return false;
1242
1243         node->data = block;
1244         iterator_insert_node_after_(iterator, node);
1245         iterator->current = node;
1246         return true;
1247 }
1248
1249
1250 /****************************************************************************
1251  *
1252  * Local function definitions
1253  *
1254  ***************************************************************************/
1255
1256 void pack_uint32_(FLAC__uint32 val, FLAC__byte *b, unsigned bytes)
1257 {
1258         unsigned i;
1259
1260         b += bytes;
1261
1262         for(i = 0; i < bytes; i++) {
1263                 *(--b) = (FLAC__byte)(val & 0xff);
1264                 val >>= 8;
1265         }
1266 }
1267
1268 void pack_uint32_little_endian_(FLAC__uint32 val, FLAC__byte *b, unsigned bytes)
1269 {
1270         unsigned i;
1271
1272         for(i = 0; i < bytes; i++) {
1273                 *(b++) = (FLAC__byte)(val & 0xff);
1274                 val >>= 8;
1275         }
1276 }
1277
1278 void pack_uint64_(FLAC__uint64 val, FLAC__byte *b, unsigned bytes)
1279 {
1280         unsigned i;
1281
1282         b += bytes;
1283
1284         for(i = 0; i < bytes; i++) {
1285                 *(--b) = (FLAC__byte)(val & 0xff);
1286                 val >>= 8;
1287         }
1288 }
1289
1290 FLAC__uint32 unpack_uint32_(FLAC__byte *b, unsigned bytes)
1291 {
1292         FLAC__uint32 ret = 0;
1293         unsigned i;
1294
1295         for(i = 0; i < bytes; i++)
1296                 ret = (ret << 8) | (FLAC__uint32)(*b++);
1297
1298         return ret;
1299 }
1300
1301 FLAC__uint32 unpack_uint32_little_endian_(FLAC__byte *b, unsigned bytes)
1302 {
1303         FLAC__uint32 ret = 0;
1304         unsigned i;
1305
1306         b += bytes;
1307
1308         for(i = 0; i < bytes; i++)
1309                 ret = (ret << 8) | (FLAC__uint32)(*--b);
1310
1311         return ret;
1312 }
1313
1314 FLAC__uint64 unpack_uint64_(FLAC__byte *b, unsigned bytes)
1315 {
1316         FLAC__uint64 ret = 0;
1317         unsigned i;
1318
1319         for(i = 0; i < bytes; i++)
1320                 ret = (ret << 8) | (FLAC__uint64)(*b++);
1321
1322         return ret;
1323 }
1324
1325 FLAC__bool read_metadata_block_header_(FLAC__Metadata_SimpleIterator *iterator)
1326 {
1327         FLAC__byte raw_header[FLAC__STREAM_METADATA_HEADER_LENGTH];
1328
1329         FLAC__ASSERT(0 != iterator);
1330         FLAC__ASSERT(0 != iterator->file);
1331
1332         if(fread(raw_header, 1, FLAC__STREAM_METADATA_HEADER_LENGTH, iterator->file) != FLAC__STREAM_METADATA_HEADER_LENGTH) {
1333                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
1334                 return false;
1335         }
1336
1337         iterator->is_last = raw_header[0] & 0x80? true : false;
1338         iterator->type = (FLAC__MetadataType)(raw_header[0] & 0x7f);
1339         iterator->length = unpack_uint32_(raw_header + 1, 3);
1340
1341         /* do some checking */
1342         if(iterator->type > FLAC__METADATA_TYPE_VORBIS_COMMENT) {
1343                 iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA;
1344                 return false;
1345         }
1346
1347         return true;
1348 }
1349
1350 FLAC__bool read_metadata_block_data_(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block)
1351 {
1352         FLAC__ASSERT(0 != iterator);
1353         FLAC__ASSERT(0 != iterator->file);
1354
1355         switch(block->type) {
1356                 case FLAC__METADATA_TYPE_STREAMINFO:
1357                         iterator->status = read_metadata_block_data_streaminfo_(iterator->file, &block->data.stream_info);
1358                         break;
1359                 case FLAC__METADATA_TYPE_PADDING:
1360                         iterator->status = read_metadata_block_data_padding_(iterator->file, &block->data.padding, block->length);
1361                         break;
1362                 case FLAC__METADATA_TYPE_APPLICATION:
1363                         iterator->status = read_metadata_block_data_application_(iterator->file, &block->data.application, block->length);
1364                         break;
1365                 case FLAC__METADATA_TYPE_SEEKTABLE:
1366                         iterator->status = read_metadata_block_data_seektable_(iterator->file, &block->data.seek_table, block->length);
1367                         break;
1368                 case FLAC__METADATA_TYPE_VORBIS_COMMENT:
1369                         iterator->status = read_metadata_block_data_vorbis_comment_(iterator->file, &block->data.vorbis_comment);
1370                         break;
1371                 default:
1372                         FLAC__ASSERT(0);
1373                         iterator->status = FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR;
1374         }
1375
1376         return (iterator->status == FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK);
1377 }
1378
1379 FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_streaminfo_(FILE *file, FLAC__StreamMetadata_StreamInfo *block)
1380 {
1381         FLAC__byte buffer[FLAC__STREAM_METADATA_STREAMINFO_LENGTH], *b;
1382
1383         FLAC__ASSERT(0 != file);
1384
1385         if(fread(buffer, 1, FLAC__STREAM_METADATA_STREAMINFO_LENGTH, file) != FLAC__STREAM_METADATA_STREAMINFO_LENGTH)
1386                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
1387
1388         b = buffer;
1389
1390         /* @@@ we are using hardcoded numbers for simplicity but we should
1391          * probably eventually write a bit-level unpacker and use the
1392          * _STREAMINFO_ constants.
1393          */
1394         block->min_blocksize = unpack_uint32_(b, 2); b += 2;
1395         block->max_blocksize = unpack_uint32_(b, 2); b += 2;
1396         block->min_framesize = unpack_uint32_(b, 3); b += 3;
1397         block->max_framesize = unpack_uint32_(b, 3); b += 3;
1398         block->sample_rate = (unpack_uint32_(b, 2) << 4) | ((unsigned)(b[2] & 0xf0) >> 4);
1399         block->channels = (unsigned)((b[2] & 0x0e) >> 1) + 1;
1400         block->bits_per_sample = ((((unsigned)(b[2] & 0x01)) << 4) | (((unsigned)(b[3] & 0xf0)) >> 4)) + 1;
1401         block->total_samples = (((FLAC__uint64)(b[3] & 0x0f)) << 32) | unpack_uint64_(b+4, 4);
1402         memcpy(block->md5sum, b+8, 16);
1403
1404         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
1405 }
1406
1407
1408 FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_padding_(FILE *file, FLAC__StreamMetadata_Padding *block, unsigned block_length)
1409 {
1410         FLAC__ASSERT(0 != file);
1411
1412         (void)block; /* nothing to do; we don't care about reading the padding bytes */
1413
1414         if(0 != fseek(file, block_length, SEEK_CUR))
1415                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR;
1416
1417         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
1418 }
1419
1420 FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_application_(FILE *file, FLAC__StreamMetadata_Application *block, unsigned block_length)
1421 {
1422         const unsigned id_bytes = FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8;
1423
1424         FLAC__ASSERT(0 != file);
1425
1426         if(fread(block->id, 1, id_bytes, file) != id_bytes)
1427                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
1428
1429         block_length -= id_bytes;
1430
1431         if(block_length == 0) {
1432                 block->data = 0;
1433         }
1434         else {
1435                 if(0 == (block->data = malloc(block_length)))
1436                         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
1437
1438                 if(fread(block->data, 1, block_length, file) != block_length)
1439                         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
1440         }
1441
1442         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
1443 }
1444
1445 FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_seektable_(FILE *file, FLAC__StreamMetadata_SeekTable *block, unsigned block_length)
1446 {
1447         unsigned i;
1448         FLAC__byte buffer[FLAC__STREAM_METADATA_SEEKPOINT_LENGTH];
1449
1450         FLAC__ASSERT(0 != file);
1451         FLAC__ASSERT(block_length % FLAC__STREAM_METADATA_SEEKPOINT_LENGTH == 0);
1452
1453         block->num_points = block_length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
1454
1455         if(block->num_points == 0)
1456                 block->points = 0;
1457         else if(0 == (block->points = malloc(block->num_points * sizeof(FLAC__StreamMetadata_SeekPoint))))
1458                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR;
1459
1460         for(i = 0; i < block->num_points; i++) {
1461                 if(fread(buffer, 1, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH, file) != FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)
1462                         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
1463                 /*@@@ some MAGIC NUMBERs here */
1464                 block->points[i].sample_number = unpack_uint64_(buffer, 8);
1465                 block->points[i].stream_offset = unpack_uint64_(buffer+8, 8);
1466                 block->points[i].frame_samples = unpack_uint32_(buffer+16, 2);
1467         }
1468
1469         return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK;
1470 }
1471
1472 FLAC__Metadata_SimpleIteratorStatus read_metadata_block_data_vorbis_comment_entry_(FILE *file, FLAC__StreamMetadata_VorbisComment_Entry *entry)
1473 {
1474         const unsigned entry_length_len = FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN / 8;
1475         FLAC__byte buffer[4]; /* magic number is asserted below */
1476
1477         FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN / 8 == 4);
1478         FLAC__ASSERT(0 != file);
1479
1480         if(fread(buffer, 1, entry_length_len, file) != entry_length_len)
1481                 return FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR;
1482         entry->length = unpack_uint32_little_endian_(buffer, entry_length_len);
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 = malloc(block->num_comments * sizeof(FLAC__StreamMetadata_VorbisComment_Entry))))
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 }