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