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