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