fix bug #606796 where do_shorthand_operations_on_file() was not checking the needs_wr...
[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 /* There's no stroull() in MSVC6 so we just write a specialized one */
1099 static FLAC__uint64 local__strtoull(const char *src)
1100 {
1101         FLAC__uint64 ret = 0;
1102         int c;
1103         FLAC__ASSERT(0 != src);
1104         while(0 != (c = *src++)) {
1105                 c -= '0';
1106                 if(c >= 0 && c <= 9)
1107                         ret = (ret * 10) + c;
1108                 else
1109                         break;
1110         }
1111         return ret;
1112 }
1113
1114 FLAC__bool parse_uint64(const char *src, FLAC__uint64 *dest)
1115 {
1116         FLAC__ASSERT(0 != src);
1117         if(strlen(src) == 0 || strspn(src, "0123456789") != strlen(src))
1118                 return false;
1119         *dest = local__strtoull(src);
1120         return true;
1121 }
1122
1123 FLAC__bool parse_filename(const char *src, char **dest)
1124 {
1125         if(0 == src || strlen(src) == 0)
1126                 return false;
1127         *dest = strdup(src);
1128         return true;
1129 }
1130
1131 FLAC__bool parse_vorbis_comment_field(const char *field_ref, char **field, char **name, char **value, unsigned *length, const char **violation)
1132 {
1133         static const char * const violations[] = {
1134                 "field name contains invalid character",
1135                 "field contains no '=' character"
1136         };
1137
1138         char *p, *q, *s;
1139
1140         if(0 != field)
1141                 *field = local_strdup(field_ref);
1142
1143         s = local_strdup(field_ref);
1144
1145         if(0 == (p = strchr(s, '='))) {
1146                 free(s);
1147                 *violation = violations[1];
1148                 return false;
1149         }
1150         *p++ = '\0';
1151
1152         for(q = s; *q; q++) {
1153                 if(*q < 0x20 || *q > 0x7d || *q == 0x3d) {
1154                         free(s);
1155                         *violation = violations[0];
1156                         return false;
1157                 }
1158         }
1159
1160         *name = local_strdup(s);
1161         *value = local_strdup(p);
1162         *length = strlen(p);
1163
1164         free(s);
1165         return true;
1166 }
1167
1168 static FLAC__bool parse_vorbis_comment_field_name(const char *field_ref, char **name, const char **violation)
1169 {
1170         static const char * const violations[] = {
1171                 "field name contains invalid character"
1172         };
1173
1174         char *q, *s;
1175
1176         s = local_strdup(field_ref);
1177
1178         for(q = s; *q; q++) {
1179                 if(*q < 0x20 || *q > 0x7d || *q == 0x3d) {
1180                         free(s);
1181                         *violation = violations[0];
1182                         return false;
1183                 }
1184         }
1185
1186         *name = s;
1187
1188         return true;
1189 }
1190
1191 FLAC__bool parse_add_padding(const char *in, unsigned *out)
1192 {
1193         *out = (unsigned)strtoul(in, 0, 10);
1194         return *out < (1u << FLAC__STREAM_METADATA_LENGTH_LEN);
1195 }
1196
1197 FLAC__bool parse_block_number(const char *in, Argument_BlockNumber *out)
1198 {
1199         char *p, *q, *s, *end;
1200         long i;
1201         unsigned entry;
1202
1203         if(*in == '\0')
1204                 return false;
1205
1206         s = local_strdup(in);
1207
1208         /* first count the entries */
1209         for(out->num_entries = 1, p = strchr(s, ','); p; out->num_entries++, p = strchr(++p, ','))
1210                 ;
1211
1212         /* make space */
1213         FLAC__ASSERT(out->num_entries > 0);
1214         if(0 == (out->entries = malloc(sizeof(unsigned) * out->num_entries)))
1215                 die("out of memory allocating space for option list");
1216
1217         /* load 'em up */
1218         entry = 0;
1219         q = s;
1220         while(q) {
1221                 FLAC__ASSERT(entry < out->num_entries);
1222                 if(0 != (p = strchr(q, ',')))
1223                         *p++ = '\0';
1224                 if(!isdigit((int)(*q)) || (i = strtol(q, &end, 10)) < 0 || *end) {
1225                         free(s);
1226                         return false;
1227                 }
1228                 out->entries[entry++] = (unsigned)i;
1229                 q = p;
1230         }
1231         FLAC__ASSERT(entry == out->num_entries);
1232
1233         free(s);
1234         return true;
1235 }
1236
1237 FLAC__bool parse_block_type(const char *in, Argument_BlockType *out)
1238 {
1239         char *p, *q, *r, *s;
1240         unsigned entry;
1241
1242         if(*in == '\0')
1243                 return false;
1244
1245         s = local_strdup(in);
1246
1247         /* first count the entries */
1248         for(out->num_entries = 1, p = strchr(s, ','); p; out->num_entries++, p = strchr(++p, ','))
1249                 ;
1250
1251         /* make space */
1252         FLAC__ASSERT(out->num_entries > 0);
1253         if(0 == (out->entries = malloc(sizeof(Argument_BlockTypeEntry) * out->num_entries)))
1254                 die("out of memory allocating space for option list");
1255
1256         /* load 'em up */
1257         entry = 0;
1258         q = s;
1259         while(q) {
1260                 FLAC__ASSERT(entry < out->num_entries);
1261                 if(0 != (p = strchr(q, ',')))
1262                         *p++ = 0;
1263                 r = strchr(q, ':');
1264                 if(r)
1265                         *r++ = '\0';
1266                 if(0 != r && 0 != strcmp(q, "APPLICATION")) {
1267                         free(s);
1268                         return false;
1269                 }
1270                 if(0 == strcmp(q, "STREAMINFO")) {
1271                         out->entries[entry++].type = FLAC__METADATA_TYPE_STREAMINFO;
1272                 }
1273                 else if(0 == strcmp(q, "PADDING")) {
1274                         out->entries[entry++].type = FLAC__METADATA_TYPE_PADDING;
1275                 }
1276                 else if(0 == strcmp(q, "APPLICATION")) {
1277                         out->entries[entry].type = FLAC__METADATA_TYPE_APPLICATION;
1278                         out->entries[entry].filter_application_by_id = (0 != r);
1279                         if(0 != r) {
1280                                 if(strlen(r) == 4) {
1281                                         strcpy(out->entries[entry].application_id, r);
1282                                 }
1283                                 else if(strlen(r) == 10 && strncmp(r, "0x", 2) == 0 && strspn(r+2, "0123456789ABCDEFabcdef") == 8) {
1284                                         FLAC__uint32 x = strtoul(r+2, 0, 16);
1285                                         out->entries[entry].application_id[3] = (FLAC__byte)(x & 0xff);
1286                                         out->entries[entry].application_id[2] = (FLAC__byte)((x>>=8) & 0xff);
1287                                         out->entries[entry].application_id[1] = (FLAC__byte)((x>>=8) & 0xff);
1288                                         out->entries[entry].application_id[0] = (FLAC__byte)((x>>=8) & 0xff);
1289                                 }
1290                                 else {
1291                                         free(s);
1292                                         return false;
1293                                 }
1294                         }
1295                         entry++;
1296                 }
1297                 else if(0 == strcmp(q, "SEEKTABLE")) {
1298                         out->entries[entry++].type = FLAC__METADATA_TYPE_SEEKTABLE;
1299                 }
1300                 else if(0 == strcmp(q, "VORBIS_COMMENT")) {
1301                         out->entries[entry++].type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
1302                 }
1303                 else {
1304                         free(s);
1305                         return false;
1306                 }
1307                 q = p;
1308         }
1309         FLAC__ASSERT(entry == out->num_entries);
1310
1311         free(s);
1312         return true;
1313 }
1314
1315 FLAC__bool parse_data_format(const char *in, Argument_DataFormat *out)
1316 {
1317         if(0 == strcmp(in, "binary"))
1318                 out->is_binary = true;
1319         else if(0 == strcmp(in, "text"))
1320                 out->is_binary = false;
1321         else
1322                 return false;
1323         return true;
1324 }
1325
1326 FLAC__bool parse_application_data_format(const char *in, FLAC__bool *out)
1327 {
1328         if(0 == strcmp(in, "hexdump"))
1329                 *out = true;
1330         else if(0 == strcmp(in, "text"))
1331                 *out = false;
1332         else
1333                 return false;
1334         return true;
1335 }
1336
1337 FLAC__bool do_operations(const CommandLineOptions *options)
1338 {
1339         FLAC__bool ok = true;
1340
1341         if(options->show_long_help) {
1342                 long_usage(0);
1343         }
1344         if(options->show_version) {
1345                 show_version();
1346         }
1347         else if(options->args.checks.num_major_ops > 0) {
1348                 FLAC__ASSERT(options->args.checks.num_shorthand_ops == 0);
1349                 FLAC__ASSERT(options->args.checks.num_major_ops == 1);
1350                 FLAC__ASSERT(options->args.checks.num_major_ops == options->ops.num_operations);
1351                 ok = do_major_operation(options);
1352         }
1353         else if(options->args.checks.num_shorthand_ops > 0) {
1354                 FLAC__ASSERT(options->args.checks.num_shorthand_ops == options->ops.num_operations);
1355                 ok = do_shorthand_operations(options);
1356         }
1357
1358         return ok;
1359 }
1360
1361 FLAC__bool do_major_operation(const CommandLineOptions *options)
1362 {
1363         unsigned i;
1364         FLAC__bool ok = true;
1365
1366         /*@@@ to die after first error,  v---  add '&& ok' here */
1367         for(i = 0; i < options->num_files; i++)
1368                 ok &= do_major_operation_on_file(options->filenames[i], options);
1369
1370         return ok;
1371 }
1372
1373 FLAC__bool do_major_operation_on_file(const char *filename, const CommandLineOptions *options)
1374 {
1375         FLAC__bool ok = true, needs_write = false;
1376         FLAC__Metadata_Chain *chain = FLAC__metadata_chain_new();
1377
1378         if(0 == chain)
1379                 die("out of memory allocating chain");
1380
1381         if(!FLAC__metadata_chain_read(chain, filename)) {
1382                 fprintf(stderr, "%s: ERROR: reading metadata, status = \"%s\"\n", filename, FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(chain)]);
1383                 return false;
1384         }
1385
1386         switch(options->ops.operations[0].type) {
1387                 case OP__LIST:
1388                         ok = do_major_operation__list(options->prefix_with_filename? filename : 0, chain, options);
1389                         break;
1390                 case OP__APPEND:
1391                         ok = do_major_operation__append(chain, options);
1392                         needs_write = true;
1393                         break;
1394                 case OP__REMOVE:
1395                         ok = do_major_operation__remove(chain, options);
1396                         needs_write = true;
1397                         break;
1398                 case OP__REMOVE_ALL:
1399                         ok = do_major_operation__remove_all(chain, options);
1400                         needs_write = true;
1401                         break;
1402                 case OP__MERGE_PADDING:
1403                         FLAC__metadata_chain_merge_padding(chain);
1404                         needs_write = true;
1405                         break;
1406                 case OP__SORT_PADDING:
1407                         FLAC__metadata_chain_sort_padding(chain);
1408                         needs_write = true;
1409                         break;
1410                 default:
1411                         FLAC__ASSERT(0);
1412                         return false;
1413         }
1414
1415         if(ok && needs_write) {
1416                 if(options->use_padding)
1417                         FLAC__metadata_chain_sort_padding(chain);
1418                 ok = FLAC__metadata_chain_write(chain, options->use_padding, options->preserve_modtime);
1419                 if(!ok)
1420                         fprintf(stderr, "%s: ERROR: writing FLAC file, error = %s\n", filename, FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(chain)]);
1421         }
1422
1423         FLAC__metadata_chain_delete(chain);
1424
1425         return ok;
1426 }
1427
1428 FLAC__bool do_major_operation__list(const char *filename, FLAC__Metadata_Chain *chain, const CommandLineOptions *options)
1429 {
1430         FLAC__Metadata_Iterator *iterator = FLAC__metadata_iterator_new();
1431         FLAC__StreamMetadata *block;
1432         FLAC__bool ok = true;
1433         unsigned block_number;
1434
1435         if(0 == iterator)
1436                 die("out of memory allocating iterator");
1437
1438         FLAC__metadata_iterator_init(iterator, chain);
1439
1440         block_number = 0;
1441         do {
1442                 block = FLAC__metadata_iterator_get_block(iterator);
1443                 ok &= (0 != block);
1444                 if(!ok)
1445                         fprintf(stderr, "%s: ERROR: couldn't get block from chain\n", filename);
1446                 else if(passes_filter(options, FLAC__metadata_iterator_get_block(iterator), block_number))
1447                         write_metadata(filename, block, block_number, options->application_data_format_is_hexdump);
1448                 block_number++;
1449         } while(ok && FLAC__metadata_iterator_next(iterator));
1450
1451         FLAC__metadata_iterator_delete(iterator);
1452
1453         return ok;
1454 }
1455
1456 FLAC__bool do_major_operation__append(FLAC__Metadata_Chain *chain, const CommandLineOptions *options)
1457 {
1458         (void) chain, (void) options;
1459         fprintf(stderr, "ERROR: --append not implemented yet\n"); /*@@@*/
1460         return false;
1461 }
1462
1463 FLAC__bool do_major_operation__remove(FLAC__Metadata_Chain *chain, const CommandLineOptions *options)
1464 {
1465         FLAC__Metadata_Iterator *iterator = FLAC__metadata_iterator_new();
1466         FLAC__bool ok = true;
1467         unsigned block_number;
1468
1469         if(0 == iterator)
1470                 die("out of memory allocating iterator");
1471
1472         FLAC__metadata_iterator_init(iterator, chain);
1473
1474         block_number = 0;
1475         while(ok && FLAC__metadata_iterator_next(iterator)) {
1476                 block_number++;
1477                 if(passes_filter(options, FLAC__metadata_iterator_get_block(iterator), block_number)) {
1478                         ok &= FLAC__metadata_iterator_delete_block(iterator, options->use_padding);
1479                         if(options->use_padding)
1480                                 ok &= FLAC__metadata_iterator_next(iterator);
1481                 }
1482         }
1483
1484         FLAC__metadata_iterator_delete(iterator);
1485
1486         return ok;
1487 }
1488
1489 FLAC__bool do_major_operation__remove_all(FLAC__Metadata_Chain *chain, const CommandLineOptions *options)
1490 {
1491         FLAC__Metadata_Iterator *iterator = FLAC__metadata_iterator_new();
1492         FLAC__bool ok = true;
1493
1494         if(0 == iterator)
1495                 die("out of memory allocating iterator");
1496
1497         FLAC__metadata_iterator_init(iterator, chain);
1498
1499         while(ok && FLAC__metadata_iterator_next(iterator)) {
1500                 ok &= FLAC__metadata_iterator_delete_block(iterator, options->use_padding);
1501                 if(options->use_padding)
1502                         ok &= FLAC__metadata_iterator_next(iterator);
1503         }
1504
1505         FLAC__metadata_iterator_delete(iterator);
1506
1507         return ok;
1508 }
1509
1510 FLAC__bool do_shorthand_operations(const CommandLineOptions *options)
1511 {
1512         unsigned i;
1513         FLAC__bool ok = true;
1514
1515         /*@@@ to die after first error,  v---  add '&& ok' here */
1516         for(i = 0; i < options->num_files; i++)
1517                 ok &= do_shorthand_operations_on_file(options->filenames[i], options);
1518
1519         return ok;
1520 }
1521
1522 FLAC__bool do_shorthand_operations_on_file(const char *filename, const CommandLineOptions *options)
1523 {
1524         unsigned i;
1525         FLAC__bool ok = true, needs_write = false;
1526         FLAC__Metadata_Chain *chain = FLAC__metadata_chain_new();
1527
1528         if(0 == chain)
1529                 die("out of memory allocating chain");
1530
1531         if(!FLAC__metadata_chain_read(chain, filename)) {
1532                 fprintf(stderr, "%s: ERROR: reading metadata, status = \"%s\"\n", filename, FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(chain)]);
1533                 return false;
1534         }
1535
1536         for(i = 0; i < options->ops.num_operations && ok; i++)
1537                 ok &= do_shorthand_operation(options->prefix_with_filename? filename : 0, chain, &options->ops.operations[i], &needs_write, options->utf8_convert);
1538
1539         if(ok && needs_write) {
1540                 if(options->use_padding)
1541                         FLAC__metadata_chain_sort_padding(chain);
1542                 ok = FLAC__metadata_chain_write(chain, options->use_padding, options->preserve_modtime);
1543                 if(!ok)
1544                         fprintf(stderr, "%s: ERROR: writing FLAC file, error = %s\n", filename, FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(chain)]);
1545         }
1546
1547         FLAC__metadata_chain_delete(chain);
1548
1549         return ok;
1550 }
1551
1552 FLAC__bool do_shorthand_operation(const char *filename, FLAC__Metadata_Chain *chain, const Operation *operation, FLAC__bool *needs_write, FLAC__bool utf8_convert)
1553 {
1554         FLAC__bool ok = true;
1555
1556         switch(operation->type) {
1557                 case OP__SHOW_MD5SUM:
1558                 case OP__SHOW_MIN_BLOCKSIZE:
1559                 case OP__SHOW_MAX_BLOCKSIZE:
1560                 case OP__SHOW_MIN_FRAMESIZE:
1561                 case OP__SHOW_MAX_FRAMESIZE:
1562                 case OP__SHOW_SAMPLE_RATE:
1563                 case OP__SHOW_CHANNELS:
1564                 case OP__SHOW_BPS:
1565                 case OP__SHOW_TOTAL_SAMPLES:
1566                 case OP__SET_MD5SUM:
1567                 case OP__SET_MIN_BLOCKSIZE:
1568                 case OP__SET_MAX_BLOCKSIZE:
1569                 case OP__SET_MIN_FRAMESIZE:
1570                 case OP__SET_MAX_FRAMESIZE:
1571                 case OP__SET_SAMPLE_RATE:
1572                 case OP__SET_CHANNELS:
1573                 case OP__SET_BPS:
1574                 case OP__SET_TOTAL_SAMPLES:
1575                         ok = do_shorthand_operation__streaminfo(filename, chain, operation, needs_write);
1576                         break;
1577                 case OP__SHOW_VC_VENDOR:
1578                 case OP__SHOW_VC_FIELD:
1579                 case OP__REMOVE_VC_ALL:
1580                 case OP__REMOVE_VC_FIELD:
1581                 case OP__REMOVE_VC_FIRSTFIELD:
1582                 case OP__SET_VC_FIELD:
1583                 case OP__IMPORT_VC_FROM:
1584                 case OP__EXPORT_VC_TO:
1585                         ok = do_shorthand_operation__vorbis_comment(filename, chain, operation, needs_write, !utf8_convert);
1586                         break;
1587                 case OP__ADD_PADDING:
1588                         ok = do_shorthand_operation__add_padding(filename, chain, operation->argument.add_padding.length, needs_write);
1589                         break;
1590                 default:
1591                         ok = false;
1592                         FLAC__ASSERT(0);
1593                         break;
1594         };
1595
1596         return ok;
1597 }
1598
1599 FLAC__bool do_shorthand_operation__add_padding(const char *filename, FLAC__Metadata_Chain *chain, unsigned length, FLAC__bool *needs_write)
1600 {
1601         FLAC__StreamMetadata *padding = 0;
1602         FLAC__Metadata_Iterator *iterator = FLAC__metadata_iterator_new();
1603
1604         if(0 == iterator)
1605                 die("out of memory allocating iterator");
1606
1607         FLAC__metadata_iterator_init(iterator, chain);
1608
1609         while(FLAC__metadata_iterator_next(iterator))
1610                 ;
1611
1612         padding = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING);
1613         if(0 == padding)
1614                 die("out of memory allocating PADDING block");
1615
1616         padding->length = length;
1617
1618         if(!FLAC__metadata_iterator_insert_block_after(iterator, padding)) {
1619                 fprintf(stderr, "%s: ERROR: adding new PADDING block to metadata, status =\"%s\"\n", filename, FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(chain)]);
1620                 FLAC__metadata_object_delete(padding);
1621                 return false;
1622         }
1623
1624         *needs_write = true;
1625         return true;
1626 }
1627
1628 FLAC__bool do_shorthand_operation__streaminfo(const char *filename, FLAC__Metadata_Chain *chain, const Operation *operation, FLAC__bool *needs_write)
1629 {
1630         unsigned i;
1631         FLAC__bool ok = true;
1632         FLAC__StreamMetadata *block;
1633         FLAC__Metadata_Iterator *iterator = FLAC__metadata_iterator_new();
1634
1635         if(0 == iterator)
1636                 die("out of memory allocating iterator");
1637
1638         FLAC__metadata_iterator_init(iterator, chain);
1639
1640         block = FLAC__metadata_iterator_get_block(iterator);
1641
1642         FLAC__ASSERT(0 != block);
1643         FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_STREAMINFO);
1644
1645         if(0 != filename)
1646                 printf("%s:", filename);
1647
1648         switch(operation->type) {
1649                 case OP__SHOW_MD5SUM:
1650                         for(i = 0; i < 16; i++)
1651                                 printf("%02x", block->data.stream_info.md5sum[i]);
1652                         printf("\n");
1653                         break;
1654                 case OP__SHOW_MIN_BLOCKSIZE:
1655                         printf("%u\n", block->data.stream_info.min_blocksize);
1656                         break;
1657                 case OP__SHOW_MAX_BLOCKSIZE:
1658                         printf("%u\n", block->data.stream_info.max_blocksize);
1659                         break;
1660                 case OP__SHOW_MIN_FRAMESIZE:
1661                         printf("%u\n", block->data.stream_info.min_framesize);
1662                         break;
1663                 case OP__SHOW_MAX_FRAMESIZE:
1664                         printf("%u\n", block->data.stream_info.max_framesize);
1665                         break;
1666                 case OP__SHOW_SAMPLE_RATE:
1667                         printf("%u\n", block->data.stream_info.sample_rate);
1668                         break;
1669                 case OP__SHOW_CHANNELS:
1670                         printf("%u\n", block->data.stream_info.channels);
1671                         break;
1672                 case OP__SHOW_BPS:
1673                         printf("%u\n", block->data.stream_info.bits_per_sample);
1674                         break;
1675                 case OP__SHOW_TOTAL_SAMPLES:
1676                         printf("%llu\n", block->data.stream_info.total_samples);
1677                         break;
1678                 case OP__SET_MD5SUM:
1679                         memcpy(block->data.stream_info.md5sum, operation->argument.streaminfo_md5.value, 16);
1680                         *needs_write = true;
1681                         break;
1682                 case OP__SET_MIN_BLOCKSIZE:
1683                         block->data.stream_info.min_blocksize = operation->argument.streaminfo_uint32.value;
1684                         *needs_write = true;
1685                         break;
1686                 case OP__SET_MAX_BLOCKSIZE:
1687                         block->data.stream_info.max_blocksize = operation->argument.streaminfo_uint32.value;
1688                         *needs_write = true;
1689                         break;
1690                 case OP__SET_MIN_FRAMESIZE:
1691                         block->data.stream_info.min_framesize = operation->argument.streaminfo_uint32.value;
1692                         *needs_write = true;
1693                         break;
1694                 case OP__SET_MAX_FRAMESIZE:
1695                         block->data.stream_info.max_framesize = operation->argument.streaminfo_uint32.value;
1696                         *needs_write = true;
1697                         break;
1698                 case OP__SET_SAMPLE_RATE:
1699                         block->data.stream_info.sample_rate = operation->argument.streaminfo_uint32.value;
1700                         *needs_write = true;
1701                         break;
1702                 case OP__SET_CHANNELS:
1703                         block->data.stream_info.channels = operation->argument.streaminfo_uint32.value;
1704                         *needs_write = true;
1705                         break;
1706                 case OP__SET_BPS:
1707                         block->data.stream_info.bits_per_sample = operation->argument.streaminfo_uint32.value;
1708                         *needs_write = true;
1709                         break;
1710                 case OP__SET_TOTAL_SAMPLES:
1711                         block->data.stream_info.total_samples = operation->argument.streaminfo_uint64.value;
1712                         *needs_write = true;
1713                         break;
1714                 default:
1715                         ok = false;
1716                         FLAC__ASSERT(0);
1717                         break;
1718         };
1719
1720         FLAC__metadata_iterator_delete(iterator);
1721
1722         return ok;
1723 }
1724
1725 FLAC__bool do_shorthand_operation__vorbis_comment(const char *filename, FLAC__Metadata_Chain *chain, const Operation *operation, FLAC__bool *needs_write, FLAC__bool raw)
1726 {
1727         FLAC__bool ok = true, found_vc_block = false;
1728         FLAC__StreamMetadata *block = 0;
1729         FLAC__Metadata_Iterator *iterator = FLAC__metadata_iterator_new();
1730
1731         if(0 == iterator)
1732                 die("out of memory allocating iterator");
1733
1734         FLAC__metadata_iterator_init(iterator, chain);
1735
1736         do {
1737                 block = FLAC__metadata_iterator_get_block(iterator);
1738                 if(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT)
1739                         found_vc_block = true;
1740         } while(!found_vc_block && FLAC__metadata_iterator_next(iterator));
1741
1742         /* create a new block if necessary */
1743         if(!found_vc_block && operation->type == OP__SET_VC_FIELD) {
1744                 block = FLAC__metadata_object_new(FLAC__METADATA_TYPE_VORBIS_COMMENT);
1745                 if(0 == block)
1746                         die("out of memory allocating VORBIS_COMMENT block");
1747                 while(FLAC__metadata_iterator_next(iterator))
1748                         ;
1749                 if(!FLAC__metadata_iterator_insert_block_after(iterator, block)) {
1750                         fprintf(stderr, "%s: ERROR: adding new VORBIS_COMMENT block to metadata, status =\"%s\"\n", filename, FLAC__Metadata_ChainStatusString[FLAC__metadata_chain_status(chain)]);
1751                         return false;
1752                 }
1753                 /* iterator is left pointing to new block */
1754                 FLAC__ASSERT(FLAC__metadata_iterator_get_block(iterator) == block);
1755         }
1756
1757         FLAC__ASSERT(0 != block);
1758         FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
1759
1760         switch(operation->type) {
1761                 case OP__SHOW_VC_VENDOR:
1762                         write_vc_field(filename, &block->data.vorbis_comment.vendor_string, raw, stdout);
1763                         break;
1764                 case OP__SHOW_VC_FIELD:
1765                         write_vc_fields(filename, operation->argument.vc_field_name.value, block->data.vorbis_comment.comments, block->data.vorbis_comment.num_comments, raw, stdout);
1766                         break;
1767                 case OP__REMOVE_VC_ALL:
1768                         ok = remove_vc_all(filename, block, needs_write);
1769                         break;
1770                 case OP__REMOVE_VC_FIELD:
1771                         ok = remove_vc_field(block, operation->argument.vc_field_name.value, needs_write);
1772                         break;
1773                 case OP__REMOVE_VC_FIRSTFIELD:
1774                         ok = remove_vc_firstfield(filename, block, operation->argument.vc_field_name.value, needs_write);
1775                         break;
1776                 case OP__SET_VC_FIELD:
1777                         ok = set_vc_field(filename, block, &operation->argument.vc_field, needs_write, raw);
1778                         break;
1779                 case OP__IMPORT_VC_FROM:
1780                         ok = import_vc_from(filename, block, &operation->argument.vc_filename, needs_write, raw);
1781                         break;
1782                 case OP__EXPORT_VC_TO:
1783                         ok = export_vc_to(filename, block, &operation->argument.vc_filename, raw);
1784                         break;
1785                 default:
1786                         ok = false;
1787                         FLAC__ASSERT(0);
1788                         break;
1789         };
1790
1791         return ok;
1792 }
1793
1794 FLAC__bool passes_filter(const CommandLineOptions *options, const FLAC__StreamMetadata *block, unsigned block_number)
1795 {
1796         unsigned i, j;
1797         FLAC__bool matches_number = false, matches_type = false;
1798         FLAC__bool has_block_number_arg = false;
1799
1800         for(i = 0; i < options->args.num_arguments; i++) {
1801                 if(options->args.arguments[i].type == ARG__BLOCK_TYPE || options->args.arguments[i].type == ARG__EXCEPT_BLOCK_TYPE) {
1802                         for(j = 0; j < options->args.arguments[i].value.block_type.num_entries; j++) {
1803                                 if(options->args.arguments[i].value.block_type.entries[j].type == block->type) {
1804                                         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))
1805                                                 matches_type = true;
1806                                 }
1807                         }
1808                 }
1809                 else if(options->args.arguments[i].type == ARG__BLOCK_NUMBER) {
1810                         has_block_number_arg = true;
1811                         for(j = 0; j < options->args.arguments[i].value.block_number.num_entries; j++) {
1812                                 if(options->args.arguments[i].value.block_number.entries[j] == block_number)
1813                                         matches_number = true;
1814                         }
1815                 }
1816         }
1817
1818         if(!has_block_number_arg)
1819                 matches_number = true;
1820
1821         if(options->args.checks.has_block_type) {
1822                 FLAC__ASSERT(!options->args.checks.has_except_block_type);
1823         }
1824         else if(options->args.checks.has_except_block_type)
1825                 matches_type = !matches_type;
1826         else
1827                 matches_type = true;
1828
1829         return matches_number && matches_type;
1830 }
1831
1832 void write_metadata(const char *filename, FLAC__StreamMetadata *block, unsigned block_number, FLAC__bool hexdump_application)
1833 {
1834         unsigned i;
1835
1836 /*@@@ yuck, should do this with a varargs function or something: */
1837 #define PPR if(filename)printf("%s:",filename);
1838         PPR; printf("METADATA block #%u\n", block_number);
1839         PPR; printf("  type: %u (%s)\n", (unsigned)block->type, block->type<=FLAC__METADATA_TYPE_VORBIS_COMMENT? FLAC__MetadataTypeString[block->type] : "UNKNOWN");
1840         PPR; printf("  is last: %s\n", block->is_last? "true":"false");
1841         PPR; printf("  length: %u\n", block->length);
1842
1843         switch(block->type) {
1844                 case FLAC__METADATA_TYPE_STREAMINFO:
1845                         PPR; printf("  minumum blocksize: %u samples\n", block->data.stream_info.min_blocksize);
1846                         PPR; printf("  maximum blocksize: %u samples\n", block->data.stream_info.max_blocksize);
1847                         PPR; printf("  minimum framesize: %u bytes\n", block->data.stream_info.min_framesize);
1848                         PPR; printf("  maximum framesize: %u bytes\n", block->data.stream_info.max_framesize);
1849                         PPR; printf("  sample_rate: %u Hz\n", block->data.stream_info.sample_rate);
1850                         PPR; printf("  channels: %u\n", block->data.stream_info.channels);
1851                         PPR; printf("  bits-per-sample: %u\n", block->data.stream_info.bits_per_sample);
1852                         PPR; printf("  total samples: %llu\n", block->data.stream_info.total_samples);
1853                         PPR; printf("  MD5 signature: ");
1854                         for(i = 0; i < 16; i++) {
1855                                 printf("%02x", (unsigned)block->data.stream_info.md5sum[i]);
1856                         }
1857                         printf("\n");
1858                         break;
1859                 case FLAC__METADATA_TYPE_PADDING:
1860                         /* nothing to print */
1861                         break;
1862                 case FLAC__METADATA_TYPE_APPLICATION:
1863                         PPR; printf("  application ID: ");
1864                         for(i = 0; i < 4; i++) {
1865                                 PPR; printf("%02x", block->data.application.id[i]);
1866                         }
1867                         PPR; printf("\n");
1868                         PPR; printf("  data contents:\n");
1869                         if(0 != block->data.application.data) {
1870                                 if(hexdump_application)
1871                                         hexdump(filename, block->data.application.data, block->length - FLAC__STREAM_METADATA_HEADER_LENGTH, "    ");
1872                                 else
1873                                         (void) fwrite(block->data.application.data, 1, block->length - FLAC__STREAM_METADATA_HEADER_LENGTH, stdout);
1874                         }
1875                         break;
1876                 case FLAC__METADATA_TYPE_SEEKTABLE:
1877                         PPR; printf("  seek points: %u\n", block->data.seek_table.num_points);
1878                         for(i = 0; i < block->data.seek_table.num_points; i++) {
1879                                 if(block->data.seek_table.points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
1880                                         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);
1881                                 }
1882                                 else {
1883                                         PPR; printf("    point %d: PLACEHOLDER\n", i);
1884                                 }
1885                         }
1886                         break;
1887                 case FLAC__METADATA_TYPE_VORBIS_COMMENT:
1888                         PPR; printf("  vendor string: ");
1889                         if(0 != block->data.vorbis_comment.vendor_string.entry)
1890                                 fwrite(block->data.vorbis_comment.vendor_string.entry, 1, block->data.vorbis_comment.vendor_string.length, stdout);
1891                         printf("\n");
1892                         PPR; printf("  comments: %u\n", block->data.vorbis_comment.num_comments);
1893                         for(i = 0; i < block->data.vorbis_comment.num_comments; i++) {
1894                                 PPR; printf("    comment[%u]: ", i);
1895                                 fwrite(block->data.vorbis_comment.comments[i].entry, 1, block->data.vorbis_comment.comments[i].length, stdout);
1896                                 printf("\n");
1897                         }
1898                         break;
1899                 default:
1900                         PPR; printf("SKIPPING block of unknown type\n");
1901                         break;
1902         }
1903 #undef PPR
1904 }
1905
1906 void write_vc_field(const char *filename, const FLAC__StreamMetadata_VorbisComment_Entry *entry, FLAC__bool raw, FILE *f)
1907 {
1908         if(0 != entry->entry) {
1909                 char *converted;
1910
1911                 if(filename)
1912                         fprintf(f, "%s:", filename);
1913
1914                 if(!raw && utf8_decode(entry->entry, &converted) >= 0) {
1915                         (void) fwrite(converted, 1, strlen(converted), f);
1916                         free(converted);
1917                 }
1918                 else {
1919                         (void) fwrite(entry->entry, 1, entry->length, f);
1920                 }
1921         }
1922
1923         fprintf(f, "\n");
1924 }
1925
1926 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)
1927 {
1928         unsigned i;
1929         const unsigned field_name_length = (0 != field_name)? strlen(field_name) : 0;
1930
1931         for(i = 0; i < num_entries; i++) {
1932                 if(0 == field_name || field_name_matches_entry(field_name, field_name_length, entry + i))
1933                         write_vc_field(filename, entry + i, raw, f);
1934         }
1935 }
1936
1937 FLAC__bool remove_vc_all(const char *filename, FLAC__StreamMetadata *block, FLAC__bool *needs_write)
1938 {
1939         FLAC__ASSERT(0 != block);
1940         FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
1941         FLAC__ASSERT(0 != needs_write);
1942
1943         if(0 != block->data.vorbis_comment.comments) {
1944                 FLAC__ASSERT(block->data.vorbis_comment.num_comments > 0);
1945                 if(!FLAC__metadata_object_vorbiscomment_resize_comments(block, 0)) {
1946                         fprintf(stderr, "%s: ERROR: memory allocation failure\n", filename);
1947                         return false;
1948                 }
1949                 *needs_write = true;
1950         }
1951         else {
1952                 FLAC__ASSERT(block->data.vorbis_comment.num_comments == 0);
1953         }
1954
1955         return true;
1956 }
1957
1958 FLAC__bool remove_vc_field(FLAC__StreamMetadata *block, const char *field_name, FLAC__bool *needs_write)
1959 {
1960         FLAC__bool ok = true;
1961         const unsigned field_name_length = strlen(field_name);
1962         int i;
1963
1964         FLAC__ASSERT(0 != block);
1965         FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
1966         FLAC__ASSERT(0 != needs_write);
1967
1968         /* must delete from end to start otherwise it will interfere with our iteration */
1969         for(i = (int)block->data.vorbis_comment.num_comments - 1; ok && i >= 0; i--) {
1970                 if(field_name_matches_entry(field_name, field_name_length, block->data.vorbis_comment.comments + i)) {
1971                         ok &= FLAC__metadata_object_vorbiscomment_delete_comment(block, (unsigned)i);
1972                         if(ok)
1973                                 *needs_write = true;
1974                 }
1975         }
1976
1977         return ok;
1978 }
1979
1980 FLAC__bool remove_vc_firstfield(const char *filename, FLAC__StreamMetadata *block, const char *field_name, FLAC__bool *needs_write)
1981 {
1982         const unsigned field_name_length = strlen(field_name);
1983         unsigned i;
1984
1985         FLAC__ASSERT(0 != block);
1986         FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
1987         FLAC__ASSERT(0 != needs_write);
1988
1989         for(i = 0; i < block->data.vorbis_comment.num_comments; i++) {
1990                 if(field_name_matches_entry(field_name, field_name_length, block->data.vorbis_comment.comments + i)) {
1991                         if(!FLAC__metadata_object_vorbiscomment_delete_comment(block, (unsigned)i)) {
1992                                 fprintf(stderr, "%s: ERROR: memory allocation failure\n", filename);
1993                                 return false;
1994                         }
1995                         else
1996                                 *needs_write = true;
1997                         break;
1998                 }
1999         }
2000
2001         return true;
2002 }
2003
2004 FLAC__bool set_vc_field(const char *filename, FLAC__StreamMetadata *block, const Argument_VcField *field, FLAC__bool *needs_write, FLAC__bool raw)
2005 {
2006         FLAC__StreamMetadata_VorbisComment_Entry entry;
2007         char *converted;
2008         FLAC__bool needs_free = false;
2009
2010         FLAC__ASSERT(0 != block);
2011         FLAC__ASSERT(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT);
2012         FLAC__ASSERT(0 != field);
2013         FLAC__ASSERT(0 != needs_write);
2014
2015         if(raw) {
2016                 entry.entry = field->field;
2017         }
2018         else if(utf8_encode(field->field, &converted) >= 0) {
2019                 entry.entry = converted;
2020                 needs_free = true;
2021         }
2022         else {
2023                 fprintf(stderr, "%s: ERROR: couldn't convert comment to UTF-8\n", filename);
2024                 return false;
2025         }
2026
2027         entry.length = strlen(entry.entry);
2028
2029         if(!FLAC__metadata_object_vorbiscomment_insert_comment(block, block->data.vorbis_comment.num_comments, entry, /*copy=*/true)) {
2030                 if(needs_free)
2031                         free(converted);
2032                 fprintf(stderr, "%s: ERROR: memory allocation failure\n", filename);
2033                 return false;
2034         }
2035         else {
2036                 *needs_write = true;
2037                 if(needs_free)
2038                         free(converted);
2039                 return true;
2040         }
2041 }
2042
2043 FLAC__bool import_vc_from(const char *filename, FLAC__StreamMetadata *block, const Argument_VcFilename *vc_filename, FLAC__bool *needs_write, FLAC__bool raw)
2044 {
2045         FILE *f;
2046         char line[65536];
2047         FLAC__bool ret;
2048
2049         if(0 == vc_filename->value || strlen(vc_filename->value) == 0) {
2050                 fprintf(stderr, "%s: ERROR: empty import file name\n", filename);
2051                 return false;
2052         }
2053         if(0 == strcmp(vc_filename->value, "-"))
2054                 f = stdin;
2055         else
2056                 f = fopen(vc_filename->value, "r");
2057
2058         if(0 == f) {
2059                 fprintf(stderr, "%s: ERROR: can't open import file %s\n", filename, vc_filename->value);
2060                 return false;
2061         }
2062
2063         ret = true;
2064         while(ret && !feof(f)) {
2065                 fgets(line, sizeof(line), f);
2066                 if(!feof(f)) {
2067                         char *p = strchr(line, '\n');
2068                         if(0 == p) {
2069                                 fprintf(stderr, "%s: ERROR: line too long, aborting\n", vc_filename->value);
2070                                 ret = false;
2071                         }
2072                         else {
2073                                 const char *violation;
2074                                 Argument_VcField field;
2075                                 *p = '\0';
2076                                 memset(&field, 0, sizeof(Argument_VcField));
2077                                 if(!parse_vorbis_comment_field(line, &field.field, &field.field_name, &field.field_value, &field.field_value_length, &violation)) {
2078                                         FLAC__ASSERT(0 != violation);
2079                                         fprintf(stderr, "%s: ERROR: malformed vorbis comment field \"%s\",\n       %s\n", vc_filename->value, line, violation);
2080                                         ret = false;
2081                                 }
2082                                 else {
2083                                         ret = set_vc_field(filename, block, &field, needs_write, raw);
2084                                 }
2085                                 if(0 != field.field)
2086                                         free(field.field);
2087                                 if(0 != field.field_name)
2088                                         free(field.field_name);
2089                                 if(0 != field.field_value)
2090                                         free(field.field_value);
2091                         }
2092                 }
2093         };
2094
2095         if(f != stdin)
2096                 fclose(f);
2097         return ret;
2098 }
2099
2100 FLAC__bool export_vc_to(const char *filename, FLAC__StreamMetadata *block, const Argument_VcFilename *vc_filename, FLAC__bool raw)
2101 {
2102         FILE *f;
2103         FLAC__bool ret;
2104
2105         if(0 == vc_filename->value || strlen(vc_filename->value) == 0) {
2106                 fprintf(stderr, "%s: ERROR: empty export file name\n", filename);
2107                 return false;
2108         }
2109         if(0 == strcmp(vc_filename->value, "-"))
2110                 f = stdout;
2111         else
2112                 f = fopen(vc_filename->value, "w");
2113
2114         if(0 == f) {
2115                 fprintf(stderr, "%s: ERROR: can't open export file %s\n", filename, vc_filename->value);
2116                 return false;
2117         }
2118
2119         ret = true;
2120
2121         write_vc_fields(0, 0, block->data.vorbis_comment.comments, block->data.vorbis_comment.num_comments, raw, f);
2122
2123         if(f != stdout)
2124                 fclose(f);
2125         return ret;
2126 }
2127
2128 FLAC__bool field_name_matches_entry(const char *field_name, unsigned field_name_length, const FLAC__StreamMetadata_VorbisComment_Entry *entry)
2129 {
2130         const FLAC__byte *eq = memchr(entry->entry, '=', entry->length);
2131 #if defined _MSC_VER || defined __MINGW32__
2132 #define FLAC__STRNCASECMP strnicmp
2133 #else
2134 #define FLAC__STRNCASECMP strncasecmp
2135 #endif
2136         return (0 != eq && (unsigned)(eq-entry->entry) == field_name_length && 0 == FLAC__STRNCASECMP(field_name, entry->entry, field_name_length));
2137 #undef FLAC__STRNCASECMP
2138 }
2139
2140 void hexdump(const char *filename, const FLAC__byte *buf, unsigned bytes, const char *indent)
2141 {
2142         unsigned i, left = bytes;
2143         const FLAC__byte *b = buf;
2144
2145         for(i = 0; i < bytes; i += 16) {
2146                 printf("%s%s%s%08X: "
2147                         "%02X %02X %02X %02X %02X %02X %02X %02X "
2148                         "%02X %02X %02X %02X %02X %02X %02X %02X "
2149                         "%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c\n",
2150                         filename? filename:"", filename? ":":"",
2151                         indent, i,
2152                         left >  0? (unsigned char)b[ 0] : 0,
2153                         left >  1? (unsigned char)b[ 1] : 0,
2154                         left >  2? (unsigned char)b[ 2] : 0,
2155                         left >  3? (unsigned char)b[ 3] : 0,
2156                         left >  4? (unsigned char)b[ 4] : 0,
2157                         left >  5? (unsigned char)b[ 5] : 0,
2158                         left >  6? (unsigned char)b[ 6] : 0,
2159                         left >  7? (unsigned char)b[ 7] : 0,
2160                         left >  8? (unsigned char)b[ 8] : 0,
2161                         left >  9? (unsigned char)b[ 9] : 0,
2162                         left > 10? (unsigned char)b[10] : 0,
2163                         left > 11? (unsigned char)b[11] : 0,
2164                         left > 12? (unsigned char)b[12] : 0,
2165                         left > 13? (unsigned char)b[13] : 0,
2166                         left > 14? (unsigned char)b[14] : 0,
2167                         left > 15? (unsigned char)b[15] : 0,
2168                         (left >  0) ? (isprint(b[ 0]) ? b[ 0] : '.') : ' ',
2169                         (left >  1) ? (isprint(b[ 1]) ? b[ 1] : '.') : ' ',
2170                         (left >  2) ? (isprint(b[ 2]) ? b[ 2] : '.') : ' ',
2171                         (left >  3) ? (isprint(b[ 3]) ? b[ 3] : '.') : ' ',
2172                         (left >  4) ? (isprint(b[ 4]) ? b[ 4] : '.') : ' ',
2173                         (left >  5) ? (isprint(b[ 5]) ? b[ 5] : '.') : ' ',
2174                         (left >  6) ? (isprint(b[ 6]) ? b[ 6] : '.') : ' ',
2175                         (left >  7) ? (isprint(b[ 7]) ? b[ 7] : '.') : ' ',
2176                         (left >  8) ? (isprint(b[ 8]) ? b[ 8] : '.') : ' ',
2177                         (left >  9) ? (isprint(b[ 9]) ? b[ 9] : '.') : ' ',
2178                         (left > 10) ? (isprint(b[10]) ? b[10] : '.') : ' ',
2179                         (left > 11) ? (isprint(b[11]) ? b[11] : '.') : ' ',
2180                         (left > 12) ? (isprint(b[12]) ? b[12] : '.') : ' ',
2181                         (left > 13) ? (isprint(b[13]) ? b[13] : '.') : ' ',
2182                         (left > 14) ? (isprint(b[14]) ? b[14] : '.') : ' ',
2183                         (left > 15) ? (isprint(b[15]) ? b[15] : '.') : ' '
2184                 );
2185                 left -= 16;
2186                 b += 16;
2187    }
2188 }
2189
2190 void undocumented_warning(const char *opt)
2191 {
2192         fprintf(stderr, "WARNING: undocmented option --%s should be used with caution,\n         only for repairing a damaged STREAMINFO block\n", opt);
2193 }