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