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