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