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