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