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