first twinges of replaygain support
[flac.git] / src / metaflac / main.c
1 /* metaflac - Command-line FLAC metadata editor
2  * Copyright (C) 2001,2002  Josh Coalson
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program 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
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
17  */
18
19 /*@@@
20 more powerful operations yet to add:
21         add a seektable, using same args as flac
22 */
23
24 #if HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include "FLAC/assert.h"
29 #include "FLAC/metadata.h"
30 #include "share/replaygain.h"
31 #include "share/utf8.h"
32 #include <ctype.h>
33 #include <locale.h>
34 #include <stdarg.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38
39 #if 0
40 /*[JEC] was:#if HAVE_GETOPT_LONG*/
41 /*[JEC] see flac/include/share/getopt.h as to why the change */
42 #  include <getopt.h>
43 #else
44 #  include "share/getopt.h"
45 #endif
46
47 /*
48    FLAC__share__getopt format struct; note we don't use short options so we just
49    set the 'val' field to 0 everywhere to indicate a valid option.
50 */
51 static struct FLAC__share__option long_options_[] = {
52         /* global options */
53         { "preserve-modtime", 0, 0, 0 },
54         { "with-filename", 0, 0, 0 },
55         { "no-filename", 0, 0, 0 },
56         { "no-utf8-convert", 0, 0, 0 },
57         { "dont-use-padding", 0, 0, 0 },
58         /* shorthand operations */
59         { "show-md5sum", 0, 0, 0 },
60         { "show-min-blocksize", 0, 0, 0 },
61         { "show-max-blocksize", 0, 0, 0 },
62         { "show-min-framesize", 0, 0, 0 },
63         { "show-max-framesize", 0, 0, 0 },
64         { "show-sample-rate", 0, 0, 0 },
65         { "show-channels", 0, 0, 0 },
66         { "show-bps", 0, 0, 0 },
67         { "show-total-samples", 0, 0, 0 },
68         { "set-md5sum", 1, 0, 0 }, /* undocumented */
69         { "set-min-blocksize", 1, 0, 0 }, /* undocumented */
70         { "set-max-blocksize", 1, 0, 0 }, /* undocumented */
71         { "set-min-framesize", 1, 0, 0 }, /* undocumented */
72         { "set-max-framesize", 1, 0, 0 }, /* undocumented */
73         { "set-sample-rate", 1, 0, 0 }, /* undocumented */
74         { "set-channels", 1, 0, 0 }, /* undocumented */
75         { "set-bps", 1, 0, 0 }, /* undocumented */
76         { "set-total-samples", 1, 0, 0 }, /* undocumented */
77         { "show-vc-vendor", 0, 0, 0 },
78         { "show-vc-field", 1, 0, 0 },
79         { "remove-vc-all", 0, 0, 0 },
80         { "remove-vc-field", 1, 0, 0 },
81         { "remove-vc-firstfield", 1, 0, 0 },
82         { "set-vc-field", 1, 0, 0 },
83         { "import-vc-from", 1, 0, 0 },
84         { "export-vc-to", 1, 0, 0 },
85         { "add-replay-gain", 0, 0, 0 },
86         { "add-padding", 1, 0, 0 },
87         /* major operations */
88         { "help", 0, 0, 0 },
89         { "version", 0, 0, 0 },
90         { "list", 0, 0, 0 },
91         { "append", 0, 0, 0 },
92         { "remove", 0, 0, 0 },
93         { "remove-all", 0, 0, 0 },
94         { "merge-padding", 0, 0, 0 },
95         { "sort-padding", 0, 0, 0 },
96         /* major operation arguments */
97         { "block-number", 1, 0, 0 },
98         { "block-type", 1, 0, 0 },
99         { "except-block-type", 1, 0, 0 },
100         { "data-format", 1, 0, 0 },
101         { "application-data-format", 1, 0, 0 },
102         { "from-file", 1, 0, 0 },
103         {0, 0, 0, 0}
104 };
105
106 typedef enum {
107         OP__SHOW_MD5SUM,
108         OP__SHOW_MIN_BLOCKSIZE,
109         OP__SHOW_MAX_BLOCKSIZE,
110         OP__SHOW_MIN_FRAMESIZE,
111         OP__SHOW_MAX_FRAMESIZE,
112         OP__SHOW_SAMPLE_RATE,
113         OP__SHOW_CHANNELS,
114         OP__SHOW_BPS,
115         OP__SHOW_TOTAL_SAMPLES,
116         OP__SET_MD5SUM,
117         OP__SET_MIN_BLOCKSIZE,
118         OP__SET_MAX_BLOCKSIZE,
119         OP__SET_MIN_FRAMESIZE,
120         OP__SET_MAX_FRAMESIZE,
121         OP__SET_SAMPLE_RATE,
122         OP__SET_CHANNELS,
123         OP__SET_BPS,
124         OP__SET_TOTAL_SAMPLES,
125         OP__SHOW_VC_VENDOR,
126         OP__SHOW_VC_FIELD,
127         OP__REMOVE_VC_ALL,
128         OP__REMOVE_VC_FIELD,
129         OP__REMOVE_VC_FIRSTFIELD,
130         OP__SET_VC_FIELD,
131         OP__IMPORT_VC_FROM,
132         OP__EXPORT_VC_TO,
133         OP__ADD_REPLAY_GAIN,
134         OP__ADD_PADDING,
135         OP__LIST,
136         OP__APPEND,
137         OP__REMOVE,
138         OP__REMOVE_ALL,
139         OP__MERGE_PADDING,
140         OP__SORT_PADDING
141 } OperationType;
142
143 typedef enum {
144         ARG__BLOCK_NUMBER,
145         ARG__BLOCK_TYPE,
146         ARG__EXCEPT_BLOCK_TYPE,
147         ARG__DATA_FORMAT,
148         ARG__FROM_FILE
149 } ArgumentType;
150
151 typedef struct {
152         FLAC__byte value[16];
153 } Argument_StreaminfoMD5;
154
155 typedef struct {
156         FLAC__uint32 value;
157 } Argument_StreaminfoUInt32;
158
159 typedef struct {
160         FLAC__uint64 value;
161 } Argument_StreaminfoUInt64;
162
163 typedef struct {
164         char *value;
165 } Argument_VcFieldName;
166
167 typedef struct {
168         char *field; /* the whole field as passed on the command line, i.e. "NAME=VALUE" */
169         char *field_name;
170         /* according to the vorbis spec, field values can contain \0 so simple C strings are not enough here */
171         unsigned field_value_length;
172         char *field_value;
173 } Argument_VcField;
174
175 typedef struct {
176         char *value;
177 } Argument_VcFilename;
178
179 typedef struct {
180         unsigned num_entries;
181         unsigned *entries;
182 } Argument_BlockNumber;
183
184 typedef struct {
185         FLAC__MetadataType type;
186         char application_id[4]; /* only relevant if type == FLAC__STREAM_METADATA_TYPE_APPLICATION */
187         FLAC__bool filter_application_by_id;
188 } Argument_BlockTypeEntry;
189
190 typedef struct {
191         unsigned num_entries;
192         Argument_BlockTypeEntry *entries;
193 } Argument_BlockType;
194
195 typedef struct {
196         FLAC__bool is_binary;
197 } Argument_DataFormat;
198
199 typedef struct {
200         char *file_name;
201 } Argument_FromFile;
202
203 typedef struct {
204         unsigned length;
205 } Argument_AddPadding;
206
207 typedef struct {
208         OperationType type;
209         union {
210                 Argument_StreaminfoMD5 streaminfo_md5;
211                 Argument_StreaminfoUInt32 streaminfo_uint32;
212                 Argument_StreaminfoUInt64 streaminfo_uint64;
213                 Argument_VcFieldName vc_field_name;
214                 Argument_VcField vc_field;
215                 Argument_VcFilename vc_filename;
216                 Argument_AddPadding add_padding;
217         } argument;
218 } Operation;
219
220 typedef struct {
221         ArgumentType type;
222         union {
223                 Argument_BlockNumber block_number;
224                 Argument_BlockType block_type;
225                 Argument_DataFormat data_format;
226                 Argument_FromFile from_file;
227         } value;
228 } Argument;
229
230 typedef struct {
231         FLAC__bool preserve_modtime;
232         FLAC__bool prefix_with_filename;
233         FLAC__bool utf8_convert;
234         FLAC__bool use_padding;
235         FLAC__bool show_long_help;
236         FLAC__bool show_version;
237         FLAC__bool application_data_format_is_hexdump;
238         struct {
239                 Operation *operations;
240                 unsigned num_operations;
241                 unsigned capacity;
242         } ops;
243         struct {
244                 struct {
245                         unsigned num_shorthand_ops;
246                         unsigned num_major_ops;
247                         FLAC__bool has_block_type;
248                         FLAC__bool has_except_block_type;
249                 } checks;
250                 Argument *arguments;
251                 unsigned num_arguments;
252                 unsigned capacity;
253         } args;
254         unsigned num_files;
255         char **filenames;
256 } CommandLineOptions;
257
258 static void die(const char *message);
259 static void init_options(CommandLineOptions *options);
260 static FLAC__bool parse_options(int argc, char *argv[], CommandLineOptions *options);
261 static FLAC__bool parse_option(int option_index, const char *option_argument, CommandLineOptions *options);
262 static void free_options(CommandLineOptions *options);
263 static void append_new_operation(CommandLineOptions *options, Operation operation);
264 static void append_new_argument(CommandLineOptions *options, Argument argument);
265 static Operation *append_major_operation(CommandLineOptions *options, OperationType type);
266 static Operation *append_shorthand_operation(CommandLineOptions *options, OperationType type);
267 static Argument *append_argument(CommandLineOptions *options, ArgumentType type);
268 static void show_version();
269 static int short_usage(const char *message, ...);
270 static int long_usage(const char *message, ...);
271 static char *local_strdup(const char *source);
272 static FLAC__bool parse_md5(const char *src, FLAC__byte dest[16]);
273 static FLAC__bool parse_uint32(const char *src, FLAC__uint32 *dest);
274 static FLAC__bool parse_uint64(const char *src, FLAC__uint64 *dest);
275 static FLAC__bool parse_filename(const char *src, char **dest);
276 static FLAC__bool parse_vorbis_comment_field(const char *field_ref, char **field, char **name, char **value, unsigned *length, const char **violation);
277 static FLAC__bool parse_vorbis_comment_field_name(const char *field_ref, char **name, const char **violation);
278 static FLAC__bool parse_add_padding(const char *in, unsigned *out);
279 static FLAC__bool parse_block_number(const char *in, Argument_BlockNumber *out);
280 static FLAC__bool parse_block_type(const char *in, Argument_BlockType *out);
281 static FLAC__bool parse_data_format(const char *in, Argument_DataFormat *out);
282 static FLAC__bool parse_application_data_format(const char *in, FLAC__bool *out);
283 static FLAC__bool do_operations(const CommandLineOptions *options);
284 static FLAC__bool do_major_operation(const CommandLineOptions *options);
285 static FLAC__bool do_major_operation_on_file(const char *filename, const CommandLineOptions *options);
286 static FLAC__bool do_major_operation__list(const char *filename, FLAC__Metadata_Chain *chain, const CommandLineOptions *options);
287 static FLAC__bool do_major_operation__append(FLAC__Metadata_Chain *chain, const CommandLineOptions *options);
288 static FLAC__bool do_major_operation__remove(FLAC__Metadata_Chain *chain, const CommandLineOptions *options);
289 static FLAC__bool do_major_operation__remove_all(FLAC__Metadata_Chain *chain, const CommandLineOptions *options);
290 static FLAC__bool do_shorthand_operations(const CommandLineOptions *options);
291 static FLAC__bool do_shorthand_operations_on_file(const char *filename, const CommandLineOptions *options);
292 static FLAC__bool do_shorthand_operation(const char *filename, FLAC__Metadata_Chain *chain, const Operation *operation, FLAC__bool *needs_write, FLAC__bool utf8_convert);
293 static FLAC__bool do_shorthand_operation__add_replay_gain(char **filenames, unsigned num_files);
294 static FLAC__bool do_replaygain_analyze_file(const char *filename, float *title_gain, float *title_peak);
295 static FLAC__bool do_replaygain_store_to_file(const char *filename, float album_gain, float album_peak, float title_gain, float title_peak);
296 static FLAC__bool do_shorthand_operation__add_padding(const char *filename, FLAC__Metadata_Chain *chain, unsigned length, FLAC__bool *needs_write);
297 static FLAC__bool do_shorthand_operation__streaminfo(const char *filename, FLAC__Metadata_Chain *chain, const Operation *operation, FLAC__bool *needs_write);
298 static FLAC__bool do_shorthand_operation__vorbis_comment(const char *filename, FLAC__Metadata_Chain *chain, const Operation *operation, FLAC__bool *needs_write, FLAC__bool raw);
299 static FLAC__bool passes_filter(const CommandLineOptions *options, const FLAC__StreamMetadata *block, unsigned block_number);
300 static void write_metadata(const char *filename, FLAC__StreamMetadata *block, unsigned block_number, FLAC__bool raw, FLAC__bool hexdump_application);
301 static void write_vc_field(const char *filename, const FLAC__StreamMetadata_VorbisComment_Entry *entry, FLAC__bool raw, FILE *f);
302 static void write_vc_fields(const char *filename, const char *field_name, const FLAC__StreamMetadata_VorbisComment_Entry entry[], unsigned num_entries, FLAC__bool raw, FILE *f);
303 static FLAC__bool remove_vc_all(const char *filename, FLAC__StreamMetadata *block, FLAC__bool *needs_write);
304 static FLAC__bool remove_vc_field(FLAC__StreamMetadata *block, const char *field_name, FLAC__bool *needs_write);
305 static FLAC__bool remove_vc_firstfield(const char *filename, FLAC__StreamMetadata *block, const char *field_name, FLAC__bool *needs_write);
306 static FLAC__bool set_vc_field(const char *filename, FLAC__StreamMetadata *block, const Argument_VcField *field, FLAC__bool *needs_write, FLAC__bool raw);
307 static FLAC__bool import_vc_from(const char *filename, FLAC__StreamMetadata *block, const Argument_VcFilename *vc_filename, FLAC__bool *needs_write, FLAC__bool raw);
308 static FLAC__bool export_vc_to(const char *filename, FLAC__StreamMetadata *block, const Argument_VcFilename *vc_filename, FLAC__bool raw);
309 static FLAC__bool field_name_matches_entry(const char *field_name, unsigned field_name_length, const FLAC__StreamMetadata_VorbisComment_Entry *entry);
310 static void hexdump(const char *filename, const FLAC__byte *buf, unsigned bytes, const char *indent);
311 static void undocumented_warning(const char *opt);
312
313 int main(int argc, char *argv[])
314 {
315         CommandLineOptions options;
316         int ret = 0;
317
318         setlocale(LC_ALL, "");
319         init_options(&options);
320
321         if(parse_options(argc, argv, &options))
322                 ret = !do_operations(&options);
323
324         free_options(&options);
325
326         return ret;
327 }
328
329 void die(const char *message)
330 {
331         FLAC__ASSERT(0 != message);
332         fprintf(stderr, "ERROR: %s\n", message);
333         exit(1);
334 }
335
336 void init_options(CommandLineOptions *options)
337 {
338         options->preserve_modtime = false;
339
340         /* '2' is a hack to mean "use default if not forced on command line" */
341         FLAC__ASSERT(true != 2);
342         options->prefix_with_filename = 2;
343
344         options->utf8_convert = true;
345         options->use_padding = true;
346         options->show_long_help = false;
347         options->show_version = false;
348         options->application_data_format_is_hexdump = false;
349
350         options->ops.operations = 0;
351         options->ops.num_operations = 0;
352         options->ops.capacity = 0;
353
354         options->args.arguments = 0;
355         options->args.num_arguments = 0;
356         options->args.capacity = 0;
357
358         options->args.checks.num_shorthand_ops = 0;
359         options->args.checks.num_major_ops = 0;
360         options->args.checks.has_block_type = false;
361         options->args.checks.has_except_block_type = false;
362
363         options->num_files = 0;
364         options->filenames = 0;
365 }
366
367 FLAC__bool parse_options(int argc, char *argv[], CommandLineOptions *options)
368 {
369         int ret;
370         int option_index = 1;
371         FLAC__bool had_error = false;
372
373         while ((ret = FLAC__share__getopt_long(argc, argv, "", long_options_, &option_index)) != -1) {
374                 switch (ret) {
375                         case 0:
376                                 had_error |= !parse_option(option_index, FLAC__share__optarg, options);
377                                 break;
378                         case '?':
379                         case ':':
380                                 had_error = true;
381                                 break;
382                         default:
383                                 FLAC__ASSERT(0);
384                                 break;
385                 }
386         }
387
388         if(options->prefix_with_filename == 2)
389                 options->prefix_with_filename = (argc - FLAC__share__optind > 1);
390
391         if(FLAC__share__optind >= argc && !options->show_long_help && !options->show_version) {
392                 fprintf(stderr,"ERROR: you must specify at least one FLAC file;\n");
393                 fprintf(stderr,"       metaflac cannot be used as a pipe\n");
394                 had_error = true;
395         }
396
397         options->num_files = argc - FLAC__share__optind;
398
399         if(options->num_files > 0) {
400                 unsigned i = 0;
401                 if(0 == (options->filenames = malloc(sizeof(char *) * options->num_files)))
402                         die("out of memory allocating space for file names list");
403                 while(FLAC__share__optind < argc)
404                         options->filenames[i++] = local_strdup(argv[FLAC__share__optind++]);
405         }
406
407         if(options->args.checks.num_major_ops > 0) {
408                 if(options->args.checks.num_major_ops > 1) {
409                         fprintf(stderr, "ERROR: you may only specify one major operation at a time\n");
410                         had_error = true;
411                 }
412                 else if(options->args.checks.num_shorthand_ops > 0) {
413                         fprintf(stderr, "ERROR: you may not mix shorthand and major operations\n");
414                         had_error = true;
415                 }
416         }
417
418         if(options->args.checks.has_block_type && options->args.checks.has_except_block_type) {
419                 fprintf(stderr, "ERROR: you may not specify both '--block-type' and '--except-block-type'\n");
420                 had_error = true;
421         }
422
423         if(had_error)
424                 short_usage(0);
425
426         return !had_error;
427 }
428
429 FLAC__bool parse_option(int option_index, const char *option_argument, CommandLineOptions *options)
430 {
431         const char *opt = long_options_[option_index].name;
432         Operation *op;
433         Argument *arg;
434         FLAC__bool ok = true;
435
436         if(0 == strcmp(opt, "preserve-modtime")) {
437                 options->preserve_modtime = true;
438         }
439         else if(0 == strcmp(opt, "with-filename")) {
440                 options->prefix_with_filename = true;
441         }
442         else if(0 == strcmp(opt, "no-filename")) {
443                 options->prefix_with_filename = false;
444         }
445         else if(0 == strcmp(opt, "no-utf8-convert")) {
446                 options->utf8_convert = false;
447         }
448         else if(0 == strcmp(opt, "dont-use-padding")) {
449                 options->use_padding = false;
450         }
451         else if(0 == strcmp(opt, "show-md5sum")) {
452                 (void) append_shorthand_operation(options, OP__SHOW_MD5SUM);
453         }
454         else if(0 == strcmp(opt, "show-min-blocksize")) {
455                 (void) append_shorthand_operation(options, OP__SHOW_MIN_BLOCKSIZE);
456         }
457         else if(0 == strcmp(opt, "show-max-blocksize")) {
458                 (void) append_shorthand_operation(options, OP__SHOW_MAX_BLOCKSIZE);
459         }
460         else if(0 == strcmp(opt, "show-min-framesize")) {
461                 (void) append_shorthand_operation(options, OP__SHOW_MIN_FRAMESIZE);
462         }
463         else if(0 == strcmp(opt, "show-max-framesize")) {
464                 (void) append_shorthand_operation(options, OP__SHOW_MAX_FRAMESIZE);
465         }
466         else if(0 == strcmp(opt, "show-sample-rate")) {
467                 (void) append_shorthand_operation(options, OP__SHOW_SAMPLE_RATE);
468         }
469         else if(0 == strcmp(opt, "show-channels")) {
470                 (void) append_shorthand_operation(options, OP__SHOW_CHANNELS);
471         }
472         else if(0 == strcmp(opt, "show-bps")) {
473                 (void) append_shorthand_operation(options, OP__SHOW_BPS);
474         }
475         else if(0 == strcmp(opt, "show-total-samples")) {
476                 (void) append_shorthand_operation(options, OP__SHOW_TOTAL_SAMPLES);
477         }
478         else if(0 == strcmp(opt, "set-md5sum")) {
479                 op = append_shorthand_operation(options, OP__SET_MD5SUM);
480                 FLAC__ASSERT(0 != option_argument);
481                 if(!parse_md5(option_argument, op->argument.streaminfo_md5.value)) {
482                         fprintf(stderr, "ERROR (--%s): bad MD5 sum\n", opt);
483                         ok = false;
484                 }
485                 else
486                         undocumented_warning(opt);
487         }
488         else if(0 == strcmp(opt, "set-min-blocksize")) {
489                 op = append_shorthand_operation(options, OP__SET_MIN_BLOCKSIZE);
490                 if(!parse_uint32(option_argument, &(op->argument.streaminfo_uint32.value)) || op->argument.streaminfo_uint32.value < FLAC__MIN_BLOCK_SIZE || op->argument.streaminfo_uint32.value > FLAC__MAX_BLOCK_SIZE) {
491                         fprintf(stderr, "ERROR (--%s): value must be >= %u and <= %u\n", opt, FLAC__MIN_BLOCK_SIZE, FLAC__MAX_BLOCK_SIZE);
492                         ok = false;
493                 }
494                 else
495                         undocumented_warning(opt);
496         }
497         else if(0 == strcmp(opt, "set-max-blocksize")) {
498                 op = append_shorthand_operation(options, OP__SET_MAX_BLOCKSIZE);
499                 if(!parse_uint32(option_argument, &(op->argument.streaminfo_uint32.value)) || op->argument.streaminfo_uint32.value < FLAC__MIN_BLOCK_SIZE || op->argument.streaminfo_uint32.value > FLAC__MAX_BLOCK_SIZE) {
500                         fprintf(stderr, "ERROR (--%s): value must be >= %u and <= %u\n", opt, FLAC__MIN_BLOCK_SIZE, FLAC__MAX_BLOCK_SIZE);
501                         ok = false;
502                 }
503                 else
504                         undocumented_warning(opt);
505         }
506         else if(0 == strcmp(opt, "set-min-framesize")) {
507                 op = append_shorthand_operation(options, OP__SET_MIN_FRAMESIZE);
508                 if(!parse_uint32(option_argument, &(op->argument.streaminfo_uint32.value)) || op->argument.streaminfo_uint32.value >= (1u<<FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN)) {
509                         fprintf(stderr, "ERROR (--%s): value must be a %u-bit unsigned integer\n", opt, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN);
510                         ok = false;
511                 }
512                 else
513                         undocumented_warning(opt);
514         }
515         else if(0 == strcmp(opt, "set-max-framesize")) {
516                 op = append_shorthand_operation(options, OP__SET_MAX_FRAMESIZE);
517                 if(!parse_uint32(option_argument, &(op->argument.streaminfo_uint32.value)) || op->argument.streaminfo_uint32.value >= (1u<<FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN)) {
518                         fprintf(stderr, "ERROR (--%s): value must be a %u-bit unsigned integer\n", opt, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN);
519                         ok = false;
520                 }
521                 else
522                         undocumented_warning(opt);
523         }
524         else if(0 == strcmp(opt, "set-sample-rate")) {
525                 op = append_shorthand_operation(options, OP__SET_SAMPLE_RATE);
526                 if(!parse_uint32(option_argument, &(op->argument.streaminfo_uint32.value)) || !FLAC__format_sample_rate_is_valid(op->argument.streaminfo_uint32.value)) {
527                         fprintf(stderr, "ERROR (--%s): invalid sample rate\n", opt);
528                         ok = false;
529                 }
530                 else
531                         undocumented_warning(opt);
532         }
533         else if(0 == strcmp(opt, "set-channels")) {
534                 op = append_shorthand_operation(options, OP__SET_CHANNELS);
535                 if(!parse_uint32(option_argument, &(op->argument.streaminfo_uint32.value)) || op->argument.streaminfo_uint32.value > FLAC__MAX_CHANNELS) {
536                         fprintf(stderr, "ERROR (--%s): value must be > 0 and <= %u\n", opt, FLAC__MAX_CHANNELS);
537                         ok = false;
538                 }
539                 else
540                         undocumented_warning(opt);
541         }
542         else if(0 == strcmp(opt, "set-bps")) {
543                 op = append_shorthand_operation(options, OP__SET_BPS);
544                 if(!parse_uint32(option_argument, &(op->argument.streaminfo_uint32.value)) || op->argument.streaminfo_uint32.value < FLAC__MIN_BITS_PER_SAMPLE || op->argument.streaminfo_uint32.value > FLAC__MAX_BITS_PER_SAMPLE) {
545                         fprintf(stderr, "ERROR (--%s): value must be >= %u and <= %u\n", opt, FLAC__MIN_BITS_PER_SAMPLE, FLAC__MAX_BITS_PER_SAMPLE);
546                         ok = false;
547                 }
548                 else
549                         undocumented_warning(opt);
550         }
551         else if(0 == strcmp(opt, "set-total-samples")) {
552                 op = append_shorthand_operation(options, OP__SET_TOTAL_SAMPLES);
553                 if(!parse_uint64(option_argument, &(op->argument.streaminfo_uint64.value)) || op->argument.streaminfo_uint64.value >= (1u<<FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN)) {
554                         fprintf(stderr, "ERROR (--%s): value must be a %u-bit unsigned integer\n", opt, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN);
555                         ok = false;
556                 }
557                 else
558                         undocumented_warning(opt);
559         }
560         else if(0 == strcmp(opt, "show-vc-vendor")) {
561                 (void) append_shorthand_operation(options, OP__SHOW_VC_VENDOR);
562         }
563         else if(0 == strcmp(opt, "show-vc-field")) {
564                 const char *violation;
565                 op = append_shorthand_operation(options, OP__SHOW_VC_FIELD);
566                 FLAC__ASSERT(0 != option_argument);
567                 if(!parse_vorbis_comment_field_name(option_argument, &(op->argument.vc_field_name.value), &violation)) {
568                         FLAC__ASSERT(0 != violation);
569                         fprintf(stderr, "ERROR (--%s): malformed vorbis comment field name \"%s\",\n       %s\n", opt, option_argument, violation);
570                         ok = false;
571                 }
572         }
573         else if(0 == strcmp(opt, "remove-vc-all")) {
574                 (void) append_shorthand_operation(options, OP__REMOVE_VC_ALL);
575         }
576         else if(0 == strcmp(opt, "remove-vc-field")) {
577                 const char *violation;
578                 op = append_shorthand_operation(options, OP__REMOVE_VC_FIELD);
579                 FLAC__ASSERT(0 != option_argument);
580                 if(!parse_vorbis_comment_field_name(option_argument, &(op->argument.vc_field_name.value), &violation)) {
581                         FLAC__ASSERT(0 != violation);
582                         fprintf(stderr, "ERROR (--%s): malformed vorbis comment field name \"%s\",\n       %s\n", opt, option_argument, violation);
583                         ok = false;
584                 }
585         }
586         else if(0 == strcmp(opt, "remove-vc-firstfield")) {
587                 const char *violation;
588                 op = append_shorthand_operation(options, OP__REMOVE_VC_FIRSTFIELD);
589                 FLAC__ASSERT(0 != option_argument);
590                 if(!parse_vorbis_comment_field_name(option_argument, &(op->argument.vc_field_name.value), &violation)) {
591                         FLAC__ASSERT(0 != violation);
592                         fprintf(stderr, "ERROR (--%s): malformed vorbis comment field name \"%s\",\n       %s\n", opt, option_argument, violation);
593                         ok = false;
594                 }
595         }
596         else if(0 == strcmp(opt, "set-vc-field")) {
597                 const char *violation;
598                 op = append_shorthand_operation(options, OP__SET_VC_FIELD);
599                 FLAC__ASSERT(0 != option_argument);
600                 if(!parse_vorbis_comment_field(option_argument, &(op->argument.vc_field.field), &(op->argument.vc_field.field_name), &(op->argument.vc_field.field_value), &(op->argument.vc_field.field_value_length), &violation)) {
601                         FLAC__ASSERT(0 != violation);
602                         fprintf(stderr, "ERROR (--%s): malformed vorbis comment field \"%s\",\n       %s\n", opt, option_argument, violation);
603                         ok = false;
604                 }
605         }
606         else if(0 == strcmp(opt, "import-vc-from")) {
607                 op = append_shorthand_operation(options, OP__IMPORT_VC_FROM);
608                 FLAC__ASSERT(0 != option_argument);
609                 if(!parse_filename(option_argument, &(op->argument.vc_filename.value))) {
610                         fprintf(stderr, "ERROR (--%s): missing filename\n", opt);
611                         ok = false;
612                 }
613         }
614         else if(0 == strcmp(opt, "export-vc-to")) {
615                 op = append_shorthand_operation(options, OP__EXPORT_VC_TO);
616                 FLAC__ASSERT(0 != option_argument);
617                 if(!parse_filename(option_argument, &(op->argument.vc_filename.value))) {
618                         fprintf(stderr, "ERROR (--%s): missing filename\n", opt);
619                         ok = false;
620                 }
621         }
622         else if(0 == strcmp(opt, "add-replay-gain")) {
623                 (void) append_shorthand_operation(options, OP__ADD_REPLAY_GAIN);
624         }
625         else if(0 == strcmp(opt, "add-padding")) {
626                 op = append_shorthand_operation(options, OP__ADD_PADDING);
627                 FLAC__ASSERT(0 != option_argument);
628                 if(!parse_add_padding(option_argument, &(op->argument.add_padding.length))) {
629                         fprintf(stderr, "ERROR (--%s): illegal length \"%s\", length must be >= 0 and < 2^%u\n", opt, option_argument, FLAC__STREAM_METADATA_LENGTH_LEN);
630                         ok = false;
631                 }
632         }
633         else if(0 == strcmp(opt, "help")) {
634                 options->show_long_help = true;
635         }
636         else if(0 == strcmp(opt, "version")) {
637                 options->show_version = true;
638         }
639         else if(0 == strcmp(opt, "list")) {
640                 (void) append_major_operation(options, OP__LIST);
641         }
642         else if(0 == strcmp(opt, "append")) {
643                 (void) append_major_operation(options, OP__APPEND);
644         }
645         else if(0 == strcmp(opt, "remove")) {
646                 (void) append_major_operation(options, OP__REMOVE);
647         }
648         else if(0 == strcmp(opt, "remove-all")) {
649                 (void) append_major_operation(options, OP__REMOVE_ALL);
650         }
651         else if(0 == strcmp(opt, "merge-padding")) {
652                 (void) append_major_operation(options, OP__MERGE_PADDING);
653         }
654         else if(0 == strcmp(opt, "sort-padding")) {
655                 (void) append_major_operation(options, OP__SORT_PADDING);
656         }
657         else if(0 == strcmp(opt, "block-number")) {
658                 arg = append_argument(options, ARG__BLOCK_NUMBER);
659                 FLAC__ASSERT(0 != option_argument);
660                 if(!parse_block_number(option_argument, &(arg->value.block_number))) {
661                         fprintf(stderr, "ERROR: malformed block number specification \"%s\"\n", option_argument);
662                         ok = false;
663                 }
664         }
665         else if(0 == strcmp(opt, "block-type")) {
666                 arg = append_argument(options, ARG__BLOCK_TYPE);
667                 FLAC__ASSERT(0 != option_argument);
668                 if(!parse_block_type(option_argument, &(arg->value.block_type))) {
669                         fprintf(stderr, "ERROR (--%s): malformed block type specification \"%s\"\n", opt, option_argument);
670                         ok = false;
671                 }
672                 options->args.checks.has_block_type = true;
673         }
674         else if(0 == strcmp(opt, "except-block-type")) {
675                 arg = append_argument(options, ARG__EXCEPT_BLOCK_TYPE);
676                 FLAC__ASSERT(0 != option_argument);
677                 if(!parse_block_type(option_argument, &(arg->value.block_type))) {
678                         fprintf(stderr, "ERROR (--%s): malformed block type specification \"%s\"\n", opt, option_argument);
679                         ok = false;
680                 }
681                 options->args.checks.has_except_block_type = true;
682         }
683         else if(0 == strcmp(opt, "data-format")) {
684                 arg = append_argument(options, ARG__DATA_FORMAT);
685                 FLAC__ASSERT(0 != option_argument);
686                 if(!parse_data_format(option_argument, &(arg->value.data_format))) {
687                         fprintf(stderr, "ERROR (--%s): illegal data format \"%s\"\n", opt, option_argument);
688                         ok = false;
689                 }
690         }
691         else if(0 == strcmp(opt, "application-data-format")) {
692                 FLAC__ASSERT(0 != option_argument);
693                 if(!parse_application_data_format(option_argument, &(options->application_data_format_is_hexdump))) {
694                         fprintf(stderr, "ERROR (--%s): illegal application data format \"%s\"\n", opt, option_argument);
695                         ok = false;
696                 }
697         }
698         else if(0 == strcmp(opt, "from-file")) {
699                 arg = append_argument(options, ARG__FROM_FILE);
700                 FLAC__ASSERT(0 != option_argument);
701                 arg->value.from_file.file_name = local_strdup(option_argument);
702         }
703         else {
704                 FLAC__ASSERT(0);
705         }
706
707         return ok;
708 }
709
710 void free_options(CommandLineOptions *options)
711 {
712         unsigned i;
713         Operation *op;
714         Argument *arg;
715
716         FLAC__ASSERT(0 == options->ops.operations || options->ops.num_operations > 0);
717         FLAC__ASSERT(0 == options->args.arguments || options->args.num_arguments > 0);
718
719         for(i = 0, op = options->ops.operations; i < options->ops.num_operations; i++, op++) {
720                 switch(op->type) {
721                         case OP__SHOW_VC_FIELD:
722                         case OP__REMOVE_VC_FIELD:
723                         case OP__REMOVE_VC_FIRSTFIELD:
724                                 if(0 != op->argument.vc_field_name.value)
725                                         free(op->argument.vc_field_name.value);
726                                 break;
727                         case OP__SET_VC_FIELD:
728                                 if(0 != op->argument.vc_field.field)
729                                         free(op->argument.vc_field.field);
730                                 if(0 != op->argument.vc_field.field_name)
731                                         free(op->argument.vc_field.field_name);
732                                 if(0 != op->argument.vc_field.field_value)
733                                         free(op->argument.vc_field.field_value);
734                                 break;
735                         case OP__IMPORT_VC_FROM:
736                         case OP__EXPORT_VC_TO:
737                                 if(0 != op->argument.vc_filename.value)
738                                         free(op->argument.vc_filename.value);
739                                 break;
740                         default:
741                                 break;
742                 }
743         }
744
745         for(i = 0, arg = options->args.arguments; i < options->args.num_arguments; i++, arg++) {
746                 switch(arg->type) {
747                         case ARG__BLOCK_NUMBER:
748                                 if(0 != arg->value.block_number.entries)
749                                         free(arg->value.block_number.entries);
750                                 break;
751                         case ARG__BLOCK_TYPE:
752                         case ARG__EXCEPT_BLOCK_TYPE:
753                                 if(0 != arg->value.block_type.entries)
754                                         free(arg->value.block_type.entries);
755                                 break;
756                         case ARG__FROM_FILE:
757                                 if(0 != arg->value.from_file.file_name)
758                                         free(arg->value.from_file.file_name);
759                                 break;
760                         default:
761                                 break;
762                 }
763         }
764
765         if(0 != options->ops.operations)
766                 free(options->ops.operations);
767
768         if(0 != options->args.arguments)
769                 free(options->args.arguments);
770
771         if(0 != options->filenames)
772                 free(options->filenames);
773 }
774
775 void append_new_operation(CommandLineOptions *options, Operation operation)
776 {
777         if(options->ops.capacity == 0) {
778                 options->ops.capacity = 50;
779                 if(0 == (options->ops.operations = malloc(sizeof(Operation) * options->ops.capacity)))
780                         die("out of memory allocating space for option list");
781                 memset(options->ops.operations, 0, sizeof(Operation) * options->ops.capacity);
782         }
783         if(options->ops.capacity <= options->ops.num_operations) {
784                 unsigned original_capacity = options->ops.capacity;
785                 options->ops.capacity *= 4;
786                 if(0 == (options->ops.operations = realloc(options->ops.operations, sizeof(Operation) * options->ops.capacity)))
787                         die("out of memory allocating space for option list");
788                 memset(options->ops.operations + original_capacity, 0, sizeof(Operation) * (options->ops.capacity - original_capacity));
789         }
790
791         options->ops.operations[options->ops.num_operations++] = operation;
792 }
793
794 void append_new_argument(CommandLineOptions *options, Argument argument)
795 {
796         if(options->args.capacity == 0) {
797                 options->args.capacity = 50;
798                 if(0 == (options->args.arguments = malloc(sizeof(Argument) * options->args.capacity)))
799                         die("out of memory allocating space for option list");
800                 memset(options->args.arguments, 0, sizeof(Argument) * options->args.capacity);
801         }
802         if(options->args.capacity <= options->args.num_arguments) {
803                 unsigned original_capacity = options->args.capacity;
804                 options->args.capacity *= 4;
805                 if(0 == (options->args.arguments = realloc(options->args.arguments, sizeof(Argument) * options->args.capacity)))
806                         die("out of memory allocating space for option list");
807                 memset(options->args.arguments + original_capacity, 0, sizeof(Argument) * (options->args.capacity - original_capacity));
808         }
809
810         options->args.arguments[options->args.num_arguments++] = argument;
811 }
812
813 Operation *append_major_operation(CommandLineOptions *options, OperationType type)
814 {
815         Operation op;
816         memset(&op, 0, sizeof(op));
817         op.type = type;
818         append_new_operation(options, op);
819         options->args.checks.num_major_ops++;
820         return options->ops.operations + (options->ops.num_operations - 1);
821 }
822
823 Operation *append_shorthand_operation(CommandLineOptions *options, OperationType type)
824 {
825         Operation op;
826         memset(&op, 0, sizeof(op));
827         op.type = type;
828         append_new_operation(options, op);
829         options->args.checks.num_shorthand_ops++;
830         return options->ops.operations + (options->ops.num_operations - 1);
831 }
832
833 Argument *append_argument(CommandLineOptions *options, ArgumentType type)
834 {
835         Argument arg;
836         memset(&arg, 0, sizeof(arg));
837         arg.type = type;
838         append_new_argument(options, arg);
839         return options->args.arguments + (options->args.num_arguments - 1);
840 }
841
842 void show_version()
843 {
844         printf("metaflac %s\n", FLAC__VERSION_STRING);
845 }
846
847 static void usage_header(FILE *out)
848 {
849         fprintf(out, "==============================================================================\n");
850         fprintf(out, "metaflac - Command-line FLAC metadata editor version %s\n", FLAC__VERSION_STRING);
851         fprintf(out, "Copyright (C) 2001,2002  Josh Coalson\n");
852         fprintf(out, "\n");
853         fprintf(out, "This program is free software; you can redistribute it and/or\n");
854         fprintf(out, "modify it under the terms of the GNU General Public License\n");
855         fprintf(out, "as published by the Free Software Foundation; either version 2\n");
856         fprintf(out, "of the License, or (at your option) any later version.\n");
857         fprintf(out, "\n");
858         fprintf(out, "This program is distributed in the hope that it will be useful,\n");
859         fprintf(out, "but WITHOUT ANY WARRANTY; without even the implied warranty of\n");
860         fprintf(out, "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n");
861         fprintf(out, "GNU General Public License for more details.\n");
862         fprintf(out, "\n");
863         fprintf(out, "You should have received a copy of the GNU General Public License\n");
864         fprintf(out, "along with this program; if not, write to the Free Software\n");
865         fprintf(out, "Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.\n");
866         fprintf(out, "==============================================================================\n");
867 }
868
869 static void usage_summary(FILE *out)
870 {
871         fprintf(out, "Usage:\n");
872         fprintf(out, "  metaflac [options] [operations] FLACfile [FLACfile ...]\n");
873         fprintf(out, "\n");
874         fprintf(out, "Use metaflac to list, add, remove, or edit metadata in one or more FLAC files.\n");
875         fprintf(out, "You may perform one major operation, or many shorthand operations at a time.\n");
876         fprintf(out, "\n");
877         fprintf(out, "Options:\n");
878         fprintf(out, "--preserve-modtime    Preserve the original modification time in spite of edits\n");
879         fprintf(out, "--with-filename       Prefix each output line with the FLAC file name\n");
880         fprintf(out, "                      (the default if more than one FLAC file is specified)\n");
881         fprintf(out, "--no-filename         Do not prefix each output line with the FLAC file name\n");
882         fprintf(out, "                      (the default if only one FLAC file is specified)\n");
883         fprintf(out, "--no-utf8-convert     Do not convert Vorbis comments from UTF-8 to local charset,\n");
884         fprintf(out, "                      or vice versa.  This is useful for scripts.\n");
885         fprintf(out, "--dont-use-padding    By default metaflac tries to use padding where possible\n");
886         fprintf(out, "                      to avoid rewriting the entire file if the metadata size\n");
887         fprintf(out, "                      changes.  Use this option to tell metaflac to not take\n");
888         fprintf(out, "                      advantage of padding this way.\n");
889 }
890
891 int short_usage(const char *message, ...)
892 {
893         va_list args;
894
895         if(message) {
896                 va_start(args, message);
897
898                 (void) vfprintf(stderr, message, args);
899
900                 va_end(args);
901
902         }
903         usage_header(stderr);
904         fprintf(stderr, "\n");
905         fprintf(stderr, "This is the short help; for full help use 'metaflac --help'\n");
906         fprintf(stderr, "\n");
907         usage_summary(stderr);
908
909         return message? 1 : 0;
910 }
911
912 int long_usage(const char *message, ...)
913 {
914         FILE *out = (message? stderr : stdout);
915         va_list args;
916
917         if(message) {
918                 va_start(args, message);
919
920                 (void) vfprintf(stderr, message, args);
921
922                 va_end(args);
923
924         }
925         usage_header(out);
926         fprintf(out, "\n");
927         usage_summary(out);
928         fprintf(out, "\n");
929         fprintf(out, "Shorthand operations:\n");
930         fprintf(out, "--show-md5sum         Show the MD5 signature from the STREAMINFO block.\n");
931         fprintf(out, "--show-min-blocksize  Show the minimum block size from the STREAMINFO block.\n");
932         fprintf(out, "--show-max-blocksize  Show the maximum block size from the STREAMINFO block.\n");
933         fprintf(out, "--show-min-framesize  Show the minimum frame size from the STREAMINFO block.\n");
934         fprintf(out, "--show-max-framesize  Show the maximum frame size from the STREAMINFO block.\n");
935         fprintf(out, "--show-sample-rate    Show the sample rate from the STREAMINFO block.\n");
936         fprintf(out, "--show-channels       Show the number of channels from the STREAMINFO block.\n");
937         fprintf(out, "--show-bps            Show the # of bits per sample from the STREAMINFO block.\n");
938         fprintf(out, "--show-total-samples  Show the total # of samples from the STREAMINFO block.\n");
939         fprintf(out, "\n");
940         fprintf(out, "--show-vc-vendor      Show the vendor string from the VORBIS_COMMENT block.\n");
941         fprintf(out, "--show-vc-field=name  Show all Vorbis comment fields where the the field name\n");
942         fprintf(out, "                      matches 'name'.\n");
943         fprintf(out, "--remove-vc-field=name\n");
944         fprintf(out, "                      Remove all Vorbis comment fields whose field name is\n");
945         fprintf(out, "                      'name'.\n");
946         fprintf(out, "--remove-vc-firstfield=name\n");
947         fprintf(out, "                      Remove first Vorbis comment field whose field name is\n");
948         fprintf(out, "                      'name'.\n");
949         fprintf(out, "--remove-vc-all       Remove all Vorbis comment fields, leaving only the\n");
950         fprintf(out, "                      vendor string in the VORBIS_COMMENT block.\n");
951         fprintf(out, "--set-vc-field=field  Add a Vorbis comment field.  The field must comply with\n");
952         fprintf(out, "                      the Vorbis comment spec, of the form \"NAME=VALUE\".  If\n");
953         fprintf(out, "                      there is currently no VORBIS_COMMENT block, one will be\n");
954         fprintf(out, "                      created.\n");
955         fprintf(out, "--import-vc-from=file Import Vorbis comments from a file.  Use '-' for stdin.\n");
956         fprintf(out, "                      Each line should be of the form NAME=VALUE.  Multi-\n");
957         fprintf(out, "                      line comments are currently not supported.  Specify\n");
958         fprintf(out, "                      --remove-vc-all and/or --no-utf8-convert before\n");
959         fprintf(out, "                      --import-vc-from if necessary.\n");
960         fprintf(out, "--export-vc-to=file   Export Vorbis comments to a file.  Use '-' for stdin.\n");
961         fprintf(out, "                      Each line will be of the form NAME=VALUE.  Specify\n");
962         fprintf(out, "                      --no-utf8-convert if necessary.\n");
963         fprintf(out, "--add-replay-gain     Calculates the title and album gains/peaks of the given\n");
964         fprintf(out, "                      FLAC files as if all the files were part of one album,\n");
965         fprintf(out, "                      then stores them in the VORBIS_COMMENT block.  The tags\n");
966         fprintf(out, "                      are the same as those used by vorbisgain.  Existing\n");
967         fprintf(out, "                      ReplayGain tags will be replaced.  If only one FLAC file\n");
968         fprintf(out, "                      is given, the album and title gains will be the same.\n");
969         fprintf(out, "                      Since this operation requires two passes, it is always\n");
970         fprintf(out, "                      executed last, after all other operations have been\n");
971         fprintf(out, "                      completed and written to disk.  All FLAC files specified\n");
972         fprintf(out, "                      must have the same resolution, sample rate, and number\n");
973         fprintf(out, "                      of channels.  The sample rate must be one of 8, 11.025,\n");
974         fprintf(out, "                      12, 16, 22.05, 24, 32, 44.1, or 48 kHz.\n");
975         fprintf(out, "--add-padding=length  Add a padding block of the given length (in bytes).\n");
976         fprintf(out, "                      The overall length of the new block will be 4 + length;\n");
977         fprintf(out, "                      the extra 4 bytes is for the metadata block header.\n");
978         fprintf(out, "\n");
979         fprintf(out, "Major operations:\n");
980         fprintf(out, "--version\n");
981         fprintf(out, "    Show the metaflac version number.\n");
982         fprintf(out, "--list\n");
983         fprintf(out, "    List the contents of one or more metadata blocks to stdout.  By default,\n");
984         fprintf(out, "    all metadata blocks are listed in text format.  Use the following options\n");
985         fprintf(out, "    to change this behavior:\n");
986         fprintf(out, "\n");
987         fprintf(out, "    --block-number=#[,#[...]]\n");
988         fprintf(out, "    An optional comma-separated list of block numbers to display.  The first\n");
989         fprintf(out, "    block, the STREAMINFO block, is block 0.\n");
990         fprintf(out, "\n");
991         fprintf(out, "    --block-type=type[,type[...]]\n");
992         fprintf(out, "    --except-block-type=type[,type[...]]\n");
993         fprintf(out, "    An optional comma-separated list of block types to included or ignored\n");
994         fprintf(out, "    with this option.  Use only one of --block-type or --except-block-type.\n");
995         fprintf(out, "    The valid block types are: STREAMINFO, PADDING, APPLICATION, SEEKTABLE,\n");
996         fprintf(out, "    VORBIS_COMMENT.  You may narrow down the types of APPLICATION blocks\n");
997         fprintf(out, "    displayed as follows:\n");
998         fprintf(out, "        APPLICATION:abcd        The APPLICATION block(s) whose textual repre-\n");
999         fprintf(out, "                                sentation of the 4-byte ID is \"abcd\"\n");
1000         fprintf(out, "        APPLICATION:0xXXXXXXXX  The APPLICATION block(s) whose hexadecimal big-\n");
1001         fprintf(out, "                                endian representation of the 4-byte ID is\n");
1002         fprintf(out, "                                \"0xXXXXXXXX\".  For the example \"abcd\" above the\n");
1003         fprintf(out, "                                hexadecimal equivalalent is 0x61626364\n");
1004         fprintf(out, "\n");
1005         fprintf(out, "    NOTE: if both --block-number and --[except-]block-type are specified,\n");
1006         fprintf(out, "          the result is the logical AND of both arguments.\n");
1007         fprintf(out, "\n");
1008 #if 0
1009         /*@@@ not implemented yet */
1010         fprintf(out, "    --data-format=binary|text\n");
1011         fprintf(out, "    By default a human-readable text representation of the data is displayed.\n");
1012         fprintf(out, "    You may specify --data-format=binary to dump the raw binary form of each\n");
1013         fprintf(out, "    metadata block.  The output can be read in using a subsequent call to\n");
1014         fprintf(out, "    "metaflac --append --from-file=..."\n");
1015         fprintf(out, "\n");
1016 #endif
1017         fprintf(out, "    --application-data-format=hexdump|text\n");
1018         fprintf(out, "    If the application block you are displaying contains binary data but your\n");
1019         fprintf(out, "    --data-format=text, you can display a hex dump of the application data\n");
1020         fprintf(out, "    contents instead using --application-data-format=hexdump\n");
1021         fprintf(out, "\n");
1022 #if 0
1023         /*@@@ not implemented yet */
1024         fprintf(out, "--append\n");
1025         fprintf(out, "    Insert a metadata block from a file.  The input file must be in the same\n");
1026         fprintf(out, "    format as generated with --list.\n");
1027         fprintf(out, "\n");
1028         fprintf(out, "    --block-number=#\n");
1029         fprintf(out, "    Specify the insertion point (defaults to last block).  The new block will\n");
1030         fprintf(out, "    be added after the given block number.  This prevents the illegal insertion\n");
1031         fprintf(out, "    of a block before the first STREAMINFO block.  You may not --append another\n");
1032         fprintf(out, "    STREAMINFO block.\n");
1033         fprintf(out, "\n");
1034         fprintf(out, "    --from-file=filename\n");
1035         fprintf(out, "    Mandatory 'option' to specify the input file containing the block contents.\n");
1036         fprintf(out, "\n");
1037         fprintf(out, "    --data-format=binary|text\n");
1038         fprintf(out, "    By default the block contents are assumed to be in binary format.  You can\n");
1039         fprintf(out, "    override this by specifying --data-format=text\n");
1040         fprintf(out, "\n");
1041 #endif
1042         fprintf(out, "--remove\n");
1043         fprintf(out, "    Remove one or more metadata blocks from the metadata.  Unless\n");
1044         fprintf(out, "    --dont-use-padding is specified, the blocks will be replaced with padding.\n");
1045         fprintf(out, "    You may not remove the STREAMINFO block.\n");
1046         fprintf(out, "\n");
1047         fprintf(out, "    --block-number=#[,#[...]]\n");
1048         fprintf(out, "    --block-type=type[,type[...]]\n");
1049         fprintf(out, "    --except-block-type=type[,type[...]]\n");
1050         fprintf(out, "    See --list above for usage.\n");
1051         fprintf(out, "\n");
1052         fprintf(out, "    NOTE: if both --block-number and --[except-]block-type are specified,\n");
1053         fprintf(out, "          the result is the logical AND of both arguments.\n");
1054         fprintf(out, "\n");
1055         fprintf(out, "--remove-all\n");
1056         fprintf(out, "    Remove all metadata blocks (except the STREAMINFO block) from the\n");
1057         fprintf(out, "    metadata.  Unless --dont-use-padding is specified, the blocks will be\n");
1058         fprintf(out, "    replaced with padding.\n");
1059         fprintf(out, "\n");
1060         fprintf(out, "--merge-padding\n");
1061         fprintf(out, "    Merge adjacent PADDING blocks into single blocks.\n");
1062         fprintf(out, "\n");
1063         fprintf(out, "--sort-padding\n");
1064         fprintf(out, "    Move all PADDING blocks to the end of the metadata and merge them into a\n");
1065         fprintf(out, "    single block.\n");
1066
1067         return message? 1 : 0;
1068 }
1069
1070 char *local_strdup(const char *source)
1071 {
1072         char *ret;
1073         FLAC__ASSERT(0 != source);
1074         if(0 == (ret = strdup(source)))
1075                 die("out of memory during strdup()");
1076         return ret;
1077 }
1078
1079 FLAC__bool parse_md5(const char *src, FLAC__byte dest[16])
1080 {
1081         unsigned i, d;
1082         int c;
1083         FLAC__ASSERT(0 != src);
1084         if(strlen(src) != 32)
1085                 return false;
1086         /* strtoul() accepts negative numbers which we do not want, so we do it the hard way */
1087         for(i = 0; i < 16; i++) {
1088                 c = (int)(*src++);
1089                 if(isdigit(c))
1090                         d = (unsigned)(c - '0');
1091                 else if(c >= 'a' && c <= 'f')
1092                         d = (unsigned)(c - 'a') + 10u;
1093                 else if(c >= 'A' && c <= 'F')
1094                         d = (unsigned)(c - 'A') + 10u;
1095                 else
1096                         return false;
1097                 d <<= 4;
1098                 c = (int)(*src++);
1099                 if(isdigit(c))
1100                         d |= (unsigned)(c - '0');
1101                 else if(c >= 'a' && c <= 'f')
1102                         d |= (unsigned)(c - 'a') + 10u;
1103                 else if(c >= 'A' && c <= 'F')
1104                         d |= (unsigned)(c - 'A') + 10u;
1105                 else
1106                         return false;
1107                 dest[i] = (FLAC__byte)d;
1108         }
1109         return true;
1110 }
1111
1112 FLAC__bool parse_uint32(const char *src, FLAC__uint32 *dest)
1113 {
1114         FLAC__ASSERT(0 != src);
1115         if(strlen(src) == 0 || strspn(src, "0123456789") != strlen(src))
1116                 return false;
1117         *dest = strtoul(src, 0, 10);
1118         return true;
1119 }
1120
1121 /* There's no stroull() in MSVC6 so we just write a specialized one */
1122 static FLAC__uint64 local__strtoull(const char *src)
1123 {
1124         FLAC__uint64 ret = 0;
1125         int c;
1126         FLAC__ASSERT(0 != src);
1127         while(0 != (c = *src++)) {
1128                 c -= '0';
1129                 if(c >= 0 && c <= 9)
1130                         ret = (ret * 10) + c;
1131                 else
1132                         break;
1133         }
1134         return ret;
1135 }
1136
1137 FLAC__bool parse_uint64(const char *src, FLAC__uint64 *dest)
1138 {
1139         FLAC__ASSERT(0 != src);
1140         if(strlen(src) == 0 || strspn(src, "0123456789") != strlen(src))
1141                 return false;
1142         *dest = local__strtoull(src);
1143         return true;
1144 }
1145
1146 FLAC__bool parse_filename(const char *src, char **dest)
1147 {
1148         if(0 == src || strlen(src) == 0)
1149                 return false;
1150         *dest = strdup(src);
1151         return true;
1152 }
1153
1154 FLAC__bool parse_vorbis_comment_field(const char *field_ref, char **field, char **name, char **value, unsigned *length, const char **violation)
1155 {
1156         static const char * const violations[] = {
1157                 "field name contains invalid character",
1158                 "field contains no '=' character"
1159         };
1160
1161         char *p, *q, *s;
1162
1163         if(0 != field)
1164                 *field = local_strdup(field_ref);
1165
1166         s = local_strdup(field_ref);
1167
1168         if(0 == (p = strchr(s, '='))) {
1169                 free(s);
1170                 *violation = violations[1];
1171                 return false;
1172         }
1173         *p++ = '\0';
1174
1175         for(q = s; *q; q++) {
1176                 if(*q < 0x20 || *q > 0x7d || *q == 0x3d) {
1177                         free(s);
1178                         *violation = violations[0];
1179                         return false;
1180                 }
1181         }
1182
1183         *name = local_strdup(s);
1184         *value = local_strdup(p);
1185         *length = strlen(p);
1186
1187         free(s);
1188         return true;
1189 }
1190
1191 static FLAC__bool parse_vorbis_comment_field_name(const char *field_ref, char **name, const char **violation)
1192 {
1193         static const char * const violations[] = {
1194                 "field name contains invalid character"
1195         };
1196
1197         char *q, *s;
1198
1199         s = local_strdup(field_ref);
1200
1201         for(q = s; *q; q++) {
1202                 if(*q < 0x20 || *q > 0x7d || *q == 0x3d) {
1203                         free(s);
1204                         *violation = violations[0];
1205                         return false;
1206                 }
1207         }
1208
1209         *name = s;
1210
1211         return true;
1212 }
1213
1214 FLAC__bool parse_add_padding(const char *in, unsigned *out)
1215 {
1216         *out = (unsigned)strtoul(in, 0, 10);
1217         return *out < (1u << FLAC__STREAM_METADATA_LENGTH_LEN);
1218 }
1219
1220 FLAC__bool parse_block_number(const char *in, Argument_BlockNumber *out)
1221 {
1222         char *p, *q, *s, *end;
1223         long i;
1224         unsigned entry;
1225
1226         if(*in == '\0')
1227                 return false;
1228
1229         s = local_strdup(in);
1230
1231         /* first count the entries */
1232         for(out->num_entries = 1, p = strchr(s, ','); p; out->num_entries++, p = strchr(++p, ','))
1233                 ;
1234
1235         /* make space */
1236         FLAC__ASSERT(out->num_entries > 0);
1237         if(0 == (out->entries = malloc(sizeof(unsigned) * out->num_entries)))
1238                 die("out of memory allocating space for option list");
1239
1240         /* load 'em up */
1241         entry = 0;
1242         q = s;
1243         while(q) {
1244                 FLAC__ASSERT(entry < out->num_entries);
1245                 if(0 != (p = strchr(q, ',')))
1246                         *p++ = '\0';
1247                 if(!isdigit((int)(*q)) || (i = strtol(q, &end, 10)) < 0 || *end) {
1248                         free(s);
1249                         return false;
1250                 }
1251                 out->entries[entry++] = (unsigned)i;
1252                 q = p;
1253         }
1254         FLAC__ASSERT(entry == out->num_entries);
1255
1256         free(s);
1257         return true;
1258 }
1259
1260 FLAC__bool parse_block_type(const char *in, Argument_BlockType *out)
1261 {
1262         char *p, *q, *r, *s;
1263         unsigned entry;
1264
1265         if(*in == '\0')
1266                 return false;
1267
1268         s = local_strdup(in);
1269
1270         /* first count the entries */
1271         for(out->num_entries = 1, p = strchr(s, ','); p; out->num_entries++, p = strchr(++p, ','))
1272                 ;
1273
1274         /* make space */
1275         FLAC__ASSERT(out->num_entries > 0);
1276         if(0 == (out->entries = malloc(sizeof(Argument_BlockTypeEntry) * out->num_entries)))
1277                 die("out of memory allocating space for option list");
1278
1279         /* load 'em up */
1280         entry = 0;
1281         q = s;
1282         while(q) {
1283                 FLAC__ASSERT(entry < out->num_entries);
1284                 if(0 != (p = strchr(q, ',')))
1285                         *p++ = 0;
1286                 r = strchr(q, ':');
1287                 if(r)
1288                         *r++ = '\0';
1289                 if(0 != r && 0 != strcmp(q, "APPLICATION")) {
1290                         free(s);
1291                         return false;
1292                 }
1293                 if(0 == strcmp(q, "STREAMINFO")) {
1294                         out->entries[entry++].type = FLAC__METADATA_TYPE_STREAMINFO;
1295                 }
1296                 else if(0 == strcmp(q, "PADDING")) {
1297                         out->entries[entry++].type = FLAC__METADATA_TYPE_PADDING;
1298                 }
1299                 else if(0 == strcmp(q, "APPLICATION")) {
1300                         out->entries[entry].type = FLAC__METADATA_TYPE_APPLICATION;
1301                         out->entries[entry].filter_application_by_id = (0 != r);
1302                         if(0 != r) {
1303                                 if(strlen(r) == 4) {
1304                                         strcpy(out->entries[entry].application_id, r);
1305                                 }
1306                                 else if(strlen(r) == 10 && strncmp(r, "0x", 2) == 0 && strspn(r+2, "0123456789ABCDEFabcdef") == 8) {
1307                                         FLAC__uint32 x = strtoul(r+2, 0, 16);
1308                                         out->entries[entry].application_id[3] = (FLAC__byte)(x & 0xff);
1309                                         out->entries[entry].application_id[2] = (FLAC__byte)((x>>=8) & 0xff);
1310                                         out->entries[entry].application_id[1] = (FLAC__byte)((x>>=8) & 0xff);
1311                                         out->entries[entry].application_id[0] = (FLAC__byte)((x>>=8) & 0xff);
1312                                 }
1313                                 else {
1314                                         free(s);
1315                                         return false;
1316                                 }
1317                         }
1318                         entry++;
1319                 }
1320                 else if(0 == strcmp(q, "SEEKTABLE")) {
1321                         out->entries[entry++].type = FLAC__METADATA_TYPE_SEEKTABLE;
1322                 }
1323                 else if(0 == strcmp(q, "VORBIS_COMMENT")) {
1324                         out->entries[entry++].type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
1325                 }
1326                 else {
1327                         free(s);
1328                         return false;
1329                 }
1330                 q = p;
1331         }
1332         FLAC__ASSERT(entry == out->num_entries);
1333
1334         free(s);
1335         return true;
1336 }
1337
1338 FLAC__bool parse_data_format(const char *in, Argument_DataFormat *out)
1339 {
1340         if(0 == strcmp(in, "binary"))
1341                 out->is_binary = true;
1342         else if(0 == strcmp(in, "text"))
1343                 out->is_binary = false;
1344         else
1345                 return false;
1346         return true;
1347 }
1348
1349 FLAC__bool parse_application_data_format(const char *in, FLAC__bool *out)
1350 {
1351         if(0 == strcmp(in, "hexdump"))
1352                 *out = true;
1353         else if(0 == strcmp(in, "text"))
1354                 *out = false;
1355         else
1356                 return false;
1357         return true;
1358 }
1359
1360 FLAC__bool do_operations(const CommandLineOptions *options)
1361 {
1362         FLAC__bool ok = true;
1363
1364         if(options->show_long_help) {
1365                 long_usage(0);
1366         }
1367         if(options->show_version) {
1368                 show_version();
1369         }
1370         else if(options->args.checks.num_major_ops > 0) {
1371                 FLAC__ASSERT(options->args.checks.num_shorthand_ops == 0);
1372                 FLAC__ASSERT(options->args.checks.num_major_ops == 1);
1373                 FLAC__ASSERT(options->args.checks.num_major_ops == options->ops.num_operations);
1374                 ok = do_major_operation(options);
1375         }
1376         else if(options->args.checks.num_shorthand_ops > 0) {
1377                 FLAC__ASSERT(options->args.checks.num_shorthand_ops == options->ops.num_operations);
1378                 ok = do_shorthand_operations(options);
1379         }
1380
1381         return ok;
1382 }
1383
1384 FLAC__bool do_major_operation(const CommandLineOptions *options)
1385 {
1386         unsigned i;
1387         FLAC__bool ok = true;
1388
1389         /*@@@ to die after first error,  v---  add '&& ok' here */
1390         for(i = 0; i < options->num_files; i++)
1391                 ok &= do_major_operation_on_file(options->filenames[i], options);
1392
1393         return ok;
1394 }
1395
1396 FLAC__bool do_major_operation_on_file(const char *filename, const CommandLineOptions *options)
1397 {
1398         FLAC__bool ok = true, needs_write = false;
1399         FLAC__Metadata_Chain *chain = FLAC__metadata_chain_new();
1400
1401         if(0 == chain)
1402                 die("out of memory allocating chain");
1403
1404         if(!FLAC__metadata_chain_read(chain, filename)) {
1405                 fprintf(stderr, "%s: ERROR: reading metadata, status = \"%s\"\n", filename, FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(chain)]);
1406                 return false;
1407         }
1408
1409         switch(options->ops.operations[0].type) {
1410                 case OP__LIST:
1411                         ok = do_major_operation__list(options->prefix_with_filename? filename : 0, chain, options);
1412                         break;
1413                 case OP__APPEND:
1414                         ok = do_major_operation__append(chain, options);
1415                         needs_write = true;
1416                         break;
1417                 case OP__REMOVE:
1418                         ok = do_major_operation__remove(chain, options);
1419                         needs_write = true;
1420                         break;
1421                 case OP__REMOVE_ALL:
1422                         ok = do_major_operation__remove_all(chain, options);
1423                         needs_write = true;
1424                         break;
1425                 case OP__MERGE_PADDING:
1426                         FLAC__metadata_chain_merge_padding(chain);
1427                         needs_write = true;
1428                         break;
1429                 case OP__SORT_PADDING:
1430                         FLAC__metadata_chain_sort_padding(chain);
1431                         needs_write = true;
1432                         break;
1433                 default:
1434                         FLAC__ASSERT(0);
1435                         return false;
1436         }
1437
1438         if(ok && needs_write) {
1439                 if(options->use_padding)
1440                         FLAC__metadata_chain_sort_padding(chain);
1441                 ok = FLAC__metadata_chain_write(chain, options->use_padding, options->preserve_modtime);
1442                 if(!ok)
1443                         fprintf(stderr, "%s: ERROR: writing FLAC file, error = %s\n", filename, FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(chain)]);
1444         }
1445
1446         FLAC__metadata_chain_delete(chain);
1447
1448         return ok;
1449 }
1450
1451 FLAC__bool do_major_operation__list(const char *filename, FLAC__Metadata_Chain *chain, const CommandLineOptions *options)
1452 {
1453         FLAC__Metadata_Iterator *iterator = FLAC__metadata_iterator_new();
1454         FLAC__StreamMetadata *block;
1455         FLAC__bool ok = true;
1456         unsigned block_number;
1457
1458         if(0 == iterator)
1459                 die("out of memory allocating iterator");
1460
1461         FLAC__metadata_iterator_init(iterator, chain);
1462
1463         block_number = 0;
1464         do {
1465                 block = FLAC__metadata_iterator_get_block(iterator);
1466                 ok &= (0 != block);
1467                 if(!ok)
1468                         fprintf(stderr, "%s: ERROR: couldn't get block from chain\n", filename);
1469                 else if(passes_filter(options, FLAC__metadata_iterator_get_block(iterator), block_number))
1470                         write_metadata(filename, block, block_number, !options->utf8_convert, options->application_data_format_is_hexdump);
1471                 block_number++;
1472         } while(ok && FLAC__metadata_iterator_next(iterator));
1473
1474         FLAC__metadata_iterator_delete(iterator);
1475
1476         return ok;
1477 }
1478
1479 FLAC__bool do_major_operation__append(FLAC__Metadata_Chain *chain, const CommandLineOptions *options)
1480 {
1481         (void) chain, (void) options;
1482         fprintf(stderr, "ERROR: --append not implemented yet\n"); /*@@@*/
1483         return false;
1484 }
1485
1486 FLAC__bool do_major_operation__remove(FLAC__Metadata_Chain *chain, const CommandLineOptions *options)
1487 {
1488         FLAC__Metadata_Iterator *iterator = FLAC__metadata_iterator_new();
1489         FLAC__bool ok = true;
1490         unsigned block_number;
1491
1492         if(0 == iterator)
1493                 die("out of memory allocating iterator");
1494
1495         FLAC__metadata_iterator_init(iterator, chain);
1496
1497         block_number = 0;
1498         while(ok && FLAC__metadata_iterator_next(iterator)) {
1499                 block_number++;
1500                 if(passes_filter(options, FLAC__metadata_iterator_get_block(iterator), block_number)) {
1501                         ok &= FLAC__metadata_iterator_delete_block(iterator, options->use_padding);
1502                         if(options->use_padding)
1503                                 ok &= FLAC__metadata_iterator_next(iterator);
1504                 }
1505         }
1506
1507         FLAC__metadata_iterator_delete(iterator);
1508
1509         return ok;
1510 }
1511
1512 FLAC__bool do_major_operation__remove_all(FLAC__Metadata_Chain *chain, const CommandLineOptions *options)
1513 {
1514         FLAC__Metadata_Iterator *iterator = FLAC__metadata_iterator_new();
1515         FLAC__bool ok = true;
1516
1517         if(0 == iterator)
1518                 die("out of memory allocating iterator");
1519
1520         FLAC__metadata_iterator_init(iterator, chain);
1521
1522         while(ok && FLAC__metadata_iterator_next(iterator)) {
1523                 ok &= FLAC__metadata_iterator_delete_block(iterator, options->use_padding);
1524                 if(options->use_padding)
1525                         ok &= FLAC__metadata_iterator_next(iterator);
1526         }
1527
1528         FLAC__metadata_iterator_delete(iterator);
1529
1530         return ok;
1531 }
1532
1533 FLAC__bool do_shorthand_operations(const CommandLineOptions *options)
1534 {
1535         unsigned i;
1536         FLAC__bool ok = true;
1537
1538         /* to die after first error,     v---  add '&& ok' here */
1539         for(i = 0; i < options->num_files; i++)
1540                 ok &= do_shorthand_operations_on_file(options->filenames[i], options);
1541
1542         /* check if OP__ADD_REPLAY_GAIN requested */
1543         if(ok && options->num_files > 0) {
1544                 for(i = 0; i < options->ops.num_operations; i++) {
1545                         if(options->ops.operations[i].type == OP__ADD_REPLAY_GAIN)
1546                                 ok = do_shorthand_operation__add_replay_gain(options->filenames, options->num_files);
1547                 }
1548         }
1549
1550         return ok;
1551 }
1552
1553 FLAC__bool do_shorthand_operations_on_file(const char *filename, const CommandLineOptions *options)
1554 {
1555         unsigned i;
1556         FLAC__bool ok = true, needs_write = false, use_padding = options->use_padding;
1557         FLAC__Metadata_Chain *chain = FLAC__metadata_chain_new();
1558
1559         if(0 == chain)
1560                 die("out of memory allocating chain");
1561
1562         if(!FLAC__metadata_chain_read(chain, filename)) {
1563                 fprintf(stderr, "%s: ERROR: reading metadata, status = \"%s\"\n", filename, FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(chain)]);
1564                 return false;
1565         }
1566
1567         for(i = 0; i < options->ops.num_operations && ok; i++) {
1568                 ok &= do_shorthand_operation(options->prefix_with_filename? filename : 0, chain, &options->ops.operations[i], &needs_write, options->utf8_convert);
1569
1570                 /* The following seems counterintuitive but the meaning
1571                  * of 'use_padding' is 'try to keep the overall metadata
1572                  * to its original size, adding or truncating extra
1573                  * padding if necessary' which is why we need to turn it
1574                  * off in this case.  If we don't, the extra padding block
1575                  * will just be truncated.
1576                  */
1577                 if(options->ops.operations[i].type == OP__ADD_PADDING)
1578                         use_padding = false;
1579         }
1580
1581         if(ok && needs_write) {
1582                 if(use_padding)
1583                         FLAC__metadata_chain_sort_padding(chain);
1584                 ok = FLAC__metadata_chain_write(chain, use_padding, options->preserve_modtime);
1585                 if(!ok)
1586                         fprintf(stderr, "%s: ERROR: writing FLAC file, error = %s\n", filename, FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(chain)]);
1587         }
1588
1589         FLAC__metadata_chain_delete(chain);
1590
1591         return ok;
1592 }
1593
1594 FLAC__bool do_shorthand_operation(const char *filename, FLAC__Metadata_Chain *chain, const Operation *operation, FLAC__bool *needs_write, FLAC__bool utf8_convert)
1595 {
1596         FLAC__bool ok = true;
1597
1598         switch(operation->type) {
1599                 case OP__SHOW_MD5SUM:
1600                 case OP__SHOW_MIN_BLOCKSIZE:
1601                 case OP__SHOW_MAX_BLOCKSIZE:
1602                 case OP__SHOW_MIN_FRAMESIZE:
1603                 case OP__SHOW_MAX_FRAMESIZE:
1604                 case OP__SHOW_SAMPLE_RATE:
1605                 case OP__SHOW_CHANNELS:
1606                 case OP__SHOW_BPS:
1607                 case OP__SHOW_TOTAL_SAMPLES:
1608                 case OP__SET_MD5SUM:
1609                 case OP__SET_MIN_BLOCKSIZE:
1610                 case OP__SET_MAX_BLOCKSIZE:
1611                 case OP__SET_MIN_FRAMESIZE:
1612                 case OP__SET_MAX_FRAMESIZE:
1613                 case OP__SET_SAMPLE_RATE:
1614                 case OP__SET_CHANNELS:
1615                 case OP__SET_BPS:
1616                 case OP__SET_TOTAL_SAMPLES:
1617                         ok = do_shorthand_operation__streaminfo(filename, chain, operation, needs_write);
1618                         break;
1619                 case OP__SHOW_VC_VENDOR:
1620                 case OP__SHOW_VC_FIELD:
1621                 case OP__REMOVE_VC_ALL:
1622                 case OP__REMOVE_VC_FIELD:
1623                 case OP__REMOVE_VC_FIRSTFIELD:
1624                 case OP__SET_VC_FIELD:
1625                 case OP__IMPORT_VC_FROM:
1626                 case OP__EXPORT_VC_TO:
1627                         ok = do_shorthand_operation__vorbis_comment(filename, chain, operation, needs_write, !utf8_convert);
1628                         break;
1629                 case OP__ADD_REPLAY_GAIN:
1630                         /* this command is always executed last */
1631                         ok = true;
1632                         break;
1633                 case OP__ADD_PADDING:
1634                         ok = do_shorthand_operation__add_padding(filename, chain, operation->argument.add_padding.length, needs_write);
1635                         break;
1636                 default:
1637                         ok = false;
1638                         FLAC__ASSERT(0);
1639                         break;
1640         };
1641
1642         return ok;
1643 }
1644
1645 FLAC__bool do_shorthand_operation__add_replay_gain(char **filenames, unsigned num_files)
1646 {
1647         static const unsigned valid_sample_rates[] = {
1648                 8000,
1649                 11025,
1650                 12000,
1651                 16000,
1652                 22050,
1653                 24000,
1654                 32000,
1655                 44100,
1656                 48000
1657         };
1658         static const unsigned n_valid_sample_rates = sizeof(valid_sample_rates) / sizeof(valid_sample_rates[0]);
1659
1660         FLAC__StreamMetadata streaminfo;
1661         float *title_gains = 0, *title_peaks = 0;
1662         float album_gain = 0.0, album_peak = 0.0;
1663         unsigned sample_rate = 0;
1664         unsigned bits_per_sample = 0;
1665         unsigned channels = 0;
1666         unsigned i, j;
1667         FLAC__bool first = true;
1668
1669         FLAC__ASSERT(num_files > 0);
1670
1671         for(i = 0; i < num_files; i++) {
1672                 FLAC__ASSERT(0 != filenames[i]);
1673                 if(!FLAC__metadata_get_streaminfo(filenames[i], &streaminfo)) {
1674                         fprintf(stderr, "%s: ERROR: can't open file or get STREAMINFO block\n", filenames[i]);
1675                         return false;
1676                 }
1677                 if(first) {
1678                         first = false;
1679                         sample_rate = streaminfo.data.stream_info.sample_rate;
1680                         bits_per_sample = streaminfo.data.stream_info.bits_per_sample;
1681                         channels = streaminfo.data.stream_info.channels;
1682                 }
1683                 else {
1684                         if(sample_rate != streaminfo.data.stream_info.sample_rate) {
1685                                 fprintf(stderr, "%s: ERROR: sample rate of %u Hz does not match previous files' %u Hz\n", filenames[i], streaminfo.data.stream_info.sample_rate, sample_rate);
1686                                 return false;
1687                         }
1688                         if(bits_per_sample != streaminfo.data.stream_info.bits_per_sample) {
1689                                 fprintf(stderr, "%s: ERROR: resolution of %u bps does not match previous files' %u bps\n", filenames[i], streaminfo.data.stream_info.bits_per_sample, bits_per_sample);
1690                                 return false;
1691                         }
1692                         if(channels != streaminfo.data.stream_info.channels) {
1693                                 fprintf(stderr, "%s: ERROR: # channels (%u) does not match previous files' (%u)\n", filenames[i], streaminfo.data.stream_info.channels, channels);
1694                                 return false;
1695                         }
1696                 }
1697                 for(j = 0; j < n_valid_sample_rates; j++)
1698                         if(sample_rate == valid_sample_rates[j])
1699                                 break;
1700                 if(j == n_valid_sample_rates) {
1701                         fprintf(stderr, "%s: ERROR: sample rate of %u Hz is not supported\n", filenames[i], sample_rate);
1702                         return false;
1703                 }
1704                 if(channels != 1 && channels != 2) {
1705                         fprintf(stderr, "%s: ERROR: # of channels (%u) is not supported, must be 1 or 2\n", filenames[i], channels);
1706                         return false;
1707                 }
1708         }
1709         FLAC__ASSERT(bits_per_sample >= FLAC__MIN_BITS_PER_SAMPLE && bits_per_sample <= FLAC__MAX_BITS_PER_SAMPLE);
1710
1711         if(!FLAC__replaygain_init(sample_rate))
1712                 FLAC__ASSERT(0);
1713
1714         if(
1715                 0 == (title_gains = (float*)malloc(sizeof(float) * num_files)) ||
1716                 0 == (title_peaks = (float*)malloc(sizeof(float) * num_files))
1717         )
1718                 die("out of memory allocating space for title gains/peaks");
1719
1720         for(i = 0; i < num_files; i++) {
1721                 if(!do_replaygain_analyze_file(filenames[i], title_gains+i, title_peaks+i)) {
1722                         free(title_gains);
1723                         free(title_peaks);
1724                         return false;
1725                 }
1726                 if(title_peaks[i] > album_peak)
1727                         album_peak = title_peaks[i];
1728         }
1729         album_gain = FLAC__replaygain_get_album_gain();
1730
1731         for(i = 0; i < num_files; i++) {
1732                 if(!do_replaygain_store_to_file(filenames[i], album_gain, album_peak, title_gains[i], title_peaks[i])) {
1733                         free(title_gains);
1734                         free(title_peaks);
1735                         return false;
1736                 }
1737         }
1738
1739         free(title_gains);
1740         free(title_peaks);
1741         return true;
1742 }
1743
1744 FLAC__bool do_replaygain_analyze_file(const char *filename, float *title_gain, float *title_peak)
1745 {
1746         return false;//@@@@
1747 }
1748
1749 FLAC__bool do_replaygain_store_to_file(const char *filename, float album_gain, float album_peak, float title_gain, float title_peak)
1750 {
1751         return false;//@@@@
1752 }
1753
1754 FLAC__bool do_shorthand_operation__add_padding(const char *filename, FLAC__Metadata_Chain *chain, unsigned length, FLAC__bool *needs_write)
1755 {
1756         FLAC__StreamMetadata *padding = 0;
1757         FLAC__Metadata_Iterator *iterator = FLAC__metadata_iterator_new();
1758
1759         if(0 == iterator)
1760                 die("out of memory allocating iterator");
1761
1762         FLAC__metadata_iterator_init(iterator, chain);
1763
1764         while(FLAC__metadata_iterator_next(iterator))
1765                 ;
1766
1767         padding = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING);
1768         if(0 == padding)
1769                 die("out of memory allocating PADDING block");
1770
1771         padding->length = length;
1772
1773         if(!FLAC__metadata_iterator_insert_block_after(iterator, padding)) {
1774                 fprintf(stderr, "%s: ERROR: adding new PADDING block to metadata, status =\"%s\"\n", filename, FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(chain)]);
1775                 FLAC__metadata_object_delete(padding);
1776                 FLAC__metadata_iterator_delete(iterator);
1777                 return false;
1778         }
1779
1780         FLAC__metadata_iterator_delete(iterator);
1781         *needs_write = true;
1782         return true;
1783 }
1784
1785 FLAC__bool do_shorthand_operation__streaminfo(const char *filename, FLAC__Metadata_Chain *chain, const Operation *operation, FLAC__bool *needs_write)
1786 {
1787         unsigned i;
1788         FLAC__bool ok = true;
1789         FLAC__StreamMetadata *block;
1790         FLAC__Metadata_Iterator *iterator = FLAC__metadata_iterator_new();
1791
1792         if(0 == iterator)
1793                 die("out of memory allocating iterator");
1794
1795         FLAC__metadata_iterator_init(iterator, chain);
1796
1797         block = FLAC__metadata_iterator_get_block(iterator);
1798
1799         FLAC__ASSERT(0 != block);
1800         FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_STREAMINFO);
1801
1802         if(0 != filename)
1803                 printf("%s:", filename);
1804
1805         switch(operation->type) {
1806                 case OP__SHOW_MD5SUM:
1807                         for(i = 0; i < 16; i++)
1808                                 printf("%02x", block->data.stream_info.md5sum[i]);
1809                         printf("\n");
1810                         break;
1811                 case OP__SHOW_MIN_BLOCKSIZE:
1812                         printf("%u\n", block->data.stream_info.min_blocksize);
1813                         break;
1814                 case OP__SHOW_MAX_BLOCKSIZE:
1815                         printf("%u\n", block->data.stream_info.max_blocksize);
1816                         break;
1817                 case OP__SHOW_MIN_FRAMESIZE:
1818                         printf("%u\n", block->data.stream_info.min_framesize);
1819                         break;
1820                 case OP__SHOW_MAX_FRAMESIZE:
1821                         printf("%u\n", block->data.stream_info.max_framesize);
1822                         break;
1823                 case OP__SHOW_SAMPLE_RATE:
1824                         printf("%u\n", block->data.stream_info.sample_rate);
1825                         break;
1826                 case OP__SHOW_CHANNELS:
1827                         printf("%u\n", block->data.stream_info.channels);
1828                         break;
1829                 case OP__SHOW_BPS:
1830                         printf("%u\n", block->data.stream_info.bits_per_sample);
1831                         break;
1832                 case OP__SHOW_TOTAL_SAMPLES:
1833                         printf("%llu\n", block->data.stream_info.total_samples);
1834                         break;
1835                 case OP__SET_MD5SUM:
1836                         memcpy(block->data.stream_info.md5sum, operation->argument.streaminfo_md5.value, 16);
1837                         *needs_write = true;
1838                         break;
1839                 case OP__SET_MIN_BLOCKSIZE:
1840                         block->data.stream_info.min_blocksize = operation->argument.streaminfo_uint32.value;
1841                         *needs_write = true;
1842                         break;
1843                 case OP__SET_MAX_BLOCKSIZE:
1844                         block->data.stream_info.max_blocksize = operation->argument.streaminfo_uint32.value;
1845                         *needs_write = true;
1846                         break;
1847                 case OP__SET_MIN_FRAMESIZE:
1848                         block->data.stream_info.min_framesize = operation->argument.streaminfo_uint32.value;
1849                         *needs_write = true;
1850                         break;
1851                 case OP__SET_MAX_FRAMESIZE:
1852                         block->data.stream_info.max_framesize = operation->argument.streaminfo_uint32.value;
1853                         *needs_write = true;
1854                         break;
1855                 case OP__SET_SAMPLE_RATE:
1856                         block->data.stream_info.sample_rate = operation->argument.streaminfo_uint32.value;
1857                         *needs_write = true;
1858                         break;
1859                 case OP__SET_CHANNELS:
1860                         block->data.stream_info.channels = operation->argument.streaminfo_uint32.value;
1861                         *needs_write = true;
1862                         break;
1863                 case OP__SET_BPS:
1864                         block->data.stream_info.bits_per_sample = operation->argument.streaminfo_uint32.value;
1865                         *needs_write = true;
1866                         break;
1867                 case OP__SET_TOTAL_SAMPLES:
1868                         block->data.stream_info.total_samples = operation->argument.streaminfo_uint64.value;
1869                         *needs_write = true;
1870                         break;
1871                 default:
1872                         ok = false;
1873                         FLAC__ASSERT(0);
1874                         break;
1875         };
1876
1877         FLAC__metadata_iterator_delete(iterator);
1878
1879         return ok;
1880 }
1881
1882 FLAC__bool do_shorthand_operation__vorbis_comment(const char *filename, FLAC__Metadata_Chain *chain, const Operation *operation, FLAC__bool *needs_write, FLAC__bool raw)
1883 {
1884         FLAC__bool ok = true, found_vc_block = false;
1885         FLAC__StreamMetadata *block = 0;
1886         FLAC__Metadata_Iterator *iterator = FLAC__metadata_iterator_new();
1887
1888         if(0 == iterator)
1889                 die("out of memory allocating iterator");
1890
1891         FLAC__metadata_iterator_init(iterator, chain);
1892
1893         do {
1894                 block = FLAC__metadata_iterator_get_block(iterator);
1895                 if(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT)
1896                         found_vc_block = true;
1897         } while(!found_vc_block && FLAC__metadata_iterator_next(iterator));
1898
1899         if(!found_vc_block) {
1900                 /* create a new block if necessary */
1901                 if(operation->type == OP__SET_VC_FIELD || operation->type == OP__IMPORT_VC_FROM) {
1902                         block = FLAC__metadata_object_new(FLAC__METADATA_TYPE_VORBIS_COMMENT);
1903                         if(0 == block)
1904                                 die("out of memory allocating VORBIS_COMMENT block");
1905                         while(FLAC__metadata_iterator_next(iterator))
1906                                 ;
1907                         if(!FLAC__metadata_iterator_insert_block_after(iterator, block)) {
1908                                 fprintf(stderr, "%s: ERROR: adding new VORBIS_COMMENT block to metadata, status =\"%s\"\n", filename, FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(chain)]);
1909                                 return false;
1910                         }
1911                         /* iterator is left pointing to new block */
1912                         FLAC__ASSERT(FLAC__metadata_iterator_get_block(iterator) == block);
1913                 }
1914                 else {
1915                         FLAC__metadata_iterator_delete(iterator);
1916                         return ok;
1917                 }
1918         }
1919
1920         FLAC__ASSERT(0 != block);
1921         FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
1922
1923         switch(operation->type) {
1924                 case OP__SHOW_VC_VENDOR:
1925                         write_vc_field(filename, &block->data.vorbis_comment.vendor_string, raw, stdout);
1926                         break;
1927                 case OP__SHOW_VC_FIELD:
1928                         write_vc_fields(filename, operation->argument.vc_field_name.value, block->data.vorbis_comment.comments, block->data.vorbis_comment.num_comments, raw, stdout);
1929                         break;
1930                 case OP__REMOVE_VC_ALL:
1931                         ok = remove_vc_all(filename, block, needs_write);
1932                         break;
1933                 case OP__REMOVE_VC_FIELD:
1934                         ok = remove_vc_field(block, operation->argument.vc_field_name.value, needs_write);
1935                         break;
1936                 case OP__REMOVE_VC_FIRSTFIELD:
1937                         ok = remove_vc_firstfield(filename, block, operation->argument.vc_field_name.value, needs_write);
1938                         break;
1939                 case OP__SET_VC_FIELD:
1940                         ok = set_vc_field(filename, block, &operation->argument.vc_field, needs_write, raw);
1941                         break;
1942                 case OP__IMPORT_VC_FROM:
1943                         ok = import_vc_from(filename, block, &operation->argument.vc_filename, needs_write, raw);
1944                         break;
1945                 case OP__EXPORT_VC_TO:
1946                         ok = export_vc_to(filename, block, &operation->argument.vc_filename, raw);
1947                         break;
1948                 default:
1949                         ok = false;
1950                         FLAC__ASSERT(0);
1951                         break;
1952         };
1953
1954         FLAC__metadata_iterator_delete(iterator);
1955         return ok;
1956 }
1957
1958 FLAC__bool passes_filter(const CommandLineOptions *options, const FLAC__StreamMetadata *block, unsigned block_number)
1959 {
1960         unsigned i, j;
1961         FLAC__bool matches_number = false, matches_type = false;
1962         FLAC__bool has_block_number_arg = false;
1963
1964         for(i = 0; i < options->args.num_arguments; i++) {
1965                 if(options->args.arguments[i].type == ARG__BLOCK_TYPE || options->args.arguments[i].type == ARG__EXCEPT_BLOCK_TYPE) {
1966                         for(j = 0; j < options->args.arguments[i].value.block_type.num_entries; j++) {
1967                                 if(options->args.arguments[i].value.block_type.entries[j].type == block->type) {
1968                                         if(block->type != FLAC__METADATA_TYPE_APPLICATION || !options->args.arguments[i].value.block_type.entries[j].filter_application_by_id || 0 == memcmp(options->args.arguments[i].value.block_type.entries[j].application_id, block->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
1969                                                 matches_type = true;
1970                                 }
1971                         }
1972                 }
1973                 else if(options->args.arguments[i].type == ARG__BLOCK_NUMBER) {
1974                         has_block_number_arg = true;
1975                         for(j = 0; j < options->args.arguments[i].value.block_number.num_entries; j++) {
1976                                 if(options->args.arguments[i].value.block_number.entries[j] == block_number)
1977                                         matches_number = true;
1978                         }
1979                 }
1980         }
1981
1982         if(!has_block_number_arg)
1983                 matches_number = true;
1984
1985         if(options->args.checks.has_block_type) {
1986                 FLAC__ASSERT(!options->args.checks.has_except_block_type);
1987         }
1988         else if(options->args.checks.has_except_block_type)
1989                 matches_type = !matches_type;
1990         else
1991                 matches_type = true;
1992
1993         return matches_number && matches_type;
1994 }
1995
1996 void write_metadata(const char *filename, FLAC__StreamMetadata *block, unsigned block_number, FLAC__bool raw, FLAC__bool hexdump_application)
1997 {
1998         unsigned i;
1999
2000 /*@@@ yuck, should do this with a varargs function or something: */
2001 #define PPR if(filename)printf("%s:",filename);
2002         PPR; printf("METADATA block #%u\n", block_number);
2003         PPR; printf("  type: %u (%s)\n", (unsigned)block->type, block->type<=FLAC__METADATA_TYPE_VORBIS_COMMENT? FLAC__MetadataTypeString[block->type] : "UNKNOWN");
2004         PPR; printf("  is last: %s\n", block->is_last? "true":"false");
2005         PPR; printf("  length: %u\n", block->length);
2006
2007         switch(block->type) {
2008                 case FLAC__METADATA_TYPE_STREAMINFO:
2009                         PPR; printf("  minumum blocksize: %u samples\n", block->data.stream_info.min_blocksize);
2010                         PPR; printf("  maximum blocksize: %u samples\n", block->data.stream_info.max_blocksize);
2011                         PPR; printf("  minimum framesize: %u bytes\n", block->data.stream_info.min_framesize);
2012                         PPR; printf("  maximum framesize: %u bytes\n", block->data.stream_info.max_framesize);
2013                         PPR; printf("  sample_rate: %u Hz\n", block->data.stream_info.sample_rate);
2014                         PPR; printf("  channels: %u\n", block->data.stream_info.channels);
2015                         PPR; printf("  bits-per-sample: %u\n", block->data.stream_info.bits_per_sample);
2016                         PPR; printf("  total samples: %llu\n", block->data.stream_info.total_samples);
2017                         PPR; printf("  MD5 signature: ");
2018                         for(i = 0; i < 16; i++) {
2019                                 printf("%02x", (unsigned)block->data.stream_info.md5sum[i]);
2020                         }
2021                         printf("\n");
2022                         break;
2023                 case FLAC__METADATA_TYPE_PADDING:
2024                         /* nothing to print */
2025                         break;
2026                 case FLAC__METADATA_TYPE_APPLICATION:
2027                         PPR; printf("  application ID: ");
2028                         for(i = 0; i < 4; i++) {
2029                                 PPR; printf("%02x", block->data.application.id[i]);
2030                         }
2031                         PPR; printf("\n");
2032                         PPR; printf("  data contents:\n");
2033                         if(0 != block->data.application.data) {
2034                                 if(hexdump_application)
2035                                         hexdump(filename, block->data.application.data, block->length - FLAC__STREAM_METADATA_HEADER_LENGTH, "    ");
2036                                 else
2037                                         (void) fwrite(block->data.application.data, 1, block->length - FLAC__STREAM_METADATA_HEADER_LENGTH, stdout);
2038                         }
2039                         break;
2040                 case FLAC__METADATA_TYPE_SEEKTABLE:
2041                         PPR; printf("  seek points: %u\n", block->data.seek_table.num_points);
2042                         for(i = 0; i < block->data.seek_table.num_points; i++) {
2043                                 if(block->data.seek_table.points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
2044                                         PPR; printf("    point %d: sample_number=%llu, stream_offset=%llu, frame_samples=%u\n", i, block->data.seek_table.points[i].sample_number, block->data.seek_table.points[i].stream_offset, block->data.seek_table.points[i].frame_samples);
2045                                 }
2046                                 else {
2047                                         PPR; printf("    point %d: PLACEHOLDER\n", i);
2048                                 }
2049                         }
2050                         break;
2051                 case FLAC__METADATA_TYPE_VORBIS_COMMENT:
2052                         PPR; printf("  vendor string: ");
2053                         write_vc_field(0, &block->data.vorbis_comment.vendor_string, raw, stdout);
2054                         PPR; printf("  comments: %u\n", block->data.vorbis_comment.num_comments);
2055                         for(i = 0; i < block->data.vorbis_comment.num_comments; i++) {
2056                                 PPR; printf("    comment[%u]: ", i);
2057                                 write_vc_field(0, &block->data.vorbis_comment.comments[i], raw, stdout);
2058                         }
2059                         break;
2060                 default:
2061                         PPR; printf("SKIPPING block of unknown type\n");
2062                         break;
2063         }
2064 #undef PPR
2065 }
2066
2067 void write_vc_field(const char *filename, const FLAC__StreamMetadata_VorbisComment_Entry *entry, FLAC__bool raw, FILE *f)
2068 {
2069         if(0 != entry->entry) {
2070                 if(filename)
2071                         fprintf(f, "%s:", filename);
2072
2073                 if(!raw) {
2074                         /*
2075                          * utf8_decode() works on NULL-terminated strings, so
2076                          * we append a null to the entry.  @@@ Note, this means
2077                          * that comments that contain an embedded null will be
2078                          * truncated by utf_decode().
2079                          */
2080                         char *terminated, *converted;
2081
2082                         if(0 == (terminated = malloc(entry->length + 1)))
2083                                 die("out of memory allocating space for vorbis comment");
2084                         memcpy(terminated, entry->entry, entry->length);
2085                         terminated[entry->length] = '\0';
2086                         if(utf8_decode(terminated, &converted) >= 0) {
2087                                 (void) fwrite(converted, 1, strlen(converted), f);
2088                                 free(terminated);
2089                                 free(converted);
2090                         }
2091                         else {
2092                                 free(terminated);
2093                                 (void) fwrite(entry->entry, 1, entry->length, f);
2094                         }
2095                 }
2096                 else {
2097                         (void) fwrite(entry->entry, 1, entry->length, f);
2098                 }
2099         }
2100
2101         fprintf(f, "\n");
2102 }
2103
2104 void write_vc_fields(const char *filename, const char *field_name, const FLAC__StreamMetadata_VorbisComment_Entry entry[], unsigned num_entries, FLAC__bool raw, FILE *f)
2105 {
2106         unsigned i;
2107         const unsigned field_name_length = (0 != field_name)? strlen(field_name) : 0;
2108
2109         for(i = 0; i < num_entries; i++) {
2110                 if(0 == field_name || field_name_matches_entry(field_name, field_name_length, entry + i))
2111                         write_vc_field(filename, entry + i, raw, f);
2112         }
2113 }
2114
2115 FLAC__bool remove_vc_all(const char *filename, FLAC__StreamMetadata *block, FLAC__bool *needs_write)
2116 {
2117         FLAC__ASSERT(0 != block);
2118         FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
2119         FLAC__ASSERT(0 != needs_write);
2120
2121         if(0 != block->data.vorbis_comment.comments) {
2122                 FLAC__ASSERT(block->data.vorbis_comment.num_comments > 0);
2123                 if(!FLAC__metadata_object_vorbiscomment_resize_comments(block, 0)) {
2124                         fprintf(stderr, "%s: ERROR: memory allocation failure\n", filename);
2125                         return false;
2126                 }
2127                 *needs_write = true;
2128         }
2129         else {
2130                 FLAC__ASSERT(block->data.vorbis_comment.num_comments == 0);
2131         }
2132
2133         return true;
2134 }
2135
2136 FLAC__bool remove_vc_field(FLAC__StreamMetadata *block, const char *field_name, FLAC__bool *needs_write)
2137 {
2138         FLAC__bool ok = true;
2139         const unsigned field_name_length = strlen(field_name);
2140         int i;
2141
2142         FLAC__ASSERT(0 != block);
2143         FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
2144         FLAC__ASSERT(0 != needs_write);
2145
2146         /* must delete from end to start otherwise it will interfere with our iteration */
2147         for(i = (int)block->data.vorbis_comment.num_comments - 1; ok && i >= 0; i--) {
2148                 if(field_name_matches_entry(field_name, field_name_length, block->data.vorbis_comment.comments + i)) {
2149                         ok &= FLAC__metadata_object_vorbiscomment_delete_comment(block, (unsigned)i);
2150                         if(ok)
2151                                 *needs_write = true;
2152                 }
2153         }
2154
2155         return ok;
2156 }
2157
2158 FLAC__bool remove_vc_firstfield(const char *filename, FLAC__StreamMetadata *block, const char *field_name, FLAC__bool *needs_write)
2159 {
2160         const unsigned field_name_length = strlen(field_name);
2161         unsigned i;
2162
2163         FLAC__ASSERT(0 != block);
2164         FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
2165         FLAC__ASSERT(0 != needs_write);
2166
2167         for(i = 0; i < block->data.vorbis_comment.num_comments; i++) {
2168                 if(field_name_matches_entry(field_name, field_name_length, block->data.vorbis_comment.comments + i)) {
2169                         if(!FLAC__metadata_object_vorbiscomment_delete_comment(block, (unsigned)i)) {
2170                                 fprintf(stderr, "%s: ERROR: memory allocation failure\n", filename);
2171                                 return false;
2172                         }
2173                         else
2174                                 *needs_write = true;
2175                         break;
2176                 }
2177         }
2178
2179         return true;
2180 }
2181
2182 FLAC__bool set_vc_field(const char *filename, FLAC__StreamMetadata *block, const Argument_VcField *field, FLAC__bool *needs_write, FLAC__bool raw)
2183 {
2184         FLAC__StreamMetadata_VorbisComment_Entry entry;
2185         char *converted;
2186         FLAC__bool needs_free = false;
2187
2188         FLAC__ASSERT(0 != block);
2189         FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
2190         FLAC__ASSERT(0 != field);
2191         FLAC__ASSERT(0 != needs_write);
2192
2193         if(raw) {
2194                 entry.entry = field->field;
2195         }
2196         else if(utf8_encode(field->field, &converted) >= 0) {
2197                 entry.entry = converted;
2198                 needs_free = true;
2199         }
2200         else {
2201                 fprintf(stderr, "%s: ERROR: couldn't convert comment to UTF-8\n", filename);
2202                 return false;
2203         }
2204
2205         entry.length = strlen(entry.entry);
2206
2207         if(!FLAC__metadata_object_vorbiscomment_insert_comment(block, block->data.vorbis_comment.num_comments, entry, /*copy=*/true)) {
2208                 if(needs_free)
2209                         free(converted);
2210                 fprintf(stderr, "%s: ERROR: memory allocation failure\n", filename);
2211                 return false;
2212         }
2213         else {
2214                 *needs_write = true;
2215                 if(needs_free)
2216                         free(converted);
2217                 return true;
2218         }
2219 }
2220
2221 FLAC__bool import_vc_from(const char *filename, FLAC__StreamMetadata *block, const Argument_VcFilename *vc_filename, FLAC__bool *needs_write, FLAC__bool raw)
2222 {
2223         FILE *f;
2224         char line[65536];
2225         FLAC__bool ret;
2226
2227         if(0 == vc_filename->value || strlen(vc_filename->value) == 0) {
2228                 fprintf(stderr, "%s: ERROR: empty import file name\n", filename);
2229                 return false;
2230         }
2231         if(0 == strcmp(vc_filename->value, "-"))
2232                 f = stdin;
2233         else
2234                 f = fopen(vc_filename->value, "r");
2235
2236         if(0 == f) {
2237                 fprintf(stderr, "%s: ERROR: can't open import file %s\n", filename, vc_filename->value);
2238                 return false;
2239         }
2240
2241         ret = true;
2242         while(ret && !feof(f)) {
2243                 fgets(line, sizeof(line), f);
2244                 if(!feof(f)) {
2245                         char *p = strchr(line, '\n');
2246                         if(0 == p) {
2247                                 fprintf(stderr, "%s: ERROR: line too long, aborting\n", vc_filename->value);
2248                                 ret = false;
2249                         }
2250                         else {
2251                                 const char *violation;
2252                                 Argument_VcField field;
2253                                 *p = '\0';
2254                                 memset(&field, 0, sizeof(Argument_VcField));
2255                                 if(!parse_vorbis_comment_field(line, &field.field, &field.field_name, &field.field_value, &field.field_value_length, &violation)) {
2256                                         FLAC__ASSERT(0 != violation);
2257                                         fprintf(stderr, "%s: ERROR: malformed vorbis comment field \"%s\",\n       %s\n", vc_filename->value, line, violation);
2258                                         ret = false;
2259                                 }
2260                                 else {
2261                                         ret = set_vc_field(filename, block, &field, needs_write, raw);
2262                                 }
2263                                 if(0 != field.field)
2264                                         free(field.field);
2265                                 if(0 != field.field_name)
2266                                         free(field.field_name);
2267                                 if(0 != field.field_value)
2268                                         free(field.field_value);
2269                         }
2270                 }
2271         };
2272
2273         if(f != stdin)
2274                 fclose(f);
2275         return ret;
2276 }
2277
2278 FLAC__bool export_vc_to(const char *filename, FLAC__StreamMetadata *block, const Argument_VcFilename *vc_filename, FLAC__bool raw)
2279 {
2280         FILE *f;
2281         FLAC__bool ret;
2282
2283         if(0 == vc_filename->value || strlen(vc_filename->value) == 0) {
2284                 fprintf(stderr, "%s: ERROR: empty export file name\n", filename);
2285                 return false;
2286         }
2287         if(0 == strcmp(vc_filename->value, "-"))
2288                 f = stdout;
2289         else
2290                 f = fopen(vc_filename->value, "w");
2291
2292         if(0 == f) {
2293                 fprintf(stderr, "%s: ERROR: can't open export file %s\n", filename, vc_filename->value);
2294                 return false;
2295         }
2296
2297         ret = true;
2298
2299         write_vc_fields(0, 0, block->data.vorbis_comment.comments, block->data.vorbis_comment.num_comments, raw, f);
2300
2301         if(f != stdout)
2302                 fclose(f);
2303         return ret;
2304 }
2305
2306 FLAC__bool field_name_matches_entry(const char *field_name, unsigned field_name_length, const FLAC__StreamMetadata_VorbisComment_Entry *entry)
2307 {
2308         const FLAC__byte *eq = memchr(entry->entry, '=', entry->length);
2309 #if defined _MSC_VER || defined __MINGW32__
2310 #define FLAC__STRNCASECMP strnicmp
2311 #else
2312 #define FLAC__STRNCASECMP strncasecmp
2313 #endif
2314         return (0 != eq && (unsigned)(eq-entry->entry) == field_name_length && 0 == FLAC__STRNCASECMP(field_name, entry->entry, field_name_length));
2315 #undef FLAC__STRNCASECMP
2316 }
2317
2318 void hexdump(const char *filename, const FLAC__byte *buf, unsigned bytes, const char *indent)
2319 {
2320         unsigned i, left = bytes;
2321         const FLAC__byte *b = buf;
2322
2323         for(i = 0; i < bytes; i += 16) {
2324                 printf("%s%s%s%08X: "
2325                         "%02X %02X %02X %02X %02X %02X %02X %02X "
2326                         "%02X %02X %02X %02X %02X %02X %02X %02X "
2327                         "%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c\n",
2328                         filename? filename:"", filename? ":":"",
2329                         indent, i,
2330                         left >  0? (unsigned char)b[ 0] : 0,
2331                         left >  1? (unsigned char)b[ 1] : 0,
2332                         left >  2? (unsigned char)b[ 2] : 0,
2333                         left >  3? (unsigned char)b[ 3] : 0,
2334                         left >  4? (unsigned char)b[ 4] : 0,
2335                         left >  5? (unsigned char)b[ 5] : 0,
2336                         left >  6? (unsigned char)b[ 6] : 0,
2337                         left >  7? (unsigned char)b[ 7] : 0,
2338                         left >  8? (unsigned char)b[ 8] : 0,
2339                         left >  9? (unsigned char)b[ 9] : 0,
2340                         left > 10? (unsigned char)b[10] : 0,
2341                         left > 11? (unsigned char)b[11] : 0,
2342                         left > 12? (unsigned char)b[12] : 0,
2343                         left > 13? (unsigned char)b[13] : 0,
2344                         left > 14? (unsigned char)b[14] : 0,
2345                         left > 15? (unsigned char)b[15] : 0,
2346                         (left >  0) ? (isprint(b[ 0]) ? b[ 0] : '.') : ' ',
2347                         (left >  1) ? (isprint(b[ 1]) ? b[ 1] : '.') : ' ',
2348                         (left >  2) ? (isprint(b[ 2]) ? b[ 2] : '.') : ' ',
2349                         (left >  3) ? (isprint(b[ 3]) ? b[ 3] : '.') : ' ',
2350                         (left >  4) ? (isprint(b[ 4]) ? b[ 4] : '.') : ' ',
2351                         (left >  5) ? (isprint(b[ 5]) ? b[ 5] : '.') : ' ',
2352                         (left >  6) ? (isprint(b[ 6]) ? b[ 6] : '.') : ' ',
2353                         (left >  7) ? (isprint(b[ 7]) ? b[ 7] : '.') : ' ',
2354                         (left >  8) ? (isprint(b[ 8]) ? b[ 8] : '.') : ' ',
2355                         (left >  9) ? (isprint(b[ 9]) ? b[ 9] : '.') : ' ',
2356                         (left > 10) ? (isprint(b[10]) ? b[10] : '.') : ' ',
2357                         (left > 11) ? (isprint(b[11]) ? b[11] : '.') : ' ',
2358                         (left > 12) ? (isprint(b[12]) ? b[12] : '.') : ' ',
2359                         (left > 13) ? (isprint(b[13]) ? b[13] : '.') : ' ',
2360                         (left > 14) ? (isprint(b[14]) ? b[14] : '.') : ' ',
2361                         (left > 15) ? (isprint(b[15]) ? b[15] : '.') : ' '
2362                 );
2363                 left -= 16;
2364                 b += 16;
2365    }
2366 }
2367
2368 void undocumented_warning(const char *opt)
2369 {
2370         fprintf(stderr, "WARNING: undocmented option --%s should be used with caution,\n         only for repairing a damaged STREAMINFO block\n", opt);
2371 }