]> git.sesse.net Git - ffmpeg/blob - ffprobe.c
ffprobe: add INI writer
[ffmpeg] / ffprobe.c
1 /*
2  * Copyright (c) 2007-2010 Stefano Sabatini
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 /**
22  * @file
23  * simple media prober based on the FFmpeg libraries
24  */
25
26 #include "config.h"
27 #include "version.h"
28
29 #include "libavformat/avformat.h"
30 #include "libavcodec/avcodec.h"
31 #include "libavutil/avstring.h"
32 #include "libavutil/bprint.h"
33 #include "libavutil/opt.h"
34 #include "libavutil/pixdesc.h"
35 #include "libavutil/dict.h"
36 #include "libavutil/timecode.h"
37 #include "libavdevice/avdevice.h"
38 #include "libswscale/swscale.h"
39 #include "libswresample/swresample.h"
40 #include "libpostproc/postprocess.h"
41 #include "cmdutils.h"
42
43 const char program_name[] = "ffprobe";
44 const int program_birth_year = 2007;
45
46 static int do_count_frames = 0;
47 static int do_count_packets = 0;
48 static int do_read_frames  = 0;
49 static int do_read_packets = 0;
50 static int do_show_error   = 0;
51 static int do_show_format  = 0;
52 static int do_show_frames  = 0;
53 static AVDictionary *fmt_entries_to_show = NULL;
54 static int do_show_packets = 0;
55 static int do_show_streams = 0;
56 static int do_show_program_version  = 0;
57 static int do_show_library_versions = 0;
58
59 static int show_value_unit              = 0;
60 static int use_value_prefix             = 0;
61 static int use_byte_value_binary_prefix = 0;
62 static int use_value_sexagesimal_format = 0;
63 static int show_private_data            = 1;
64
65 static char *print_format;
66
67 static const OptionDef options[];
68
69 /* FFprobe context */
70 static const char *input_filename;
71 static AVInputFormat *iformat = NULL;
72
73 static const char *const binary_unit_prefixes [] = { "", "Ki", "Mi", "Gi", "Ti", "Pi" };
74 static const char *const decimal_unit_prefixes[] = { "", "K" , "M" , "G" , "T" , "P"  };
75
76 static const char unit_second_str[]         = "s"    ;
77 static const char unit_hertz_str[]          = "Hz"   ;
78 static const char unit_byte_str[]           = "byte" ;
79 static const char unit_bit_per_second_str[] = "bit/s";
80 static uint64_t *nb_streams_packets;
81 static uint64_t *nb_streams_frames;
82
83 void av_noreturn exit_program(int ret)
84 {
85     av_dict_free(&fmt_entries_to_show);
86     exit(ret);
87 }
88
89 struct unit_value {
90     union { double d; long long int i; } val;
91     const char *unit;
92 };
93
94 static char *value_string(char *buf, int buf_size, struct unit_value uv)
95 {
96     double vald;
97     int show_float = 0;
98
99     if (uv.unit == unit_second_str) {
100         vald = uv.val.d;
101         show_float = 1;
102     } else {
103         vald = uv.val.i;
104     }
105
106     if (uv.unit == unit_second_str && use_value_sexagesimal_format) {
107         double secs;
108         int hours, mins;
109         secs  = vald;
110         mins  = (int)secs / 60;
111         secs  = secs - mins * 60;
112         hours = mins / 60;
113         mins %= 60;
114         snprintf(buf, buf_size, "%d:%02d:%09.6f", hours, mins, secs);
115     } else {
116         const char *prefix_string = "";
117         int l;
118
119         if (use_value_prefix && vald > 1) {
120             long long int index;
121
122             if (uv.unit == unit_byte_str && use_byte_value_binary_prefix) {
123                 index = (long long int) (log(vald)/log(2)) / 10;
124                 index = av_clip(index, 0, FF_ARRAY_ELEMS(binary_unit_prefixes) - 1);
125                 vald /= pow(2, index * 10);
126                 prefix_string = binary_unit_prefixes[index];
127             } else {
128                 index = (long long int) (log10(vald)) / 3;
129                 index = av_clip(index, 0, FF_ARRAY_ELEMS(decimal_unit_prefixes) - 1);
130                 vald /= pow(10, index * 3);
131                 prefix_string = decimal_unit_prefixes[index];
132             }
133         }
134
135         if (show_float || (use_value_prefix && vald != (long long int)vald))
136             l = snprintf(buf, buf_size, "%f", vald);
137         else
138             l = snprintf(buf, buf_size, "%lld", (long long int)vald);
139         snprintf(buf+l, buf_size-l, "%s%s%s", *prefix_string || show_value_unit ? " " : "",
140                  prefix_string, show_value_unit ? uv.unit : "");
141     }
142
143     return buf;
144 }
145
146 /* WRITERS API */
147
148 typedef struct WriterContext WriterContext;
149
150 #define WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS 1
151 #define WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER 2
152
153 typedef struct Writer {
154     int priv_size;                  ///< private size for the writer context
155     const char *name;
156
157     int  (*init)  (WriterContext *wctx, const char *args, void *opaque);
158     void (*uninit)(WriterContext *wctx);
159
160     void (*print_header)(WriterContext *ctx);
161     void (*print_footer)(WriterContext *ctx);
162
163     void (*print_chapter_header)(WriterContext *wctx, const char *);
164     void (*print_chapter_footer)(WriterContext *wctx, const char *);
165     void (*print_section_header)(WriterContext *wctx, const char *);
166     void (*print_section_footer)(WriterContext *wctx, const char *);
167     void (*print_integer)       (WriterContext *wctx, const char *, long long int);
168     void (*print_string)        (WriterContext *wctx, const char *, const char *);
169     void (*show_tags)           (WriterContext *wctx, AVDictionary *dict);
170     int flags;                  ///< a combination or WRITER_FLAG_*
171 } Writer;
172
173 struct WriterContext {
174     const AVClass *class;           ///< class of the writer
175     const Writer *writer;           ///< the Writer of which this is an instance
176     char *name;                     ///< name of this writer instance
177     void *priv;                     ///< private data for use by the filter
178     unsigned int nb_item;           ///< number of the item printed in the given section, starting at 0
179     unsigned int nb_section;        ///< number of the section printed in the given section sequence, starting at 0
180     unsigned int nb_chapter;        ///< number of the chapter, starting at 0
181
182     int multiple_sections;          ///< tells if the current chapter can contain multiple sections
183     int is_fmt_chapter;             ///< tells if the current chapter is "format", required by the print_format_entry option
184 };
185
186 static const char *writer_get_name(void *p)
187 {
188     WriterContext *wctx = p;
189     return wctx->writer->name;
190 }
191
192 static const AVClass writer_class = {
193     "Writer",
194     writer_get_name,
195     NULL,
196     LIBAVUTIL_VERSION_INT,
197 };
198
199 static void writer_close(WriterContext **wctx)
200 {
201     if (!*wctx)
202         return;
203
204     if ((*wctx)->writer->uninit)
205         (*wctx)->writer->uninit(*wctx);
206     av_freep(&((*wctx)->priv));
207     av_freep(wctx);
208 }
209
210 static int writer_open(WriterContext **wctx, const Writer *writer,
211                        const char *args, void *opaque)
212 {
213     int ret = 0;
214
215     if (!(*wctx = av_malloc(sizeof(WriterContext)))) {
216         ret = AVERROR(ENOMEM);
217         goto fail;
218     }
219
220     if (!((*wctx)->priv = av_mallocz(writer->priv_size))) {
221         ret = AVERROR(ENOMEM);
222         goto fail;
223     }
224
225     (*wctx)->class = &writer_class;
226     (*wctx)->writer = writer;
227     if ((*wctx)->writer->init)
228         ret = (*wctx)->writer->init(*wctx, args, opaque);
229     if (ret < 0)
230         goto fail;
231
232     return 0;
233
234 fail:
235     writer_close(wctx);
236     return ret;
237 }
238
239 static inline void writer_print_header(WriterContext *wctx)
240 {
241     if (wctx->writer->print_header)
242         wctx->writer->print_header(wctx);
243     wctx->nb_chapter = 0;
244 }
245
246 static inline void writer_print_footer(WriterContext *wctx)
247 {
248     if (wctx->writer->print_footer)
249         wctx->writer->print_footer(wctx);
250 }
251
252 static inline void writer_print_chapter_header(WriterContext *wctx,
253                                                const char *chapter)
254 {
255     if (wctx->writer->print_chapter_header)
256         wctx->writer->print_chapter_header(wctx, chapter);
257     wctx->nb_section = 0;
258
259     wctx->multiple_sections = !strcmp(chapter, "packets") || !strcmp(chapter, "frames" ) ||
260                               !strcmp(chapter, "packets_and_frames") ||
261                               !strcmp(chapter, "streams") || !strcmp(chapter, "library_versions");
262     wctx->is_fmt_chapter = !strcmp(chapter, "format");
263 }
264
265 static inline void writer_print_chapter_footer(WriterContext *wctx,
266                                                const char *chapter)
267 {
268     if (wctx->writer->print_chapter_footer)
269         wctx->writer->print_chapter_footer(wctx, chapter);
270     wctx->nb_chapter++;
271 }
272
273 static inline void writer_print_section_header(WriterContext *wctx,
274                                                const char *section)
275 {
276     if (wctx->writer->print_section_header)
277         wctx->writer->print_section_header(wctx, section);
278     wctx->nb_item = 0;
279 }
280
281 static inline void writer_print_section_footer(WriterContext *wctx,
282                                                const char *section)
283 {
284     if (wctx->writer->print_section_footer)
285         wctx->writer->print_section_footer(wctx, section);
286     wctx->nb_section++;
287 }
288
289 static inline void writer_print_integer(WriterContext *wctx,
290                                         const char *key, long long int val)
291 {
292     if (!wctx->is_fmt_chapter || !fmt_entries_to_show || av_dict_get(fmt_entries_to_show, key, NULL, 0)) {
293         wctx->writer->print_integer(wctx, key, val);
294         wctx->nb_item++;
295     }
296 }
297
298 static inline void writer_print_string(WriterContext *wctx,
299                                        const char *key, const char *val, int opt)
300 {
301     if (opt && !(wctx->writer->flags & WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS))
302         return;
303     if (!wctx->is_fmt_chapter || !fmt_entries_to_show || av_dict_get(fmt_entries_to_show, key, NULL, 0)) {
304         wctx->writer->print_string(wctx, key, val);
305         wctx->nb_item++;
306     }
307 }
308
309 static void writer_print_time(WriterContext *wctx, const char *key,
310                               int64_t ts, const AVRational *time_base)
311 {
312     char buf[128];
313
314     if (!wctx->is_fmt_chapter || !fmt_entries_to_show || av_dict_get(fmt_entries_to_show, key, NULL, 0)) {
315         if (ts == AV_NOPTS_VALUE) {
316             writer_print_string(wctx, key, "N/A", 1);
317         } else {
318             double d = ts * av_q2d(*time_base);
319             value_string(buf, sizeof(buf), (struct unit_value){.val.d=d, .unit=unit_second_str});
320             writer_print_string(wctx, key, buf, 0);
321         }
322     }
323 }
324
325 static void writer_print_ts(WriterContext *wctx, const char *key, int64_t ts)
326 {
327     if (ts == AV_NOPTS_VALUE) {
328         writer_print_string(wctx, key, "N/A", 1);
329     } else {
330         writer_print_integer(wctx, key, ts);
331     }
332 }
333
334 static inline void writer_show_tags(WriterContext *wctx, AVDictionary *dict)
335 {
336     wctx->writer->show_tags(wctx, dict);
337 }
338
339 #define MAX_REGISTERED_WRITERS_NB 64
340
341 static const Writer *registered_writers[MAX_REGISTERED_WRITERS_NB + 1];
342
343 static int writer_register(const Writer *writer)
344 {
345     static int next_registered_writer_idx = 0;
346
347     if (next_registered_writer_idx == MAX_REGISTERED_WRITERS_NB)
348         return AVERROR(ENOMEM);
349
350     registered_writers[next_registered_writer_idx++] = writer;
351     return 0;
352 }
353
354 static const Writer *writer_get_by_name(const char *name)
355 {
356     int i;
357
358     for (i = 0; registered_writers[i]; i++)
359         if (!strcmp(registered_writers[i]->name, name))
360             return registered_writers[i];
361
362     return NULL;
363 }
364
365
366 /* WRITERS */
367
368 /* Default output */
369
370 typedef struct DefaultContext {
371     const AVClass *class;
372     int nokey;
373     int noprint_wrappers;
374 } DefaultContext;
375
376 #define OFFSET(x) offsetof(DefaultContext, x)
377
378 static const AVOption default_options[] = {
379     { "noprint_wrappers", "do not print headers and footers", OFFSET(noprint_wrappers), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
380     { "nw",               "do not print headers and footers", OFFSET(noprint_wrappers), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
381     { "nokey",          "force no key printing",     OFFSET(nokey),          AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
382     { "nk",             "force no key printing",     OFFSET(nokey),          AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
383     {NULL},
384 };
385
386 static const char *default_get_name(void *ctx)
387 {
388     return "default";
389 }
390
391 static const AVClass default_class = {
392     "DefaultContext",
393     default_get_name,
394     default_options
395 };
396
397 static av_cold int default_init(WriterContext *wctx, const char *args, void *opaque)
398 {
399     DefaultContext *def = wctx->priv;
400     int err;
401
402     def->class = &default_class;
403     av_opt_set_defaults(def);
404
405     if (args &&
406         (err = (av_set_options_string(def, args, "=", ":"))) < 0) {
407         av_log(wctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
408         return err;
409     }
410
411     return 0;
412 }
413
414 static void default_print_footer(WriterContext *wctx)
415 {
416     DefaultContext *def = wctx->priv;
417
418     if (!def->noprint_wrappers)
419         printf("\n");
420 }
421
422 static void default_print_chapter_header(WriterContext *wctx, const char *chapter)
423 {
424     DefaultContext *def = wctx->priv;
425
426     if (!def->noprint_wrappers && wctx->nb_chapter)
427         printf("\n");
428 }
429
430 /* lame uppercasing routine, assumes the string is lower case ASCII */
431 static inline char *upcase_string(char *dst, size_t dst_size, const char *src)
432 {
433     int i;
434     for (i = 0; src[i] && i < dst_size-1; i++)
435         dst[i] = av_toupper(src[i]);
436     dst[i] = 0;
437     return dst;
438 }
439
440 static void default_print_section_header(WriterContext *wctx, const char *section)
441 {
442     DefaultContext *def = wctx->priv;
443     char buf[32];
444
445     if (wctx->nb_section)
446         printf("\n");
447     if (!def->noprint_wrappers)
448         printf("[%s]\n", upcase_string(buf, sizeof(buf), section));
449 }
450
451 static void default_print_section_footer(WriterContext *wctx, const char *section)
452 {
453     DefaultContext *def = wctx->priv;
454     char buf[32];
455
456     if (!def->noprint_wrappers)
457         printf("[/%s]", upcase_string(buf, sizeof(buf), section));
458 }
459
460 static void default_print_str(WriterContext *wctx, const char *key, const char *value)
461 {
462     DefaultContext *def = wctx->priv;
463     if (!def->nokey)
464         printf("%s=", key);
465     printf("%s\n", value);
466 }
467
468 static void default_print_int(WriterContext *wctx, const char *key, long long int value)
469 {
470     DefaultContext *def = wctx->priv;
471
472     if (!def->nokey)
473         printf("%s=", key);
474     printf("%lld\n", value);
475 }
476
477 static void default_show_tags(WriterContext *wctx, AVDictionary *dict)
478 {
479     AVDictionaryEntry *tag = NULL;
480     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
481         if (!fmt_entries_to_show || (tag->key && av_dict_get(fmt_entries_to_show, tag->key, NULL, 0)))
482             printf("TAG:");
483         writer_print_string(wctx, tag->key, tag->value, 0);
484     }
485 }
486
487 static const Writer default_writer = {
488     .name                  = "default",
489     .priv_size             = sizeof(DefaultContext),
490     .init                  = default_init,
491     .print_footer          = default_print_footer,
492     .print_chapter_header  = default_print_chapter_header,
493     .print_section_header  = default_print_section_header,
494     .print_section_footer  = default_print_section_footer,
495     .print_integer         = default_print_int,
496     .print_string          = default_print_str,
497     .show_tags             = default_show_tags,
498     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
499 };
500
501 /* Compact output */
502
503 /**
504  * Apply C-language-like string escaping.
505  */
506 static const char *c_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
507 {
508     const char *p;
509
510     for (p = src; *p; p++) {
511         switch (*src) {
512         case '\b': av_bprintf(dst, "%s", "\\b");  break;
513         case '\f': av_bprintf(dst, "%s", "\\f");  break;
514         case '\n': av_bprintf(dst, "%s", "\\n");  break;
515         case '\r': av_bprintf(dst, "%s", "\\r");  break;
516         case '\\': av_bprintf(dst, "%s", "\\\\"); break;
517         default:
518             if (*p == sep)
519                 av_bprint_chars(dst, '\\', 1);
520             av_bprint_chars(dst, *p, 1);
521         }
522     }
523     return dst->str;
524 }
525
526 /**
527  * Quote fields containing special characters, check RFC4180.
528  */
529 static const char *csv_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
530 {
531     const char *p;
532     int quote = 0;
533
534     /* check if input needs quoting */
535     for (p = src; *p; p++)
536         if (*p == '"' || *p == sep || *p == '\n' || *p == '\r')
537             quote = 1;
538
539     if (quote)
540         av_bprint_chars(dst, '\"', 1);
541
542     for (p = src; *p; p++) {
543         if (*p == '"')
544             av_bprint_chars(dst, '\"', 1);
545         av_bprint_chars(dst, *p, 1);
546     }
547     if (quote)
548         av_bprint_chars(dst, '\"', 1);
549     return dst->str;
550 }
551
552 static const char *none_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
553 {
554     return src;
555 }
556
557 typedef struct CompactContext {
558     const AVClass *class;
559     char *item_sep_str;
560     char item_sep;
561     int nokey;
562     char *escape_mode_str;
563     const char * (*escape_str)(AVBPrint *dst, const char *src, const char sep, void *log_ctx);
564 } CompactContext;
565
566 #undef OFFSET
567 #define OFFSET(x) offsetof(CompactContext, x)
568
569 static const AVOption compact_options[]= {
570     {"item_sep", "set item separator",    OFFSET(item_sep_str),    AV_OPT_TYPE_STRING, {.str="|"},  CHAR_MIN, CHAR_MAX },
571     {"s",        "set item separator",    OFFSET(item_sep_str),    AV_OPT_TYPE_STRING, {.str="|"},  CHAR_MIN, CHAR_MAX },
572     {"nokey",    "force no key printing", OFFSET(nokey),           AV_OPT_TYPE_INT,    {.dbl=0},    0,        1        },
573     {"nk",       "force no key printing", OFFSET(nokey),           AV_OPT_TYPE_INT,    {.dbl=0},    0,        1        },
574     {"escape",   "set escape mode",       OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"},  CHAR_MIN, CHAR_MAX },
575     {"e",        "set escape mode",       OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"},  CHAR_MIN, CHAR_MAX },
576     {NULL},
577 };
578
579 static const char *compact_get_name(void *ctx)
580 {
581     return "compact";
582 }
583
584 static const AVClass compact_class = {
585     "CompactContext",
586     compact_get_name,
587     compact_options
588 };
589
590 static av_cold int compact_init(WriterContext *wctx, const char *args, void *opaque)
591 {
592     CompactContext *compact = wctx->priv;
593     int err;
594
595     compact->class = &compact_class;
596     av_opt_set_defaults(compact);
597
598     if (args &&
599         (err = (av_set_options_string(compact, args, "=", ":"))) < 0) {
600         av_log(wctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
601         return err;
602     }
603     if (strlen(compact->item_sep_str) != 1) {
604         av_log(wctx, AV_LOG_ERROR, "Item separator '%s' specified, but must contain a single character\n",
605                compact->item_sep_str);
606         return AVERROR(EINVAL);
607     }
608     compact->item_sep = compact->item_sep_str[0];
609
610     if      (!strcmp(compact->escape_mode_str, "none")) compact->escape_str = none_escape_str;
611     else if (!strcmp(compact->escape_mode_str, "c"   )) compact->escape_str = c_escape_str;
612     else if (!strcmp(compact->escape_mode_str, "csv" )) compact->escape_str = csv_escape_str;
613     else {
614         av_log(wctx, AV_LOG_ERROR, "Unknown escape mode '%s'\n", compact->escape_mode_str);
615         return AVERROR(EINVAL);
616     }
617
618     return 0;
619 }
620
621 static av_cold void compact_uninit(WriterContext *wctx)
622 {
623     CompactContext *compact = wctx->priv;
624
625     av_freep(&compact->item_sep_str);
626     av_freep(&compact->escape_mode_str);
627 }
628
629 static void compact_print_section_header(WriterContext *wctx, const char *section)
630 {
631     CompactContext *compact = wctx->priv;
632
633     printf("%s%c", section, compact->item_sep);
634 }
635
636 static void compact_print_section_footer(WriterContext *wctx, const char *section)
637 {
638     printf("\n");
639 }
640
641 static void compact_print_str(WriterContext *wctx, const char *key, const char *value)
642 {
643     CompactContext *compact = wctx->priv;
644     AVBPrint buf;
645
646     if (wctx->nb_item) printf("%c", compact->item_sep);
647     if (!compact->nokey)
648         printf("%s=", key);
649     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
650     printf("%s", compact->escape_str(&buf, value, compact->item_sep, wctx));
651     av_bprint_finalize(&buf, NULL);
652 }
653
654 static void compact_print_int(WriterContext *wctx, const char *key, long long int value)
655 {
656     CompactContext *compact = wctx->priv;
657
658     if (wctx->nb_item) printf("%c", compact->item_sep);
659     if (!compact->nokey)
660         printf("%s=", key);
661     printf("%lld", value);
662 }
663
664 static void compact_show_tags(WriterContext *wctx, AVDictionary *dict)
665 {
666     CompactContext *compact = wctx->priv;
667     AVDictionaryEntry *tag = NULL;
668     AVBPrint buf;
669
670     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
671     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
672         if (wctx->nb_item) printf("%c", compact->item_sep);
673         if (!compact->nokey) {
674             av_bprint_clear(&buf);
675             printf("tag:%s=", compact->escape_str(&buf, tag->key, compact->item_sep, wctx));
676         }
677         av_bprint_clear(&buf);
678         printf("%s", compact->escape_str(&buf, tag->value, compact->item_sep, wctx));
679     }
680     av_bprint_finalize(&buf, NULL);
681 }
682
683 static const Writer compact_writer = {
684     .name                 = "compact",
685     .priv_size            = sizeof(CompactContext),
686     .init                 = compact_init,
687     .uninit               = compact_uninit,
688     .print_section_header = compact_print_section_header,
689     .print_section_footer = compact_print_section_footer,
690     .print_integer        = compact_print_int,
691     .print_string         = compact_print_str,
692     .show_tags            = compact_show_tags,
693     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
694 };
695
696 /* CSV output */
697
698 static av_cold int csv_init(WriterContext *wctx, const char *args, void *opaque)
699 {
700     return compact_init(wctx, "item_sep=,:nokey=1:escape=csv", opaque);
701 }
702
703 static const Writer csv_writer = {
704     .name                 = "csv",
705     .priv_size            = sizeof(CompactContext),
706     .init                 = csv_init,
707     .uninit               = compact_uninit,
708     .print_section_header = compact_print_section_header,
709     .print_section_footer = compact_print_section_footer,
710     .print_integer        = compact_print_int,
711     .print_string         = compact_print_str,
712     .show_tags            = compact_show_tags,
713     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
714 };
715
716 /* INI format output */
717
718 typedef struct {
719     const AVClass *class;
720     AVBPrint chapter_name, section_name;
721     int print_packets_and_frames;
722     int nb_frame;
723     int nb_packet;
724     int hierarchical;
725 } INIContext;
726
727 #undef OFFSET
728 #define OFFSET(x) offsetof(INIContext, x)
729
730 static const AVOption ini_options[] = {
731     {"hierachical", "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_INT, {.dbl=1}, 0, 1 },
732     {"h",           "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_INT, {.dbl=1}, 0, 1 },
733     {NULL},
734 };
735
736 static const char *ini_get_name(void *ctx)
737 {
738     return "ini";
739 }
740
741 static const AVClass ini_class = {
742     "INIContext",
743     ini_get_name,
744     ini_options
745 };
746
747 static av_cold int ini_init(WriterContext *wctx, const char *args, void *opaque)
748 {
749     INIContext *ini = wctx->priv;
750     int err;
751
752     av_bprint_init(&ini->chapter_name, 1, AV_BPRINT_SIZE_UNLIMITED);
753     av_bprint_init(&ini->section_name, 1, AV_BPRINT_SIZE_UNLIMITED);
754     ini->nb_frame = ini->nb_packet = 0;
755
756     ini->class = &ini_class;
757     av_opt_set_defaults(ini);
758
759     if (args && (err = av_set_options_string(ini, args, "=", ":")) < 0) {
760         av_log(wctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
761         return err;
762     }
763
764     return 0;
765 }
766
767 static av_cold void ini_uninit(WriterContext *wctx)
768 {
769     INIContext *ini = wctx->priv;
770     av_bprint_finalize(&ini->chapter_name, NULL);
771     av_bprint_finalize(&ini->section_name, NULL);
772 }
773
774 static void ini_print_header(WriterContext *wctx)
775 {
776     printf("# ffprobe output\n\n");
777 }
778
779 static char *ini_escape_str(AVBPrint *dst, const char *src)
780 {
781     int i = 0;
782     char c = 0;
783
784     while (c = src[i++]) {
785         switch (c) {
786         case '\b': av_bprintf(dst, "%s", "\\b"); break;
787         case '\f': av_bprintf(dst, "%s", "\\f"); break;
788         case '\n': av_bprintf(dst, "%s", "\\n"); break;
789         case '\r': av_bprintf(dst, "%s", "\\r"); break;
790         case '\t': av_bprintf(dst, "%s", "\\t"); break;
791         case '\\':
792         case '#' :
793         case '=' :
794         case ':' : av_bprint_chars(dst, '\\', 1);
795         default:
796             if ((unsigned char)c < 32)
797                 av_bprintf(dst, "\\x00%02x", c & 0xff);
798             else
799                 av_bprint_chars(dst, c, 1);
800             break;
801         }
802     }
803     return dst->str;
804 }
805
806 static void ini_print_chapter_header(WriterContext *wctx, const char *chapter)
807 {
808     INIContext *ini = wctx->priv;
809
810     av_bprint_clear(&ini->chapter_name);
811     av_bprintf(&ini->chapter_name, "%s", chapter);
812
813     if (wctx->nb_chapter)
814         printf("\n");
815     ini->print_packets_and_frames = !strcmp("packets_and_frames", chapter);
816 }
817
818 static void ini_print_section_header(WriterContext *wctx, const char *section)
819 {
820     INIContext *ini = wctx->priv;
821     int n;
822     if (wctx->nb_section)
823         printf("\n");
824     av_bprint_clear(&ini->section_name);
825
826     if (ini->hierarchical && wctx->multiple_sections)
827         av_bprintf(&ini->section_name, "%s.", ini->chapter_name.str);
828     av_bprintf(&ini->section_name, "%s", section);
829
830     if (ini->print_packets_and_frames)
831         n = !strcmp(section, "packet") ? ini->nb_packet++ : ini->nb_frame++;
832     else
833         n = wctx->nb_section;
834     if (wctx->multiple_sections)
835         av_bprintf(&ini->section_name, ".%d", n);
836     printf("[%s]\n", ini->section_name.str);
837 }
838
839 static void ini_print_str(WriterContext *wctx, const char *key, const char *value)
840 {
841     AVBPrint buf;
842
843     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
844     printf("%s=", ini_escape_str(&buf, key));
845     av_bprint_clear(&buf);
846     printf("%s\n", ini_escape_str(&buf, value));
847     av_bprint_finalize(&buf, NULL);
848 }
849
850 static void ini_print_int(WriterContext *wctx, const char *key, long long int value)
851 {
852     printf("%s=%lld\n", key, value);
853 }
854
855 static void ini_show_tags(WriterContext *wctx, AVDictionary *dict)
856 {
857     INIContext *ini = wctx->priv;
858     AVDictionaryEntry *tag = NULL;
859     int is_first = 1;
860
861     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
862         if (is_first) {
863             printf("\n[%s.tags]\n", ini->section_name.str);
864             is_first = 0;
865         }
866         writer_print_string(wctx, tag->key, tag->value, 0);
867     }
868 }
869
870 static const Writer ini_writer = {
871     .name                  = "ini",
872     .priv_size             = sizeof(INIContext),
873     .init                  = ini_init,
874     .uninit                = ini_uninit,
875     .print_header          = ini_print_header,
876     .print_chapter_header  = ini_print_chapter_header,
877     .print_section_header  = ini_print_section_header,
878     .print_integer         = ini_print_int,
879     .print_string          = ini_print_str,
880     .show_tags             = ini_show_tags,
881     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS|WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
882 };
883
884 /* JSON output */
885
886 typedef struct {
887     const AVClass *class;
888     int print_packets_and_frames;
889     int indent_level;
890     int compact;
891     const char *item_sep, *item_start_end;
892 } JSONContext;
893
894 #undef OFFSET
895 #define OFFSET(x) offsetof(JSONContext, x)
896
897 static const AVOption json_options[]= {
898     { "compact", "enable compact output", OFFSET(compact), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
899     { "c",       "enable compact output", OFFSET(compact), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
900     { NULL }
901 };
902
903 static const char *json_get_name(void *ctx)
904 {
905     return "json";
906 }
907
908 static const AVClass json_class = {
909     "JSONContext",
910     json_get_name,
911     json_options
912 };
913
914 static av_cold int json_init(WriterContext *wctx, const char *args, void *opaque)
915 {
916     JSONContext *json = wctx->priv;
917     int err;
918
919     json->class = &json_class;
920     av_opt_set_defaults(json);
921
922     if (args &&
923         (err = (av_set_options_string(json, args, "=", ":"))) < 0) {
924         av_log(wctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
925         return err;
926     }
927
928     json->item_sep       = json->compact ? ", " : ",\n";
929     json->item_start_end = json->compact ? " "  : "\n";
930
931     return 0;
932 }
933
934 static const char *json_escape_str(AVBPrint *dst, const char *src, void *log_ctx)
935 {
936     static const char json_escape[] = {'"', '\\', '\b', '\f', '\n', '\r', '\t', 0};
937     static const char json_subst[]  = {'"', '\\',  'b',  'f',  'n',  'r',  't', 0};
938     const char *p;
939
940     for (p = src; *p; p++) {
941         char *s = strchr(json_escape, *p);
942         if (s) {
943             av_bprint_chars(dst, '\\', 1);
944             av_bprint_chars(dst, json_subst[s - json_escape], 1);
945         } else if ((unsigned char)*p < 32) {
946             av_bprintf(dst, "\\u00%02x", *p & 0xff);
947         } else {
948             av_bprint_chars(dst, *p, 1);
949         }
950     }
951     return dst->str;
952 }
953
954 static void json_print_header(WriterContext *wctx)
955 {
956     JSONContext *json = wctx->priv;
957     printf("{");
958     json->indent_level++;
959 }
960
961 static void json_print_footer(WriterContext *wctx)
962 {
963     JSONContext *json = wctx->priv;
964     json->indent_level--;
965     printf("\n}\n");
966 }
967
968 #define JSON_INDENT() printf("%*c", json->indent_level * 4, ' ')
969
970 static void json_print_chapter_header(WriterContext *wctx, const char *chapter)
971 {
972     JSONContext *json = wctx->priv;
973     AVBPrint buf;
974
975     if (wctx->nb_chapter)
976         printf(",");
977     printf("\n");
978     if (wctx->multiple_sections) {
979         JSON_INDENT();
980         av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
981         printf("\"%s\": [\n", json_escape_str(&buf, chapter, wctx));
982         av_bprint_finalize(&buf, NULL);
983         json->print_packets_and_frames = !strcmp(chapter, "packets_and_frames");
984         json->indent_level++;
985     }
986 }
987
988 static void json_print_chapter_footer(WriterContext *wctx, const char *chapter)
989 {
990     JSONContext *json = wctx->priv;
991
992     if (wctx->multiple_sections) {
993         printf("\n");
994         json->indent_level--;
995         JSON_INDENT();
996         printf("]");
997     }
998 }
999
1000 static void json_print_section_header(WriterContext *wctx, const char *section)
1001 {
1002     JSONContext *json = wctx->priv;
1003
1004     if (wctx->nb_section)
1005         printf(",\n");
1006     JSON_INDENT();
1007     if (!wctx->multiple_sections)
1008         printf("\"%s\": ", section);
1009     printf("{%s", json->item_start_end);
1010     json->indent_level++;
1011     /* this is required so the parser can distinguish between packets and frames */
1012     if (json->print_packets_and_frames) {
1013         if (!json->compact)
1014             JSON_INDENT();
1015         printf("\"type\": \"%s\"%s", section, json->item_sep);
1016     }
1017 }
1018
1019 static void json_print_section_footer(WriterContext *wctx, const char *section)
1020 {
1021     JSONContext *json = wctx->priv;
1022
1023     printf("%s", json->item_start_end);
1024     json->indent_level--;
1025     if (!json->compact)
1026         JSON_INDENT();
1027     printf("}");
1028 }
1029
1030 static inline void json_print_item_str(WriterContext *wctx,
1031                                        const char *key, const char *value)
1032 {
1033     AVBPrint buf;
1034
1035     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
1036     printf("\"%s\":", json_escape_str(&buf, key,   wctx));
1037     av_bprint_clear(&buf);
1038     printf(" \"%s\"", json_escape_str(&buf, value, wctx));
1039     av_bprint_finalize(&buf, NULL);
1040 }
1041
1042 static void json_print_str(WriterContext *wctx, const char *key, const char *value)
1043 {
1044     JSONContext *json = wctx->priv;
1045
1046     if (wctx->nb_item) printf("%s", json->item_sep);
1047     if (!json->compact)
1048         JSON_INDENT();
1049     json_print_item_str(wctx, key, value);
1050 }
1051
1052 static void json_print_int(WriterContext *wctx, const char *key, long long int value)
1053 {
1054     JSONContext *json = wctx->priv;
1055     AVBPrint buf;
1056
1057     if (wctx->nb_item) printf("%s", json->item_sep);
1058     if (!json->compact)
1059         JSON_INDENT();
1060
1061     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
1062     printf("\"%s\": %lld", json_escape_str(&buf, key, wctx), value);
1063     av_bprint_finalize(&buf, NULL);
1064 }
1065
1066 static void json_show_tags(WriterContext *wctx, AVDictionary *dict)
1067 {
1068     JSONContext *json = wctx->priv;
1069     AVDictionaryEntry *tag = NULL;
1070     int is_first = 1;
1071     if (!dict)
1072         return;
1073     printf("%s", json->item_sep);
1074     if (!json->compact)
1075         JSON_INDENT();
1076     printf("\"tags\": {%s", json->item_start_end);
1077     json->indent_level++;
1078     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
1079         if (is_first) is_first = 0;
1080         else          printf("%s", json->item_sep);
1081         if (!json->compact)
1082             JSON_INDENT();
1083         json_print_item_str(wctx, tag->key, tag->value);
1084     }
1085     json->indent_level--;
1086     printf("%s", json->item_start_end);
1087     if (!json->compact)
1088         JSON_INDENT();
1089     printf("}");
1090 }
1091
1092 static const Writer json_writer = {
1093     .name                 = "json",
1094     .priv_size            = sizeof(JSONContext),
1095     .init                 = json_init,
1096     .print_header         = json_print_header,
1097     .print_footer         = json_print_footer,
1098     .print_chapter_header = json_print_chapter_header,
1099     .print_chapter_footer = json_print_chapter_footer,
1100     .print_section_header = json_print_section_header,
1101     .print_section_footer = json_print_section_footer,
1102     .print_integer        = json_print_int,
1103     .print_string         = json_print_str,
1104     .show_tags            = json_show_tags,
1105     .flags = WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
1106 };
1107
1108 /* XML output */
1109
1110 typedef struct {
1111     const AVClass *class;
1112     int within_tag;
1113     int multiple_entries; ///< tells if the given chapter requires multiple entries
1114     int indent_level;
1115     int fully_qualified;
1116     int xsd_strict;
1117 } XMLContext;
1118
1119 #undef OFFSET
1120 #define OFFSET(x) offsetof(XMLContext, x)
1121
1122 static const AVOption xml_options[] = {
1123     {"fully_qualified", "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_INT, {.dbl=0},  0, 1 },
1124     {"q",               "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_INT, {.dbl=0},  0, 1 },
1125     {"xsd_strict",      "ensure that the output is XSD compliant",         OFFSET(xsd_strict),      AV_OPT_TYPE_INT, {.dbl=0},  0, 1 },
1126     {"x",               "ensure that the output is XSD compliant",         OFFSET(xsd_strict),      AV_OPT_TYPE_INT, {.dbl=0},  0, 1 },
1127     {NULL},
1128 };
1129
1130 static const char *xml_get_name(void *ctx)
1131 {
1132     return "xml";
1133 }
1134
1135 static const AVClass xml_class = {
1136     "XMLContext",
1137     xml_get_name,
1138     xml_options
1139 };
1140
1141 static av_cold int xml_init(WriterContext *wctx, const char *args, void *opaque)
1142 {
1143     XMLContext *xml = wctx->priv;
1144     int err;
1145
1146     xml->class = &xml_class;
1147     av_opt_set_defaults(xml);
1148
1149     if (args &&
1150         (err = (av_set_options_string(xml, args, "=", ":"))) < 0) {
1151         av_log(wctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
1152         return err;
1153     }
1154
1155     if (xml->xsd_strict) {
1156         xml->fully_qualified = 1;
1157 #define CHECK_COMPLIANCE(opt, opt_name)                                 \
1158         if (opt) {                                                      \
1159             av_log(wctx, AV_LOG_ERROR,                                  \
1160                    "XSD-compliant output selected but option '%s' was selected, XML output may be non-compliant.\n" \
1161                    "You need to disable such option with '-no%s'\n", opt_name, opt_name); \
1162             return AVERROR(EINVAL);                                     \
1163         }
1164         CHECK_COMPLIANCE(show_private_data, "private");
1165         CHECK_COMPLIANCE(show_value_unit,   "unit");
1166         CHECK_COMPLIANCE(use_value_prefix,  "prefix");
1167
1168         if (do_show_frames && do_show_packets) {
1169             av_log(wctx, AV_LOG_ERROR,
1170                    "Interleaved frames and packets are not allowed in XSD. "
1171                    "Select only one between the -show_frames and the -show_packets options.\n");
1172             return AVERROR(EINVAL);
1173         }
1174     }
1175
1176     return 0;
1177 }
1178
1179 static const char *xml_escape_str(AVBPrint *dst, const char *src, void *log_ctx)
1180 {
1181     const char *p;
1182
1183     for (p = src; *p; p++) {
1184         switch (*p) {
1185         case '&' : av_bprintf(dst, "%s", "&amp;");  break;
1186         case '<' : av_bprintf(dst, "%s", "&lt;");   break;
1187         case '>' : av_bprintf(dst, "%s", "&gt;");   break;
1188         case '\"': av_bprintf(dst, "%s", "&quot;"); break;
1189         case '\'': av_bprintf(dst, "%s", "&apos;"); break;
1190         default: av_bprint_chars(dst, *p, 1);
1191         }
1192     }
1193
1194     return dst->str;
1195 }
1196
1197 static void xml_print_header(WriterContext *wctx)
1198 {
1199     XMLContext *xml = wctx->priv;
1200     const char *qual = " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' "
1201         "xmlns:ffprobe='http://www.ffmpeg.org/schema/ffprobe' "
1202         "xsi:schemaLocation='http://www.ffmpeg.org/schema/ffprobe ffprobe.xsd'";
1203
1204     printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1205     printf("<%sffprobe%s>\n",
1206            xml->fully_qualified ? "ffprobe:" : "",
1207            xml->fully_qualified ? qual : "");
1208
1209     xml->indent_level++;
1210 }
1211
1212 static void xml_print_footer(WriterContext *wctx)
1213 {
1214     XMLContext *xml = wctx->priv;
1215
1216     xml->indent_level--;
1217     printf("</%sffprobe>\n", xml->fully_qualified ? "ffprobe:" : "");
1218 }
1219
1220 #define XML_INDENT() printf("%*c", xml->indent_level * 4, ' ')
1221
1222 static void xml_print_chapter_header(WriterContext *wctx, const char *chapter)
1223 {
1224     XMLContext *xml = wctx->priv;
1225
1226     if (wctx->nb_chapter)
1227         printf("\n");
1228     xml->multiple_entries = !strcmp(chapter, "packets") || !strcmp(chapter, "frames") ||
1229                             !strcmp(chapter, "packets_and_frames") ||
1230                             !strcmp(chapter, "streams") || !strcmp(chapter, "library_versions");
1231
1232     if (xml->multiple_entries) {
1233         XML_INDENT(); printf("<%s>\n", chapter);
1234         xml->indent_level++;
1235     }
1236 }
1237
1238 static void xml_print_chapter_footer(WriterContext *wctx, const char *chapter)
1239 {
1240     XMLContext *xml = wctx->priv;
1241
1242     if (xml->multiple_entries) {
1243         xml->indent_level--;
1244         XML_INDENT(); printf("</%s>\n", chapter);
1245     }
1246 }
1247
1248 static void xml_print_section_header(WriterContext *wctx, const char *section)
1249 {
1250     XMLContext *xml = wctx->priv;
1251
1252     XML_INDENT(); printf("<%s ", section);
1253     xml->within_tag = 1;
1254 }
1255
1256 static void xml_print_section_footer(WriterContext *wctx, const char *section)
1257 {
1258     XMLContext *xml = wctx->priv;
1259
1260     if (xml->within_tag)
1261         printf("/>\n");
1262     else {
1263         XML_INDENT(); printf("</%s>\n", section);
1264     }
1265 }
1266
1267 static void xml_print_str(WriterContext *wctx, const char *key, const char *value)
1268 {
1269     AVBPrint buf;
1270
1271     if (wctx->nb_item)
1272         printf(" ");
1273     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
1274     printf("%s=\"%s\"", key, xml_escape_str(&buf, value, wctx));
1275     av_bprint_finalize(&buf, NULL);
1276 }
1277
1278 static void xml_print_int(WriterContext *wctx, const char *key, long long int value)
1279 {
1280     if (wctx->nb_item)
1281         printf(" ");
1282     printf("%s=\"%lld\"", key, value);
1283 }
1284
1285 static void xml_show_tags(WriterContext *wctx, AVDictionary *dict)
1286 {
1287     XMLContext *xml = wctx->priv;
1288     AVDictionaryEntry *tag = NULL;
1289     int is_first = 1;
1290     AVBPrint buf;
1291
1292     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
1293     xml->indent_level++;
1294     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
1295         if (is_first) {
1296             /* close section tag */
1297             printf(">\n");
1298             xml->within_tag = 0;
1299             is_first = 0;
1300         }
1301         XML_INDENT();
1302
1303         av_bprint_clear(&buf);
1304         printf("<tag key=\"%s\"", xml_escape_str(&buf, tag->key, wctx));
1305         av_bprint_clear(&buf);
1306         printf(" value=\"%s\"/>\n", xml_escape_str(&buf, tag->value, wctx));
1307     }
1308     av_bprint_finalize(&buf, NULL);
1309     xml->indent_level--;
1310 }
1311
1312 static Writer xml_writer = {
1313     .name                 = "xml",
1314     .priv_size            = sizeof(XMLContext),
1315     .init                 = xml_init,
1316     .print_header         = xml_print_header,
1317     .print_footer         = xml_print_footer,
1318     .print_chapter_header = xml_print_chapter_header,
1319     .print_chapter_footer = xml_print_chapter_footer,
1320     .print_section_header = xml_print_section_header,
1321     .print_section_footer = xml_print_section_footer,
1322     .print_integer        = xml_print_int,
1323     .print_string         = xml_print_str,
1324     .show_tags            = xml_show_tags,
1325     .flags = WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
1326 };
1327
1328 static void writer_register_all(void)
1329 {
1330     static int initialized;
1331
1332     if (initialized)
1333         return;
1334     initialized = 1;
1335
1336     writer_register(&default_writer);
1337     writer_register(&compact_writer);
1338     writer_register(&csv_writer);
1339     writer_register(&ini_writer);
1340     writer_register(&json_writer);
1341     writer_register(&xml_writer);
1342 }
1343
1344 #define print_fmt(k, f, ...) do {              \
1345     av_bprint_clear(&pbuf);                    \
1346     av_bprintf(&pbuf, f, __VA_ARGS__);         \
1347     writer_print_string(w, k, pbuf.str, 0);    \
1348 } while (0)
1349
1350 #define print_int(k, v)         writer_print_integer(w, k, v)
1351 #define print_str(k, v)         writer_print_string(w, k, v, 0)
1352 #define print_str_opt(k, v)     writer_print_string(w, k, v, 1)
1353 #define print_time(k, v, tb)    writer_print_time(w, k, v, tb)
1354 #define print_ts(k, v)          writer_print_ts(w, k, v)
1355 #define print_val(k, v, u)      writer_print_string(w, k, \
1356     value_string(val_str, sizeof(val_str), (struct unit_value){.val.i = v, .unit=u}), 0)
1357 #define print_section_header(s) writer_print_section_header(w, s)
1358 #define print_section_footer(s) writer_print_section_footer(w, s)
1359 #define show_tags(metadata)     writer_show_tags(w, metadata)
1360
1361 static void show_packet(WriterContext *w, AVFormatContext *fmt_ctx, AVPacket *pkt, int packet_idx)
1362 {
1363     char val_str[128];
1364     AVStream *st = fmt_ctx->streams[pkt->stream_index];
1365     AVBPrint pbuf;
1366     const char *s;
1367
1368     av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
1369
1370     print_section_header("packet");
1371     s = av_get_media_type_string(st->codec->codec_type);
1372     if (s) print_str    ("codec_type", s);
1373     else   print_str_opt("codec_type", "unknown");
1374     print_int("stream_index",     pkt->stream_index);
1375     print_ts  ("pts",             pkt->pts);
1376     print_time("pts_time",        pkt->pts, &st->time_base);
1377     print_ts  ("dts",             pkt->dts);
1378     print_time("dts_time",        pkt->dts, &st->time_base);
1379     print_ts  ("duration",        pkt->duration);
1380     print_time("duration_time",   pkt->duration, &st->time_base);
1381     print_val("size",             pkt->size, unit_byte_str);
1382     if (pkt->pos != -1) print_fmt    ("pos", "%"PRId64, pkt->pos);
1383     else                print_str_opt("pos", "N/A");
1384     print_fmt("flags", "%c",      pkt->flags & AV_PKT_FLAG_KEY ? 'K' : '_');
1385     print_section_footer("packet");
1386
1387     av_bprint_finalize(&pbuf, NULL);
1388     fflush(stdout);
1389 }
1390
1391 static void show_frame(WriterContext *w, AVFrame *frame, AVStream *stream)
1392 {
1393     AVBPrint pbuf;
1394     const char *s;
1395
1396     av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
1397
1398     print_section_header("frame");
1399
1400     s = av_get_media_type_string(stream->codec->codec_type);
1401     if (s) print_str    ("media_type", s);
1402     else   print_str_opt("media_type", "unknown");
1403     print_int("key_frame",              frame->key_frame);
1404     print_ts  ("pkt_pts",               frame->pkt_pts);
1405     print_time("pkt_pts_time",          frame->pkt_pts, &stream->time_base);
1406     print_ts  ("pkt_dts",               frame->pkt_dts);
1407     print_time("pkt_dts_time",          frame->pkt_dts, &stream->time_base);
1408     if (frame->pkt_pos != -1) print_fmt    ("pkt_pos", "%"PRId64, frame->pkt_pos);
1409     else                      print_str_opt("pkt_pos", "N/A");
1410
1411     switch (stream->codec->codec_type) {
1412     case AVMEDIA_TYPE_VIDEO:
1413         print_int("width",                  frame->width);
1414         print_int("height",                 frame->height);
1415         s = av_get_pix_fmt_name(frame->format);
1416         if (s) print_str    ("pix_fmt", s);
1417         else   print_str_opt("pix_fmt", "unknown");
1418         if (frame->sample_aspect_ratio.num) {
1419             print_fmt("sample_aspect_ratio", "%d:%d",
1420                       frame->sample_aspect_ratio.num,
1421                       frame->sample_aspect_ratio.den);
1422         } else {
1423             print_str_opt("sample_aspect_ratio", "N/A");
1424         }
1425         print_fmt("pict_type",              "%c", av_get_picture_type_char(frame->pict_type));
1426         print_int("coded_picture_number",   frame->coded_picture_number);
1427         print_int("display_picture_number", frame->display_picture_number);
1428         print_int("interlaced_frame",       frame->interlaced_frame);
1429         print_int("top_field_first",        frame->top_field_first);
1430         print_int("repeat_pict",            frame->repeat_pict);
1431         print_int("reference",              frame->reference);
1432         break;
1433
1434     case AVMEDIA_TYPE_AUDIO:
1435         s = av_get_sample_fmt_name(frame->format);
1436         if (s) print_str    ("sample_fmt", s);
1437         else   print_str_opt("sample_fmt", "unknown");
1438         print_int("nb_samples",         frame->nb_samples);
1439         break;
1440     }
1441
1442     print_section_footer("frame");
1443
1444     av_bprint_finalize(&pbuf, NULL);
1445     fflush(stdout);
1446 }
1447
1448 static av_always_inline int get_decoded_frame(AVFormatContext *fmt_ctx,
1449                                               AVFrame *frame, int *got_frame,
1450                                               AVPacket *pkt)
1451 {
1452     AVCodecContext *dec_ctx = fmt_ctx->streams[pkt->stream_index]->codec;
1453     int ret = 0;
1454
1455     *got_frame = 0;
1456     switch (dec_ctx->codec_type) {
1457     case AVMEDIA_TYPE_VIDEO:
1458         ret = avcodec_decode_video2(dec_ctx, frame, got_frame, pkt);
1459         break;
1460
1461     case AVMEDIA_TYPE_AUDIO:
1462         ret = avcodec_decode_audio4(dec_ctx, frame, got_frame, pkt);
1463         break;
1464     }
1465
1466     return ret;
1467 }
1468
1469 static void read_packets(WriterContext *w, AVFormatContext *fmt_ctx)
1470 {
1471     AVPacket pkt, pkt1;
1472     AVFrame frame;
1473     int i = 0, ret, got_frame;
1474
1475     av_init_packet(&pkt);
1476
1477     while (!av_read_frame(fmt_ctx, &pkt)) {
1478         if (do_read_packets) {
1479             if (do_show_packets)
1480                 show_packet(w, fmt_ctx, &pkt, i++);
1481             nb_streams_packets[pkt.stream_index]++;
1482         }
1483         if (do_read_frames) {
1484             pkt1 = pkt;
1485             while (pkt1.size) {
1486                 avcodec_get_frame_defaults(&frame);
1487                 ret = get_decoded_frame(fmt_ctx, &frame, &got_frame, &pkt1);
1488                 if (ret < 0 || !got_frame)
1489                     break;
1490                 if (do_show_frames)
1491                     show_frame(w, &frame, fmt_ctx->streams[pkt.stream_index]);
1492                 pkt1.data += ret;
1493                 pkt1.size -= ret;
1494                 nb_streams_frames[pkt.stream_index]++;
1495             }
1496         }
1497         av_free_packet(&pkt);
1498     }
1499     av_init_packet(&pkt);
1500     pkt.data = NULL;
1501     pkt.size = 0;
1502     //Flush remaining frames that are cached in the decoder
1503     for (i = 0; i < fmt_ctx->nb_streams; i++) {
1504         pkt.stream_index = i;
1505         while (get_decoded_frame(fmt_ctx, &frame, &got_frame, &pkt) >= 0 && got_frame) {
1506             if (do_read_frames) {
1507                 if (do_show_frames)
1508                     show_frame(w, &frame, fmt_ctx->streams[pkt.stream_index]);
1509                 nb_streams_frames[pkt.stream_index]++;
1510             }
1511         }
1512     }
1513 }
1514
1515 static void show_stream(WriterContext *w, AVFormatContext *fmt_ctx, int stream_idx)
1516 {
1517     AVStream *stream = fmt_ctx->streams[stream_idx];
1518     AVCodecContext *dec_ctx;
1519     AVCodec *dec;
1520     char val_str[128];
1521     const char *s;
1522     AVRational display_aspect_ratio;
1523     AVBPrint pbuf;
1524
1525     av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
1526
1527     print_section_header("stream");
1528
1529     print_int("index", stream->index);
1530
1531     if ((dec_ctx = stream->codec)) {
1532         const char *profile = NULL;
1533         if ((dec = dec_ctx->codec)) {
1534             print_str("codec_name",      dec->name);
1535             print_str("codec_long_name", dec->long_name);
1536         } else {
1537             print_str_opt("codec_name",      "unknown");
1538             print_str_opt("codec_long_name", "unknown");
1539         }
1540
1541         if (dec && (profile = av_get_profile_name(dec, dec_ctx->profile)))
1542             print_str("profile", profile);
1543         else
1544             print_str_opt("profile", "unknown");
1545
1546         s = av_get_media_type_string(dec_ctx->codec_type);
1547         if (s) print_str    ("codec_type", s);
1548         else   print_str_opt("codec_type", "unknown");
1549         print_fmt("codec_time_base", "%d/%d", dec_ctx->time_base.num, dec_ctx->time_base.den);
1550
1551         /* print AVI/FourCC tag */
1552         av_get_codec_tag_string(val_str, sizeof(val_str), dec_ctx->codec_tag);
1553         print_str("codec_tag_string",    val_str);
1554         print_fmt("codec_tag", "0x%04x", dec_ctx->codec_tag);
1555
1556         switch (dec_ctx->codec_type) {
1557         case AVMEDIA_TYPE_VIDEO:
1558             print_int("width",        dec_ctx->width);
1559             print_int("height",       dec_ctx->height);
1560             print_int("has_b_frames", dec_ctx->has_b_frames);
1561             if (dec_ctx->sample_aspect_ratio.num) {
1562                 print_fmt("sample_aspect_ratio", "%d:%d",
1563                           dec_ctx->sample_aspect_ratio.num,
1564                           dec_ctx->sample_aspect_ratio.den);
1565                 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
1566                           dec_ctx->width  * dec_ctx->sample_aspect_ratio.num,
1567                           dec_ctx->height * dec_ctx->sample_aspect_ratio.den,
1568                           1024*1024);
1569                 print_fmt("display_aspect_ratio", "%d:%d",
1570                           display_aspect_ratio.num,
1571                           display_aspect_ratio.den);
1572             } else {
1573                 print_str_opt("sample_aspect_ratio", "N/A");
1574                 print_str_opt("display_aspect_ratio", "N/A");
1575             }
1576             s = av_get_pix_fmt_name(dec_ctx->pix_fmt);
1577             if (s) print_str    ("pix_fmt", s);
1578             else   print_str_opt("pix_fmt", "unknown");
1579             print_int("level",   dec_ctx->level);
1580             if (dec_ctx->timecode_frame_start >= 0) {
1581                 char tcbuf[AV_TIMECODE_STR_SIZE];
1582                 av_timecode_make_mpeg_tc_string(tcbuf, dec_ctx->timecode_frame_start);
1583                 print_str("timecode", tcbuf);
1584             } else {
1585                 print_str_opt("timecode", "N/A");
1586             }
1587             break;
1588
1589         case AVMEDIA_TYPE_AUDIO:
1590             s = av_get_sample_fmt_name(dec_ctx->sample_fmt);
1591             if (s) print_str    ("sample_fmt", s);
1592             else   print_str_opt("sample_fmt", "unknown");
1593             print_val("sample_rate",     dec_ctx->sample_rate, unit_hertz_str);
1594             print_int("channels",        dec_ctx->channels);
1595             print_int("bits_per_sample", av_get_bits_per_sample(dec_ctx->codec_id));
1596             break;
1597         }
1598     } else {
1599         print_str_opt("codec_type", "unknown");
1600     }
1601     if (dec_ctx->codec && dec_ctx->codec->priv_class && show_private_data) {
1602         const AVOption *opt = NULL;
1603         while (opt = av_opt_next(dec_ctx->priv_data,opt)) {
1604             uint8_t *str;
1605             if (opt->flags) continue;
1606             if (av_opt_get(dec_ctx->priv_data, opt->name, 0, &str) >= 0) {
1607                 print_str(opt->name, str);
1608                 av_free(str);
1609             }
1610         }
1611     }
1612
1613     if (fmt_ctx->iformat->flags & AVFMT_SHOW_IDS) print_fmt    ("id", "0x%x", stream->id);
1614     else                                          print_str_opt("id", "N/A");
1615     print_fmt("r_frame_rate",   "%d/%d", stream->r_frame_rate.num,   stream->r_frame_rate.den);
1616     print_fmt("avg_frame_rate", "%d/%d", stream->avg_frame_rate.num, stream->avg_frame_rate.den);
1617     print_fmt("time_base",      "%d/%d", stream->time_base.num,      stream->time_base.den);
1618     print_time("start_time",    stream->start_time, &stream->time_base);
1619     print_time("duration",      stream->duration,   &stream->time_base);
1620     if (dec_ctx->bit_rate > 0) print_val    ("bit_rate", dec_ctx->bit_rate, unit_bit_per_second_str);
1621     else                       print_str_opt("bit_rate", "N/A");
1622     if (stream->nb_frames) print_fmt    ("nb_frames", "%"PRId64, stream->nb_frames);
1623     else                   print_str_opt("nb_frames", "N/A");
1624     if (nb_streams_frames[stream_idx])  print_fmt    ("nb_read_frames", "%"PRIu64, nb_streams_frames[stream_idx]);
1625     else                                print_str_opt("nb_read_frames", "N/A");
1626     if (nb_streams_packets[stream_idx]) print_fmt    ("nb_read_packets", "%"PRIu64, nb_streams_packets[stream_idx]);
1627     else                                print_str_opt("nb_read_packets", "N/A");
1628     show_tags(stream->metadata);
1629
1630     print_section_footer("stream");
1631     av_bprint_finalize(&pbuf, NULL);
1632     fflush(stdout);
1633 }
1634
1635 static void show_streams(WriterContext *w, AVFormatContext *fmt_ctx)
1636 {
1637     int i;
1638     for (i = 0; i < fmt_ctx->nb_streams; i++)
1639         show_stream(w, fmt_ctx, i);
1640 }
1641
1642 static void show_format(WriterContext *w, AVFormatContext *fmt_ctx)
1643 {
1644     char val_str[128];
1645     int64_t size = fmt_ctx->pb ? avio_size(fmt_ctx->pb) : -1;
1646
1647     print_section_header("format");
1648     print_str("filename",         fmt_ctx->filename);
1649     print_int("nb_streams",       fmt_ctx->nb_streams);
1650     print_str("format_name",      fmt_ctx->iformat->name);
1651     print_str("format_long_name", fmt_ctx->iformat->long_name);
1652     print_time("start_time",      fmt_ctx->start_time, &AV_TIME_BASE_Q);
1653     print_time("duration",        fmt_ctx->duration,   &AV_TIME_BASE_Q);
1654     if (size >= 0) print_val    ("size", size, unit_byte_str);
1655     else           print_str_opt("size", "N/A");
1656     if (fmt_ctx->bit_rate > 0) print_val    ("bit_rate", fmt_ctx->bit_rate, unit_bit_per_second_str);
1657     else                       print_str_opt("bit_rate", "N/A");
1658     show_tags(fmt_ctx->metadata);
1659     print_section_footer("format");
1660     fflush(stdout);
1661 }
1662
1663 static void show_error(WriterContext *w, int err)
1664 {
1665     char errbuf[128];
1666     const char *errbuf_ptr = errbuf;
1667
1668     if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
1669         errbuf_ptr = strerror(AVUNERROR(err));
1670
1671     writer_print_chapter_header(w, "error");
1672     print_section_header("error");
1673     print_int("code", err);
1674     print_str("string", errbuf_ptr);
1675     print_section_footer("error");
1676     writer_print_chapter_footer(w, "error");
1677 }
1678
1679 static int open_input_file(AVFormatContext **fmt_ctx_ptr, const char *filename)
1680 {
1681     int err, i;
1682     AVFormatContext *fmt_ctx = NULL;
1683     AVDictionaryEntry *t;
1684
1685     if ((err = avformat_open_input(&fmt_ctx, filename,
1686                                    iformat, &format_opts)) < 0) {
1687         print_error(filename, err);
1688         return err;
1689     }
1690     if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
1691         av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
1692         return AVERROR_OPTION_NOT_FOUND;
1693     }
1694
1695
1696     /* fill the streams in the format context */
1697     if ((err = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
1698         print_error(filename, err);
1699         return err;
1700     }
1701
1702     av_dump_format(fmt_ctx, 0, filename, 0);
1703
1704     /* bind a decoder to each input stream */
1705     for (i = 0; i < fmt_ctx->nb_streams; i++) {
1706         AVStream *stream = fmt_ctx->streams[i];
1707         AVCodec *codec;
1708
1709         if (!(codec = avcodec_find_decoder(stream->codec->codec_id))) {
1710             av_log(NULL, AV_LOG_ERROR,
1711                     "Unsupported codec with id %d for input stream %d\n",
1712                     stream->codec->codec_id, stream->index);
1713         } else if (avcodec_open2(stream->codec, codec, NULL) < 0) {
1714             av_log(NULL, AV_LOG_ERROR, "Error while opening codec for input stream %d\n",
1715                    stream->index);
1716         }
1717     }
1718
1719     *fmt_ctx_ptr = fmt_ctx;
1720     return 0;
1721 }
1722
1723 static void close_input_file(AVFormatContext **ctx_ptr)
1724 {
1725     int i;
1726     AVFormatContext *fmt_ctx = *ctx_ptr;
1727
1728     /* close decoder for each stream */
1729     for (i = 0; i < fmt_ctx->nb_streams; i++)
1730         if (fmt_ctx->streams[i]->codec->codec_id != CODEC_ID_NONE)
1731             avcodec_close(fmt_ctx->streams[i]->codec);
1732
1733     avformat_close_input(ctx_ptr);
1734 }
1735
1736 #define PRINT_CHAPTER(name) do {                                        \
1737     if (do_show_ ## name) {                                             \
1738         writer_print_chapter_header(wctx, #name);                       \
1739         show_ ## name (wctx, fmt_ctx);                                  \
1740         writer_print_chapter_footer(wctx, #name);                       \
1741     }                                                                   \
1742 } while (0)
1743
1744 static int probe_file(WriterContext *wctx, const char *filename)
1745 {
1746     AVFormatContext *fmt_ctx;
1747     int ret;
1748
1749     do_read_frames = do_show_frames || do_count_frames;
1750     do_read_packets = do_show_packets || do_count_packets;
1751
1752     ret = open_input_file(&fmt_ctx, filename);
1753     if (ret >= 0) {
1754         nb_streams_frames  = av_calloc(fmt_ctx->nb_streams, sizeof(*nb_streams_frames));
1755         nb_streams_packets = av_calloc(fmt_ctx->nb_streams, sizeof(*nb_streams_packets));
1756         if (do_read_frames || do_read_packets) {
1757             const char *chapter;
1758             if (do_show_frames && do_show_packets &&
1759                 wctx->writer->flags & WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER)
1760                 chapter = "packets_and_frames";
1761             else if (do_show_packets && !do_show_frames)
1762                 chapter = "packets";
1763             else // (!do_show_packets && do_show_frames)
1764                 chapter = "frames";
1765             if (do_show_frames || do_show_packets)
1766                 writer_print_chapter_header(wctx, chapter);
1767             read_packets(wctx, fmt_ctx);
1768             if (do_show_frames || do_show_packets)
1769                 writer_print_chapter_footer(wctx, chapter);
1770         }
1771         PRINT_CHAPTER(streams);
1772         PRINT_CHAPTER(format);
1773         close_input_file(&fmt_ctx);
1774         av_freep(&nb_streams_frames);
1775         av_freep(&nb_streams_packets);
1776     }
1777     return ret;
1778 }
1779
1780 static void show_usage(void)
1781 {
1782     av_log(NULL, AV_LOG_INFO, "Simple multimedia streams analyzer\n");
1783     av_log(NULL, AV_LOG_INFO, "usage: %s [OPTIONS] [INPUT_FILE]\n", program_name);
1784     av_log(NULL, AV_LOG_INFO, "\n");
1785 }
1786
1787 static void ffprobe_show_program_version(WriterContext *w)
1788 {
1789     AVBPrint pbuf;
1790     av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
1791
1792     writer_print_chapter_header(w, "program_version");
1793     print_section_header("program_version");
1794     print_str("version", FFMPEG_VERSION);
1795     print_fmt("copyright", "Copyright (c) %d-%d the FFmpeg developers",
1796               program_birth_year, this_year);
1797     print_str("build_date", __DATE__);
1798     print_str("build_time", __TIME__);
1799     print_str("compiler_type", CC_TYPE);
1800     print_str("compiler_version", CC_VERSION);
1801     print_str("configuration", FFMPEG_CONFIGURATION);
1802     print_section_footer("program_version");
1803     writer_print_chapter_footer(w, "program_version");
1804
1805     av_bprint_finalize(&pbuf, NULL);
1806 }
1807
1808 #define SHOW_LIB_VERSION(libname, LIBNAME)                              \
1809     do {                                                                \
1810         if (CONFIG_##LIBNAME) {                                         \
1811             unsigned int version = libname##_version();                 \
1812             print_section_header("library_version");                    \
1813             print_str("name",    "lib" #libname);                       \
1814             print_int("major",   LIB##LIBNAME##_VERSION_MAJOR);         \
1815             print_int("minor",   LIB##LIBNAME##_VERSION_MINOR);         \
1816             print_int("micro",   LIB##LIBNAME##_VERSION_MICRO);         \
1817             print_int("version", version);                              \
1818             print_section_footer("library_version");                    \
1819         }                                                               \
1820     } while (0)
1821
1822 static void ffprobe_show_library_versions(WriterContext *w)
1823 {
1824     writer_print_chapter_header(w, "library_versions");
1825     SHOW_LIB_VERSION(avutil,     AVUTIL);
1826     SHOW_LIB_VERSION(avcodec,    AVCODEC);
1827     SHOW_LIB_VERSION(avformat,   AVFORMAT);
1828     SHOW_LIB_VERSION(avdevice,   AVDEVICE);
1829     SHOW_LIB_VERSION(avfilter,   AVFILTER);
1830     SHOW_LIB_VERSION(swscale,    SWSCALE);
1831     SHOW_LIB_VERSION(swresample, SWRESAMPLE);
1832     SHOW_LIB_VERSION(postproc,   POSTPROC);
1833     writer_print_chapter_footer(w, "library_versions");
1834 }
1835
1836 static int opt_format(const char *opt, const char *arg)
1837 {
1838     iformat = av_find_input_format(arg);
1839     if (!iformat) {
1840         av_log(NULL, AV_LOG_ERROR, "Unknown input format: %s\n", arg);
1841         return AVERROR(EINVAL);
1842     }
1843     return 0;
1844 }
1845
1846 static int opt_show_format_entry(const char *opt, const char *arg)
1847 {
1848     do_show_format = 1;
1849     av_dict_set(&fmt_entries_to_show, arg, "", 0);
1850     return 0;
1851 }
1852
1853 static void opt_input_file(void *optctx, const char *arg)
1854 {
1855     if (input_filename) {
1856         av_log(NULL, AV_LOG_ERROR,
1857                 "Argument '%s' provided as input filename, but '%s' was already specified.\n",
1858                 arg, input_filename);
1859         exit(1);
1860     }
1861     if (!strcmp(arg, "-"))
1862         arg = "pipe:";
1863     input_filename = arg;
1864 }
1865
1866 static int opt_help(const char *opt, const char *arg)
1867 {
1868     av_log_set_callback(log_callback_help);
1869     show_usage();
1870     show_help_options(options, "Main options:\n", 0, 0);
1871     printf("\n");
1872
1873     show_help_children(avformat_get_class(), AV_OPT_FLAG_DECODING_PARAM);
1874
1875     return 0;
1876 }
1877
1878 static int opt_pretty(const char *opt, const char *arg)
1879 {
1880     show_value_unit              = 1;
1881     use_value_prefix             = 1;
1882     use_byte_value_binary_prefix = 1;
1883     use_value_sexagesimal_format = 1;
1884     return 0;
1885 }
1886
1887 static int opt_show_versions(const char *opt, const char *arg)
1888 {
1889     do_show_program_version  = 1;
1890     do_show_library_versions = 1;
1891     return 0;
1892 }
1893
1894 static const OptionDef options[] = {
1895 #include "cmdutils_common_opts.h"
1896     { "f", HAS_ARG, {(void*)opt_format}, "force format", "format" },
1897     { "unit", OPT_BOOL, {(void*)&show_value_unit}, "show unit of the displayed values" },
1898     { "prefix", OPT_BOOL, {(void*)&use_value_prefix}, "use SI prefixes for the displayed values" },
1899     { "byte_binary_prefix", OPT_BOOL, {(void*)&use_byte_value_binary_prefix},
1900       "use binary prefixes for byte units" },
1901     { "sexagesimal", OPT_BOOL,  {(void*)&use_value_sexagesimal_format},
1902       "use sexagesimal format HOURS:MM:SS.MICROSECONDS for time units" },
1903     { "pretty", 0, {(void*)&opt_pretty},
1904       "prettify the format of displayed values, make it more human readable" },
1905     { "print_format", OPT_STRING | HAS_ARG, {(void*)&print_format},
1906       "set the output printing format (available formats are: default, compact, csv, ini, json, xml)", "format" },
1907     { "show_error",   OPT_BOOL, {(void*)&do_show_error} ,  "show probing error" },
1908     { "show_format",  OPT_BOOL, {(void*)&do_show_format} , "show format/container info" },
1909     { "show_frames",  OPT_BOOL, {(void*)&do_show_frames} , "show frames info" },
1910     { "show_format_entry", HAS_ARG, {(void*)opt_show_format_entry},
1911       "show a particular entry from the format/container info", "entry" },
1912     { "show_packets", OPT_BOOL, {(void*)&do_show_packets}, "show packets info" },
1913     { "show_streams", OPT_BOOL, {(void*)&do_show_streams}, "show streams info" },
1914     { "count_frames", OPT_BOOL, {(void*)&do_count_frames}, "count the number of frames per stream" },
1915     { "count_packets", OPT_BOOL, {(void*)&do_count_packets}, "count the number of packets per stream" },
1916     { "show_program_version",  OPT_BOOL, {(void*)&do_show_program_version},  "show ffprobe version" },
1917     { "show_library_versions", OPT_BOOL, {(void*)&do_show_library_versions}, "show library versions" },
1918     { "show_versions",         0, {(void*)&opt_show_versions}, "show program and library versions" },
1919     { "show_private_data", OPT_BOOL, {(void*)&show_private_data}, "show private data" },
1920     { "private",           OPT_BOOL, {(void*)&show_private_data}, "same as show_private_data" },
1921     { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
1922     { "i", HAS_ARG, {(void *)opt_input_file}, "read specified file", "input_file"},
1923     { NULL, },
1924 };
1925
1926 int main(int argc, char **argv)
1927 {
1928     const Writer *w;
1929     WriterContext *wctx;
1930     char *buf;
1931     char *w_name = NULL, *w_args = NULL;
1932     int ret;
1933
1934     av_log_set_flags(AV_LOG_SKIP_REPEATED);
1935     parse_loglevel(argc, argv, options);
1936     av_register_all();
1937     avformat_network_init();
1938     init_opts();
1939 #if CONFIG_AVDEVICE
1940     avdevice_register_all();
1941 #endif
1942
1943     show_banner(argc, argv, options);
1944     parse_options(NULL, argc, argv, options, opt_input_file);
1945
1946     writer_register_all();
1947
1948     if (!print_format)
1949         print_format = av_strdup("default");
1950     w_name = av_strtok(print_format, "=", &buf);
1951     w_args = buf;
1952
1953     w = writer_get_by_name(w_name);
1954     if (!w) {
1955         av_log(NULL, AV_LOG_ERROR, "Unknown output format with name '%s'\n", w_name);
1956         ret = AVERROR(EINVAL);
1957         goto end;
1958     }
1959
1960     if ((ret = writer_open(&wctx, w, w_args, NULL)) >= 0) {
1961         writer_print_header(wctx);
1962
1963         if (do_show_program_version)
1964             ffprobe_show_program_version(wctx);
1965         if (do_show_library_versions)
1966             ffprobe_show_library_versions(wctx);
1967
1968         if (!input_filename &&
1969             ((do_show_format || do_show_streams || do_show_packets || do_show_error) ||
1970              (!do_show_program_version && !do_show_library_versions))) {
1971             show_usage();
1972             av_log(NULL, AV_LOG_ERROR, "You have to specify one input file.\n");
1973             av_log(NULL, AV_LOG_ERROR, "Use -h to get full help or, even better, run 'man %s'.\n", program_name);
1974             ret = AVERROR(EINVAL);
1975         } else if (input_filename) {
1976             ret = probe_file(wctx, input_filename);
1977             if (ret < 0 && do_show_error)
1978                 show_error(wctx, ret);
1979         }
1980
1981         writer_print_footer(wctx);
1982         writer_close(&wctx);
1983     }
1984
1985 end:
1986     av_freep(&print_format);
1987
1988     uninit_opts();
1989     av_dict_free(&fmt_entries_to_show);
1990
1991     avformat_network_deinit();
1992
1993     return ret;
1994 }