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