]> git.sesse.net Git - ffmpeg/blob - ffprobe.c
ffprobe: fix NULL pointer dereference in writer_close()
[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
28 #include "libavformat/avformat.h"
29 #include "libavcodec/avcodec.h"
30 #include "libavutil/avstring.h"
31 #include "libavutil/opt.h"
32 #include "libavutil/pixdesc.h"
33 #include "libavutil/dict.h"
34 #include "libavdevice/avdevice.h"
35 #include "cmdutils.h"
36
37 const char program_name[] = "ffprobe";
38 const int program_birth_year = 2007;
39
40 static int do_show_error   = 0;
41 static int do_show_format  = 0;
42 static int do_show_packets = 0;
43 static int do_show_streams = 0;
44
45 static int show_value_unit              = 0;
46 static int use_value_prefix             = 0;
47 static int use_byte_value_binary_prefix = 0;
48 static int use_value_sexagesimal_format = 0;
49 static int show_private_data            = 1;
50
51 static char *print_format;
52
53 static const OptionDef options[];
54
55 /* FFprobe context */
56 static const char *input_filename;
57 static AVInputFormat *iformat = NULL;
58
59 static const char *binary_unit_prefixes [] = { "", "Ki", "Mi", "Gi", "Ti", "Pi" };
60 static const char *decimal_unit_prefixes[] = { "", "K" , "M" , "G" , "T" , "P"  };
61
62 static const char *unit_second_str          = "s"    ;
63 static const char *unit_hertz_str           = "Hz"   ;
64 static const char *unit_byte_str            = "byte" ;
65 static const char *unit_bit_per_second_str  = "bit/s";
66
67 void av_noreturn exit_program(int ret)
68 {
69     exit(ret);
70 }
71
72 struct unit_value {
73     union { double d; int i; } val;
74     const char *unit;
75 };
76
77 static char *value_string(char *buf, int buf_size, struct unit_value uv)
78 {
79     double vald;
80     int show_float = 0;
81
82     if (uv.unit == unit_second_str) {
83         vald = uv.val.d;
84         show_float = 1;
85     } else {
86         vald = uv.val.i;
87     }
88
89     if (uv.unit == unit_second_str && use_value_sexagesimal_format) {
90         double secs;
91         int hours, mins;
92         secs  = vald;
93         mins  = (int)secs / 60;
94         secs  = secs - mins * 60;
95         hours = mins / 60;
96         mins %= 60;
97         snprintf(buf, buf_size, "%d:%02d:%09.6f", hours, mins, secs);
98     } else if (use_value_prefix) {
99         const char *prefix_string;
100         int index, l;
101
102         if (uv.unit == unit_byte_str && use_byte_value_binary_prefix) {
103             index = (int) (log(vald)/log(2)) / 10;
104             index = av_clip(index, 0, FF_ARRAY_ELEMS(binary_unit_prefixes) -1);
105             vald /= pow(2, index*10);
106             prefix_string = binary_unit_prefixes[index];
107         } else {
108             index = (int) (log10(vald)) / 3;
109             index = av_clip(index, 0, FF_ARRAY_ELEMS(decimal_unit_prefixes) -1);
110             vald /= pow(10, index*3);
111             prefix_string = decimal_unit_prefixes[index];
112         }
113
114         if (show_float || vald != (int)vald) l = snprintf(buf, buf_size, "%.3f", vald);
115         else                                 l = snprintf(buf, buf_size, "%d",   (int)vald);
116         snprintf(buf+l, buf_size-l, "%s%s%s", prefix_string || show_value_unit ? " " : "",
117                  prefix_string, show_value_unit ? uv.unit : "");
118     } else {
119         int l;
120
121         if (show_float) l = snprintf(buf, buf_size, "%.3f", vald);
122         else            l = snprintf(buf, buf_size, "%d",   (int)vald);
123         snprintf(buf+l, buf_size-l, "%s%s", show_value_unit ? " " : "",
124                  show_value_unit ? uv.unit : "");
125     }
126
127     return buf;
128 }
129
130 /* WRITERS API */
131
132 typedef struct WriterContext WriterContext;
133
134 #define WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS 1
135
136 typedef struct Writer {
137     int priv_size;                  ///< private size for the writer context
138     const char *name;
139
140     int  (*init)  (WriterContext *wctx, const char *args, void *opaque);
141     void (*uninit)(WriterContext *wctx);
142
143     void (*print_header)(WriterContext *ctx);
144     void (*print_footer)(WriterContext *ctx);
145
146     void (*print_chapter_header)(WriterContext *wctx, const char *);
147     void (*print_chapter_footer)(WriterContext *wctx, const char *);
148     void (*print_section_header)(WriterContext *wctx, const char *);
149     void (*print_section_footer)(WriterContext *wctx, const char *);
150     void (*print_integer)       (WriterContext *wctx, const char *, long long int);
151     void (*print_string)        (WriterContext *wctx, const char *, const char *);
152     void (*show_tags)           (WriterContext *wctx, AVDictionary *dict);
153     int flags;                  ///< a combination or WRITER_FLAG_*
154 } Writer;
155
156 struct WriterContext {
157     const AVClass *class;           ///< class of the writer
158     const Writer *writer;           ///< the Writer of which this is an instance
159     char *name;                     ///< name of this writer instance
160     void *priv;                     ///< private data for use by the filter
161     unsigned int nb_item;           ///< number of the item printed in the given section, starting at 0
162     unsigned int nb_section;        ///< number of the section printed in the given section sequence, starting at 0
163     unsigned int nb_chapter;        ///< number of the chapter, starting at 0
164 };
165
166 static const char *writer_get_name(void *p)
167 {
168     WriterContext *wctx = p;
169     return wctx->writer->name;
170 }
171
172 static const AVClass writer_class = {
173     "Writer",
174     writer_get_name,
175     NULL,
176     LIBAVUTIL_VERSION_INT,
177 };
178
179 static void writer_close(WriterContext **wctx)
180 {
181     if (!*wctx)
182         return;
183
184     if ((*wctx)->writer->uninit)
185         (*wctx)->writer->uninit(*wctx);
186     av_freep(&((*wctx)->priv));
187     av_freep(wctx);
188 }
189
190 static int writer_open(WriterContext **wctx, const Writer *writer,
191                        const char *args, void *opaque)
192 {
193     int ret = 0;
194
195     if (!(*wctx = av_malloc(sizeof(WriterContext)))) {
196         ret = AVERROR(ENOMEM);
197         goto fail;
198     }
199
200     if (!((*wctx)->priv = av_mallocz(writer->priv_size))) {
201         ret = AVERROR(ENOMEM);
202         goto fail;
203     }
204
205     (*wctx)->class = &writer_class;
206     (*wctx)->writer = writer;
207     if ((*wctx)->writer->init)
208         ret = (*wctx)->writer->init(*wctx, args, opaque);
209     if (ret < 0)
210         goto fail;
211
212     return 0;
213
214 fail:
215     writer_close(wctx);
216     return ret;
217 }
218
219 static inline void writer_print_header(WriterContext *wctx)
220 {
221     if (wctx->writer->print_header)
222         wctx->writer->print_header(wctx);
223     wctx->nb_chapter = 0;
224 }
225
226 static inline void writer_print_footer(WriterContext *wctx)
227 {
228     if (wctx->writer->print_footer)
229         wctx->writer->print_footer(wctx);
230 }
231
232 static inline void writer_print_chapter_header(WriterContext *wctx,
233                                                const char *header)
234 {
235     if (wctx->writer->print_chapter_header)
236         wctx->writer->print_chapter_header(wctx, header);
237     wctx->nb_section = 0;
238 }
239
240 static inline void writer_print_chapter_footer(WriterContext *wctx,
241                                                const char *footer)
242 {
243     if (wctx->writer->print_chapter_footer)
244         wctx->writer->print_chapter_footer(wctx, footer);
245     wctx->nb_chapter++;
246 }
247
248 static inline void writer_print_section_header(WriterContext *wctx,
249                                                const char *header)
250 {
251     if (wctx->writer->print_section_header)
252         wctx->writer->print_section_header(wctx, header);
253     wctx->nb_item = 0;
254 }
255
256 static inline void writer_print_section_footer(WriterContext *wctx,
257                                                const char *footer)
258 {
259     if (wctx->writer->print_section_footer)
260         wctx->writer->print_section_footer(wctx, footer);
261     wctx->nb_section++;
262 }
263
264 static inline void writer_print_integer(WriterContext *wctx,
265                                         const char *key, long long int val)
266 {
267     wctx->writer->print_integer(wctx, key, val);
268     wctx->nb_item++;
269 }
270
271 static inline void writer_print_string(WriterContext *wctx,
272                                        const char *key, const char *val, int opt)
273 {
274     if (opt && !(wctx->writer->flags & WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS))
275         return;
276     wctx->writer->print_string(wctx, key, val);
277     wctx->nb_item++;
278 }
279
280 static void writer_print_time(WriterContext *wctx, const char *key,
281                               int64_t ts, const AVRational *time_base)
282 {
283     char buf[128];
284
285     if (ts == AV_NOPTS_VALUE) {
286         writer_print_string(wctx, key, "N/A", 1);
287     } else {
288         double d = ts * av_q2d(*time_base);
289         value_string(buf, sizeof(buf), (struct unit_value){.val.d=d, .unit=unit_second_str});
290         writer_print_string(wctx, key, buf, 0);
291     }
292 }
293
294 static void writer_print_ts(WriterContext *wctx, const char *key, int64_t ts)
295 {
296     if (ts == AV_NOPTS_VALUE) {
297         writer_print_string(wctx, key, "N/A", 1);
298     } else {
299         writer_print_integer(wctx, key, ts);
300     }
301 }
302
303 static inline void writer_show_tags(WriterContext *wctx, AVDictionary *dict)
304 {
305     wctx->writer->show_tags(wctx, dict);
306 }
307
308 #define MAX_REGISTERED_WRITERS_NB 64
309
310 static const Writer *registered_writers[MAX_REGISTERED_WRITERS_NB + 1];
311
312 static int writer_register(const Writer *writer)
313 {
314     static int next_registered_writer_idx = 0;
315
316     if (next_registered_writer_idx == MAX_REGISTERED_WRITERS_NB)
317         return AVERROR(ENOMEM);
318
319     registered_writers[next_registered_writer_idx++] = writer;
320     return 0;
321 }
322
323 static const Writer *writer_get_by_name(const char *name)
324 {
325     int i;
326
327     for (i = 0; registered_writers[i]; i++)
328         if (!strcmp(registered_writers[i]->name, name))
329             return registered_writers[i];
330
331     return NULL;
332 }
333
334 /* Print helpers */
335
336 struct print_buf {
337     char *s;
338     int len;
339 };
340
341 static char *fast_asprintf(struct print_buf *pbuf, const char *fmt, ...)
342 {
343     va_list va;
344     int len;
345
346     va_start(va, fmt);
347     len = vsnprintf(NULL, 0, fmt, va);
348     va_end(va);
349     if (len < 0)
350         goto fail;
351
352     if (pbuf->len < len) {
353         char *p = av_realloc(pbuf->s, len + 1);
354         if (!p)
355             goto fail;
356         pbuf->s   = p;
357         pbuf->len = len;
358     }
359
360     va_start(va, fmt);
361     len = vsnprintf(pbuf->s, len + 1, fmt, va);
362     va_end(va);
363     if (len < 0)
364         goto fail;
365     return pbuf->s;
366
367 fail:
368     av_freep(&pbuf->s);
369     pbuf->len = 0;
370     return NULL;
371 }
372
373 #define ESCAPE_INIT_BUF_SIZE 256
374
375 #define ESCAPE_CHECK_SIZE(src, size, max_size)                          \
376     if (size > max_size) {                                              \
377         char buf[64];                                                   \
378         snprintf(buf, sizeof(buf), "%s", src);                          \
379         av_log(log_ctx, AV_LOG_WARNING,                                 \
380                "String '%s...' with is too big\n", buf);                \
381         return "FFPROBE_TOO_BIG_STRING";                                \
382     }
383
384 #define ESCAPE_REALLOC_BUF(dst_size_p, dst_p, src, size)                \
385     if (*dst_size_p < size) {                                           \
386         char *q = av_realloc(*dst_p, size);                             \
387         if (!q) {                                                       \
388             char buf[64];                                               \
389             snprintf(buf, sizeof(buf), "%s", src);                      \
390             av_log(log_ctx, AV_LOG_WARNING,                             \
391                    "String '%s...' could not be escaped\n", buf);       \
392             return "FFPROBE_THIS_STRING_COULD_NOT_BE_ESCAPED";          \
393         }                                                               \
394         *dst_size_p = size;                                             \
395         *dst = q;                                                       \
396     }
397
398 /* WRITERS */
399
400 /* Default output */
401
402 static void default_print_footer(WriterContext *wctx)
403 {
404     printf("\n");
405 }
406
407 static void default_print_chapter_header(WriterContext *wctx, const char *chapter)
408 {
409     if (wctx->nb_chapter)
410         printf("\n");
411 }
412
413 /* lame uppercasing routine, assumes the string is lower case ASCII */
414 static inline char *upcase_string(char *dst, size_t dst_size, const char *src)
415 {
416     int i;
417     for (i = 0; src[i] && i < dst_size-1; i++)
418         dst[i] = src[i]-32;
419     dst[i] = 0;
420     return dst;
421 }
422
423 static void default_print_section_header(WriterContext *wctx, const char *section)
424 {
425     char buf[32];
426
427     if (wctx->nb_section)
428         printf("\n");
429     printf("[%s]\n", upcase_string(buf, sizeof(buf), section));
430 }
431
432 static void default_print_section_footer(WriterContext *wctx, const char *section)
433 {
434     char buf[32];
435
436     printf("[/%s]", upcase_string(buf, sizeof(buf), section));
437 }
438
439 static void default_print_str(WriterContext *wctx, const char *key, const char *value)
440 {
441     printf("%s=%s\n", key, value);
442 }
443
444 static void default_print_int(WriterContext *wctx, const char *key, long long int value)
445 {
446     printf("%s=%lld\n", key, value);
447 }
448
449 static void default_show_tags(WriterContext *wctx, AVDictionary *dict)
450 {
451     AVDictionaryEntry *tag = NULL;
452     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
453         printf("TAG:");
454         writer_print_string(wctx, tag->key, tag->value, 0);
455     }
456 }
457
458 static const Writer default_writer = {
459     .name                  = "default",
460     .print_footer          = default_print_footer,
461     .print_chapter_header  = default_print_chapter_header,
462     .print_section_header  = default_print_section_header,
463     .print_section_footer  = default_print_section_footer,
464     .print_integer         = default_print_int,
465     .print_string          = default_print_str,
466     .show_tags             = default_show_tags,
467     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
468 };
469
470 /* Compact output */
471
472 /**
473  * Escape \n, \r, \\ and sep characters contained in s, and print the
474  * resulting string.
475  */
476 static const char *c_escape_str(char **dst, size_t *dst_size,
477                                 const char *src, const char sep, void *log_ctx)
478 {
479     const char *p;
480     char *q;
481     size_t size = 1;
482
483     /* precompute size */
484     for (p = src; *p; p++, size++) {
485         ESCAPE_CHECK_SIZE(src, size, SIZE_MAX-2);
486         if (*p == '\n' || *p == '\r' || *p == '\\')
487             size++;
488     }
489
490     ESCAPE_REALLOC_BUF(dst_size, dst, src, size);
491
492     q = *dst;
493     for (p = src; *p; p++) {
494         switch (*src) {
495         case '\n': *q++ = '\\'; *q++ = 'n';  break;
496         case '\r': *q++ = '\\'; *q++ = 'r';  break;
497         case '\\': *q++ = '\\'; *q++ = '\\'; break;
498         default:
499             if (*p == sep)
500                 *q++ = '\\';
501             *q++ = *p;
502         }
503     }
504     *q = 0;
505     return *dst;
506 }
507
508 /**
509  * Quote fields containing special characters, check RFC4180.
510  */
511 static const char *csv_escape_str(char **dst, size_t *dst_size,
512                                   const char *src, const char sep, void *log_ctx)
513 {
514     const char *p;
515     char *q;
516     size_t size = 1;
517     int quote = 0;
518
519     /* precompute size */
520     for (p = src; *p; p++, size++) {
521         ESCAPE_CHECK_SIZE(src, size, SIZE_MAX-4);
522         if (*p == '"' || *p == sep || *p == '\n' || *p == '\r')
523             if (!quote) {
524                 quote = 1;
525                 size += 2;
526             }
527         if (*p == '"')
528             size++;
529     }
530
531     ESCAPE_REALLOC_BUF(dst_size, dst, src, size);
532
533     q = *dst;
534     p = src;
535     if (quote)
536         *q++ = '\"';
537     while (*p) {
538         if (*p == '"')
539             *q++ = '\"';
540         *q++ = *p++;
541     }
542     if (quote)
543         *q++ = '\"';
544     *q = 0;
545
546     return *dst;
547 }
548
549 static const char *none_escape_str(char **dst, size_t *dst_size,
550                                    const char *src, const char sep, void *log_ctx)
551 {
552     return src;
553 }
554
555 typedef struct CompactContext {
556     const AVClass *class;
557     char *item_sep_str;
558     char item_sep;
559     int nokey;
560     char  *buf;
561     size_t buf_size;
562     char *escape_mode_str;
563     const char * (*escape_str)(char **dst, size_t *dst_size,
564                                const char *src, const char sep, void *log_ctx);
565 } CompactContext;
566
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     compact->buf_size = ESCAPE_INIT_BUF_SIZE;
611     if (!(compact->buf = av_malloc(compact->buf_size)))
612         return AVERROR(ENOMEM);
613
614     if      (!strcmp(compact->escape_mode_str, "none")) compact->escape_str = none_escape_str;
615     else if (!strcmp(compact->escape_mode_str, "c"   )) compact->escape_str = c_escape_str;
616     else if (!strcmp(compact->escape_mode_str, "csv" )) compact->escape_str = csv_escape_str;
617     else {
618         av_log(wctx, AV_LOG_ERROR, "Unknown escape mode '%s'\n", compact->escape_mode_str);
619         return AVERROR(EINVAL);
620     }
621
622     return 0;
623 }
624
625 static av_cold void compact_uninit(WriterContext *wctx)
626 {
627     CompactContext *compact = wctx->priv;
628
629     av_freep(&compact->item_sep_str);
630     av_freep(&compact->buf);
631     av_freep(&compact->escape_mode_str);
632 }
633
634 static void compact_print_section_header(WriterContext *wctx, const char *section)
635 {
636     CompactContext *compact = wctx->priv;
637
638     printf("%s%c", section, compact->item_sep);
639 }
640
641 static void compact_print_section_footer(WriterContext *wctx, const char *section)
642 {
643     printf("\n");
644 }
645
646 static void compact_print_str(WriterContext *wctx, const char *key, const char *value)
647 {
648     CompactContext *compact = wctx->priv;
649
650     if (wctx->nb_item) printf("%c", compact->item_sep);
651     if (!compact->nokey)
652         printf("%s=", key);
653     printf("%s", compact->escape_str(&compact->buf, &compact->buf_size,
654                                      value, compact->item_sep, wctx));
655 }
656
657 static void compact_print_int(WriterContext *wctx, const char *key, long long int value)
658 {
659     CompactContext *compact = wctx->priv;
660
661     if (wctx->nb_item) printf("%c", compact->item_sep);
662     if (!compact->nokey)
663         printf("%s=", key);
664     printf("%lld", value);
665 }
666
667 static void compact_show_tags(WriterContext *wctx, AVDictionary *dict)
668 {
669     CompactContext *compact = wctx->priv;
670     AVDictionaryEntry *tag = NULL;
671
672     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
673         if (wctx->nb_item) printf("%c", compact->item_sep);
674         if (!compact->nokey)
675             printf("tag:%s=", compact->escape_str(&compact->buf, &compact->buf_size,
676                                                   tag->key, compact->item_sep, wctx));
677         printf("%s", compact->escape_str(&compact->buf, &compact->buf_size,
678                                          tag->value, compact->item_sep, wctx));
679     }
680 }
681
682 static const Writer compact_writer = {
683     .name                 = "compact",
684     .priv_size            = sizeof(CompactContext),
685     .init                 = compact_init,
686     .uninit               = compact_uninit,
687     .print_section_header = compact_print_section_header,
688     .print_section_footer = compact_print_section_footer,
689     .print_integer        = compact_print_int,
690     .print_string         = compact_print_str,
691     .show_tags            = compact_show_tags,
692     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
693 };
694
695 /* CSV output */
696
697 static av_cold int csv_init(WriterContext *wctx, const char *args, void *opaque)
698 {
699     return compact_init(wctx, "item_sep=,:nokey=1:escape=csv", opaque);
700 }
701
702 static const Writer csv_writer = {
703     .name                 = "csv",
704     .priv_size            = sizeof(CompactContext),
705     .init                 = csv_init,
706     .uninit               = compact_uninit,
707     .print_section_header = compact_print_section_header,
708     .print_section_footer = compact_print_section_footer,
709     .print_integer        = compact_print_int,
710     .print_string         = compact_print_str,
711     .show_tags            = compact_show_tags,
712     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
713 };
714
715 /* JSON output */
716
717 typedef struct {
718     int multiple_entries; ///< tells if the given chapter requires multiple entries
719     char *buf;
720     size_t buf_size;
721 } JSONContext;
722
723 static av_cold int json_init(WriterContext *wctx, const char *args, void *opaque)
724 {
725     JSONContext *json = wctx->priv;
726
727     json->buf_size = ESCAPE_INIT_BUF_SIZE;
728     if (!(json->buf = av_malloc(json->buf_size)))
729         return AVERROR(ENOMEM);
730
731     return 0;
732 }
733
734 static av_cold void json_uninit(WriterContext *wctx)
735 {
736     JSONContext *json = wctx->priv;
737     av_freep(&json->buf);
738 }
739
740 static const char *json_escape_str(char **dst, size_t *dst_size, const char *src,
741                                    void *log_ctx)
742 {
743     static const char json_escape[] = {'"', '\\', '\b', '\f', '\n', '\r', '\t', 0};
744     static const char json_subst[]  = {'"', '\\',  'b',  'f',  'n',  'r',  't', 0};
745     const char *p;
746     char *q;
747     size_t size = 1;
748
749     // compute the length of the escaped string
750     for (p = src; *p; p++) {
751         ESCAPE_CHECK_SIZE(src, size, SIZE_MAX-6);
752         if (strchr(json_escape, *p))     size += 2; // simple escape
753         else if ((unsigned char)*p < 32) size += 6; // handle non-printable chars
754         else                             size += 1; // char copy
755     }
756     ESCAPE_REALLOC_BUF(dst_size, dst, src, size);
757
758     q = *dst;
759     for (p = src; *p; p++) {
760         char *s = strchr(json_escape, *p);
761         if (s) {
762             *q++ = '\\';
763             *q++ = json_subst[s - json_escape];
764         } else if ((unsigned char)*p < 32) {
765             snprintf(q, 7, "\\u00%02x", *p & 0xff);
766             q += 6;
767         } else {
768             *q++ = *p;
769         }
770     }
771     *q = 0;
772     return *dst;
773 }
774
775 static void json_print_header(WriterContext *wctx)
776 {
777     printf("{");
778 }
779
780 static void json_print_footer(WriterContext *wctx)
781 {
782     printf("\n}\n");
783 }
784
785 static void json_print_chapter_header(WriterContext *wctx, const char *chapter)
786 {
787     JSONContext *json = wctx->priv;
788
789     if (wctx->nb_chapter)
790         printf(",");
791     json->multiple_entries = !strcmp(chapter, "packets") || !strcmp(chapter, "streams");
792     printf("\n  \"%s\":%s", json_escape_str(&json->buf, &json->buf_size, chapter, wctx),
793            json->multiple_entries ? " [" : " ");
794 }
795
796 static void json_print_chapter_footer(WriterContext *wctx, const char *chapter)
797 {
798     JSONContext *json = wctx->priv;
799
800     if (json->multiple_entries)
801         printf("]");
802 }
803
804 static void json_print_section_header(WriterContext *wctx, const char *section)
805 {
806     if (wctx->nb_section) printf(",");
807     printf("{\n");
808 }
809
810 static void json_print_section_footer(WriterContext *wctx, const char *section)
811 {
812     printf("\n  }");
813 }
814
815 static inline void json_print_item_str(WriterContext *wctx,
816                                        const char *key, const char *value,
817                                        const char *indent)
818 {
819     JSONContext *json = wctx->priv;
820
821     printf("%s\"%s\":", indent, json_escape_str(&json->buf, &json->buf_size, key,   wctx));
822     printf(" \"%s\"",           json_escape_str(&json->buf, &json->buf_size, value, wctx));
823 }
824
825 #define INDENT "    "
826
827 static void json_print_str(WriterContext *wctx, const char *key, const char *value)
828 {
829     if (wctx->nb_item) printf(",\n");
830     json_print_item_str(wctx, key, value, INDENT);
831 }
832
833 static void json_print_int(WriterContext *wctx, const char *key, long long int value)
834 {
835     JSONContext *json = wctx->priv;
836
837     if (wctx->nb_item) printf(",\n");
838     printf(INDENT "\"%s\": %lld",
839            json_escape_str(&json->buf, &json->buf_size, key, wctx), value);
840 }
841
842 static void json_show_tags(WriterContext *wctx, AVDictionary *dict)
843 {
844     AVDictionaryEntry *tag = NULL;
845     int is_first = 1;
846     if (!dict)
847         return;
848     printf(",\n" INDENT "\"tags\": {\n");
849     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
850         if (is_first) is_first = 0;
851         else          printf(",\n");
852         json_print_item_str(wctx, tag->key, tag->value, INDENT INDENT);
853     }
854     printf("\n    }");
855 }
856
857 static const Writer json_writer = {
858     .name                 = "json",
859     .priv_size            = sizeof(JSONContext),
860     .init                 = json_init,
861     .uninit               = json_uninit,
862     .print_header         = json_print_header,
863     .print_footer         = json_print_footer,
864     .print_chapter_header = json_print_chapter_header,
865     .print_chapter_footer = json_print_chapter_footer,
866     .print_section_header = json_print_section_header,
867     .print_section_footer = json_print_section_footer,
868     .print_integer        = json_print_int,
869     .print_string         = json_print_str,
870     .show_tags            = json_show_tags,
871 };
872
873 /* XML output */
874
875 typedef struct {
876     const AVClass *class;
877     int within_tag;
878     int multiple_entries; ///< tells if the given chapter requires multiple entries
879     int indent_level;
880     int fully_qualified;
881     int xsd_strict;
882     char *buf;
883     size_t buf_size;
884 } XMLContext;
885
886 #undef OFFSET
887 #define OFFSET(x) offsetof(XMLContext, x)
888
889 static const AVOption xml_options[] = {
890     {"fully_qualified", "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_INT, {.dbl=0},  0, 1 },
891     {"q",               "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_INT, {.dbl=0},  0, 1 },
892     {"xsd_strict",      "ensure that the output is XSD compliant",         OFFSET(xsd_strict),      AV_OPT_TYPE_INT, {.dbl=0},  0, 1 },
893     {"x",               "ensure that the output is XSD compliant",         OFFSET(xsd_strict),      AV_OPT_TYPE_INT, {.dbl=0},  0, 1 },
894     {NULL},
895 };
896
897 static const char *xml_get_name(void *ctx)
898 {
899     return "xml";
900 }
901
902 static const AVClass xml_class = {
903     "XMLContext",
904     xml_get_name,
905     xml_options
906 };
907
908 static av_cold int xml_init(WriterContext *wctx, const char *args, void *opaque)
909 {
910     XMLContext *xml = wctx->priv;
911     int err;
912
913     xml->class = &xml_class;
914     av_opt_set_defaults(xml);
915
916     if (args &&
917         (err = (av_set_options_string(xml, args, "=", ":"))) < 0) {
918         av_log(wctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
919         return err;
920     }
921
922     if (xml->xsd_strict) {
923         xml->fully_qualified = 1;
924 #define CHECK_COMPLIANCE(opt, opt_name)                                 \
925         if (opt) {                                                      \
926             av_log(wctx, AV_LOG_ERROR,                                  \
927                    "XSD-compliant output selected but option '%s' was selected, XML output may be non-compliant.\n" \
928                    "You need to disable such option with '-no%s'\n", opt_name, opt_name); \
929         }
930         CHECK_COMPLIANCE(show_private_data, "private");
931         CHECK_COMPLIANCE(show_value_unit,   "unit");
932         CHECK_COMPLIANCE(use_value_prefix,  "prefix");
933     }
934
935     xml->buf_size = ESCAPE_INIT_BUF_SIZE;
936     if (!(xml->buf = av_malloc(xml->buf_size)))
937         return AVERROR(ENOMEM);
938     return 0;
939 }
940
941 static av_cold void xml_uninit(WriterContext *wctx)
942 {
943     XMLContext *xml = wctx->priv;
944     av_freep(&xml->buf);
945 }
946
947 static const char *xml_escape_str(char **dst, size_t *dst_size, const char *src,
948                                   void *log_ctx)
949 {
950     const char *p;
951     char *q;
952     size_t size = 1;
953
954     /* precompute size */
955     for (p = src; *p; p++, size++) {
956         ESCAPE_CHECK_SIZE(src, size, SIZE_MAX-10);
957         switch (*p) {
958         case '&' : size += strlen("&amp;");  break;
959         case '<' : size += strlen("&lt;");   break;
960         case '>' : size += strlen("&gt;");   break;
961         case '\"': size += strlen("&quot;"); break;
962         case '\'': size += strlen("&apos;"); break;
963         default: size++;
964         }
965     }
966     ESCAPE_REALLOC_BUF(dst_size, dst, src, size);
967
968 #define COPY_STR(str) {      \
969         const char *s = str; \
970         while (*s)           \
971             *q++ = *s++;     \
972     }
973
974     p = src;
975     q = *dst;
976     while (*p) {
977         switch (*p) {
978         case '&' : COPY_STR("&amp;");  break;
979         case '<' : COPY_STR("&lt;");   break;
980         case '>' : COPY_STR("&gt;");   break;
981         case '\"': COPY_STR("&quot;"); break;
982         case '\'': COPY_STR("&apos;"); break;
983         default: *q++ = *p;
984         }
985         p++;
986     }
987     *q = 0;
988
989     return *dst;
990 }
991
992 static void xml_print_header(WriterContext *wctx)
993 {
994     XMLContext *xml = wctx->priv;
995     const char *qual = " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' "
996         "xmlns:ffprobe='http://www.ffmpeg.org/schema/ffprobe' "
997         "xsi:schemaLocation='http://www.ffmpeg.org/schema/ffprobe ffprobe.xsd'";
998
999     printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1000     printf("<%sffprobe%s>\n",
1001            xml->fully_qualified ? "ffprobe:" : "",
1002            xml->fully_qualified ? qual : "");
1003
1004     xml->indent_level++;
1005 }
1006
1007 static void xml_print_footer(WriterContext *wctx)
1008 {
1009     XMLContext *xml = wctx->priv;
1010
1011     xml->indent_level--;
1012     printf("</%sffprobe>\n", xml->fully_qualified ? "ffprobe:" : "");
1013 }
1014
1015 #define XML_INDENT() { int i; for (i = 0; i < xml->indent_level; i++) printf(INDENT); }
1016
1017 static void xml_print_chapter_header(WriterContext *wctx, const char *chapter)
1018 {
1019     XMLContext *xml = wctx->priv;
1020
1021     if (wctx->nb_chapter)
1022         printf("\n");
1023     xml->multiple_entries = !strcmp(chapter, "packets") || !strcmp(chapter, "streams");
1024
1025     if (xml->multiple_entries) {
1026         XML_INDENT(); printf("<%s>\n", chapter);
1027         xml->indent_level++;
1028     }
1029 }
1030
1031 static void xml_print_chapter_footer(WriterContext *wctx, const char *chapter)
1032 {
1033     XMLContext *xml = wctx->priv;
1034
1035     if (xml->multiple_entries) {
1036         xml->indent_level--;
1037         XML_INDENT(); printf("</%s>\n", chapter);
1038     }
1039 }
1040
1041 static void xml_print_section_header(WriterContext *wctx, const char *section)
1042 {
1043     XMLContext *xml = wctx->priv;
1044
1045     XML_INDENT(); printf("<%s ", section);
1046     xml->within_tag = 1;
1047 }
1048
1049 static void xml_print_section_footer(WriterContext *wctx, const char *section)
1050 {
1051     XMLContext *xml = wctx->priv;
1052
1053     if (xml->within_tag)
1054         printf("/>\n");
1055     else {
1056         XML_INDENT(); printf("</%s>\n", section);
1057     }
1058 }
1059
1060 static void xml_print_str(WriterContext *wctx, const char *key, const char *value)
1061 {
1062     XMLContext *xml = wctx->priv;
1063
1064     if (wctx->nb_item)
1065         printf(" ");
1066     printf("%s=\"%s\"", key, xml_escape_str(&xml->buf, &xml->buf_size, value, wctx));
1067 }
1068
1069 static void xml_print_int(WriterContext *wctx, const char *key, long long int value)
1070 {
1071     if (wctx->nb_item)
1072         printf(" ");
1073     printf("%s=\"%lld\"", key, value);
1074 }
1075
1076 static void xml_show_tags(WriterContext *wctx, AVDictionary *dict)
1077 {
1078     XMLContext *xml = wctx->priv;
1079     AVDictionaryEntry *tag = NULL;
1080     int is_first = 1;
1081
1082     xml->indent_level++;
1083     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
1084         if (is_first) {
1085             /* close section tag */
1086             printf(">\n");
1087             xml->within_tag = 0;
1088             is_first = 0;
1089         }
1090         XML_INDENT();
1091         printf("<tag key=\"%s\"",
1092                xml_escape_str(&xml->buf, &xml->buf_size, tag->key,   wctx));
1093         printf(" value=\"%s\"/>\n",
1094                xml_escape_str(&xml->buf, &xml->buf_size, tag->value, wctx));
1095     }
1096     xml->indent_level--;
1097 }
1098
1099 static Writer xml_writer = {
1100     .name                 = "xml",
1101     .priv_size            = sizeof(XMLContext),
1102     .init                 = xml_init,
1103     .uninit               = xml_uninit,
1104     .print_header         = xml_print_header,
1105     .print_footer         = xml_print_footer,
1106     .print_chapter_header = xml_print_chapter_header,
1107     .print_chapter_footer = xml_print_chapter_footer,
1108     .print_section_header = xml_print_section_header,
1109     .print_section_footer = xml_print_section_footer,
1110     .print_integer        = xml_print_int,
1111     .print_string         = xml_print_str,
1112     .show_tags            = xml_show_tags,
1113 };
1114
1115 static void writer_register_all(void)
1116 {
1117     static int initialized;
1118
1119     if (initialized)
1120         return;
1121     initialized = 1;
1122
1123     writer_register(&default_writer);
1124     writer_register(&compact_writer);
1125     writer_register(&csv_writer);
1126     writer_register(&json_writer);
1127     writer_register(&xml_writer);
1128 }
1129
1130 #define print_fmt(k, f, ...) do {              \
1131     if (fast_asprintf(&pbuf, f, __VA_ARGS__))  \
1132         writer_print_string(w, k, pbuf.s, 0);  \
1133 } while (0)
1134
1135 #define print_fmt_opt(k, f, ...) do {          \
1136     if (fast_asprintf(&pbuf, f, __VA_ARGS__))  \
1137         writer_print_string(w, k, pbuf.s, 1);  \
1138 } while (0)
1139
1140 #define print_int(k, v)         writer_print_integer(w, k, v)
1141 #define print_str(k, v)         writer_print_string(w, k, v, 0)
1142 #define print_str_opt(k, v)     writer_print_string(w, k, v, 1)
1143 #define print_time(k, v, tb)    writer_print_time(w, k, v, tb)
1144 #define print_ts(k, v)          writer_print_ts(w, k, v)
1145 #define print_val(k, v, u)      writer_print_string(w, k, \
1146     value_string(val_str, sizeof(val_str), (struct unit_value){.val.i = v, .unit=u}), 0)
1147 #define print_section_header(s) writer_print_section_header(w, s)
1148 #define print_section_footer(s) writer_print_section_footer(w, s)
1149 #define show_tags(metadata)     writer_show_tags(w, metadata)
1150
1151 static void show_packet(WriterContext *w, AVFormatContext *fmt_ctx, AVPacket *pkt, int packet_idx)
1152 {
1153     char val_str[128];
1154     AVStream *st = fmt_ctx->streams[pkt->stream_index];
1155     struct print_buf pbuf = {.s = NULL};
1156     const char *s;
1157
1158     print_section_header("packet");
1159     s = av_get_media_type_string(st->codec->codec_type);
1160     if (s) print_str    ("codec_type", s);
1161     else   print_str_opt("codec_type", "unknown");
1162     print_int("stream_index",     pkt->stream_index);
1163     print_ts  ("pts",             pkt->pts);
1164     print_time("pts_time",        pkt->pts, &st->time_base);
1165     print_ts  ("dts",             pkt->dts);
1166     print_time("dts_time",        pkt->dts, &st->time_base);
1167     print_ts  ("duration",        pkt->duration);
1168     print_time("duration_time",   pkt->duration, &st->time_base);
1169     print_val("size",             pkt->size, unit_byte_str);
1170     if (pkt->pos != -1) print_fmt    ("pos", "%"PRId64, pkt->pos);
1171     else                print_str_opt("pos", "N/A");
1172     print_fmt("flags", "%c",      pkt->flags & AV_PKT_FLAG_KEY ? 'K' : '_');
1173     print_section_footer("packet");
1174
1175     av_free(pbuf.s);
1176     fflush(stdout);
1177 }
1178
1179 static void show_packets(WriterContext *w, AVFormatContext *fmt_ctx)
1180 {
1181     AVPacket pkt;
1182     int i = 0;
1183
1184     av_init_packet(&pkt);
1185
1186     while (!av_read_frame(fmt_ctx, &pkt))
1187         show_packet(w, fmt_ctx, &pkt, i++);
1188 }
1189
1190 static void show_stream(WriterContext *w, AVFormatContext *fmt_ctx, int stream_idx)
1191 {
1192     AVStream *stream = fmt_ctx->streams[stream_idx];
1193     AVCodecContext *dec_ctx;
1194     AVCodec *dec;
1195     char val_str[128];
1196     const char *s;
1197     AVRational display_aspect_ratio;
1198     struct print_buf pbuf = {.s = NULL};
1199
1200     print_section_header("stream");
1201
1202     print_int("index", stream->index);
1203
1204     if ((dec_ctx = stream->codec)) {
1205         if ((dec = dec_ctx->codec)) {
1206             print_str("codec_name",      dec->name);
1207             print_str("codec_long_name", dec->long_name);
1208         } else {
1209             print_str_opt("codec_name",      "unknown");
1210             print_str_opt("codec_long_name", "unknown");
1211         }
1212
1213         s = av_get_media_type_string(dec_ctx->codec_type);
1214         if (s) print_str    ("codec_type", s);
1215         else   print_str_opt("codec_type", "unknown");
1216         print_fmt("codec_time_base", "%d/%d", dec_ctx->time_base.num, dec_ctx->time_base.den);
1217
1218         /* print AVI/FourCC tag */
1219         av_get_codec_tag_string(val_str, sizeof(val_str), dec_ctx->codec_tag);
1220         print_str("codec_tag_string",    val_str);
1221         print_fmt("codec_tag", "0x%04x", dec_ctx->codec_tag);
1222
1223         switch (dec_ctx->codec_type) {
1224         case AVMEDIA_TYPE_VIDEO:
1225             print_int("width",        dec_ctx->width);
1226             print_int("height",       dec_ctx->height);
1227             print_int("has_b_frames", dec_ctx->has_b_frames);
1228             if (dec_ctx->sample_aspect_ratio.num) {
1229                 print_fmt("sample_aspect_ratio", "%d:%d",
1230                           dec_ctx->sample_aspect_ratio.num,
1231                           dec_ctx->sample_aspect_ratio.den);
1232                 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
1233                           dec_ctx->width  * dec_ctx->sample_aspect_ratio.num,
1234                           dec_ctx->height * dec_ctx->sample_aspect_ratio.den,
1235                           1024*1024);
1236                 print_fmt("display_aspect_ratio", "%d:%d",
1237                           display_aspect_ratio.num,
1238                           display_aspect_ratio.den);
1239             } else {
1240                 print_str_opt("sample_aspect_ratio", "N/A");
1241                 print_str_opt("display_aspect_ratio", "N/A");
1242             }
1243             s = av_get_pix_fmt_name(dec_ctx->pix_fmt);
1244             if (s) print_str    ("pix_fmt", s);
1245             else   print_str_opt("pix_fmt", "unknown");
1246             print_int("level",   dec_ctx->level);
1247             if (dec_ctx->timecode_frame_start >= 0) {
1248                 uint32_t tc = dec_ctx->timecode_frame_start;
1249                 print_fmt("timecode", "%02d:%02d:%02d%c%02d",
1250                           tc>>19 & 0x1f,              // hours
1251                           tc>>13 & 0x3f,              // minutes
1252                           tc>>6  & 0x3f,              // seconds
1253                           tc     & 1<<24 ? ';' : ':', // drop
1254                           tc     & 0x3f);             // frames
1255             } else {
1256                 print_str_opt("timecode", "N/A");
1257             }
1258             break;
1259
1260         case AVMEDIA_TYPE_AUDIO:
1261             s = av_get_sample_fmt_name(dec_ctx->sample_fmt);
1262             if (s) print_str    ("sample_fmt", s);
1263             else   print_str_opt("sample_fmt", "unknown");
1264             print_val("sample_rate",     dec_ctx->sample_rate, unit_hertz_str);
1265             print_int("channels",        dec_ctx->channels);
1266             print_int("bits_per_sample", av_get_bits_per_sample(dec_ctx->codec_id));
1267             break;
1268         }
1269     } else {
1270         print_str_opt("codec_type", "unknown");
1271     }
1272     if (dec_ctx->codec && dec_ctx->codec->priv_class && show_private_data) {
1273         const AVOption *opt = NULL;
1274         while (opt = av_opt_next(dec_ctx->priv_data,opt)) {
1275             uint8_t *str;
1276             if (opt->flags) continue;
1277             if (av_opt_get(dec_ctx->priv_data, opt->name, 0, &str) >= 0) {
1278                 print_str(opt->name, str);
1279                 av_free(str);
1280             }
1281         }
1282     }
1283
1284     if (fmt_ctx->iformat->flags & AVFMT_SHOW_IDS) print_fmt    ("id", "0x%x", stream->id);
1285     else                                          print_str_opt("id", "N/A");
1286     print_fmt("r_frame_rate",   "%d/%d", stream->r_frame_rate.num,   stream->r_frame_rate.den);
1287     print_fmt("avg_frame_rate", "%d/%d", stream->avg_frame_rate.num, stream->avg_frame_rate.den);
1288     print_fmt("time_base",      "%d/%d", stream->time_base.num,      stream->time_base.den);
1289     print_time("start_time",    stream->start_time, &stream->time_base);
1290     print_time("duration",      stream->duration,   &stream->time_base);
1291     if (stream->nb_frames) print_fmt    ("nb_frames", "%"PRId64, stream->nb_frames);
1292     else                   print_str_opt("nb_frames", "N/A");
1293     show_tags(stream->metadata);
1294
1295     print_section_footer("stream");
1296     av_free(pbuf.s);
1297     fflush(stdout);
1298 }
1299
1300 static void show_streams(WriterContext *w, AVFormatContext *fmt_ctx)
1301 {
1302     int i;
1303     for (i = 0; i < fmt_ctx->nb_streams; i++)
1304         show_stream(w, fmt_ctx, i);
1305 }
1306
1307 static void show_format(WriterContext *w, AVFormatContext *fmt_ctx)
1308 {
1309     char val_str[128];
1310     int64_t size = avio_size(fmt_ctx->pb);
1311
1312     print_section_header("format");
1313     print_str("filename",         fmt_ctx->filename);
1314     print_int("nb_streams",       fmt_ctx->nb_streams);
1315     print_str("format_name",      fmt_ctx->iformat->name);
1316     print_str("format_long_name", fmt_ctx->iformat->long_name);
1317     print_time("start_time",      fmt_ctx->start_time, &AV_TIME_BASE_Q);
1318     print_time("duration",        fmt_ctx->duration,   &AV_TIME_BASE_Q);
1319     if (size >= 0) print_val    ("size", size, unit_byte_str);
1320     else           print_str_opt("size", "N/A");
1321     if (fmt_ctx->bit_rate > 0) print_val    ("bit_rate", fmt_ctx->bit_rate, unit_bit_per_second_str);
1322     else                       print_str_opt("bit_rate", "N/A");
1323     show_tags(fmt_ctx->metadata);
1324     print_section_footer("format");
1325     fflush(stdout);
1326 }
1327
1328 static void show_error(WriterContext *w, int err)
1329 {
1330     char errbuf[128];
1331     const char *errbuf_ptr = errbuf;
1332
1333     if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
1334         errbuf_ptr = strerror(AVUNERROR(err));
1335
1336     writer_print_chapter_header(w, "error");
1337     print_section_header("error");
1338     print_int("code", err);
1339     print_str("string", errbuf_ptr);
1340     print_section_footer("error");
1341     writer_print_chapter_footer(w, "error");
1342 }
1343
1344 static int open_input_file(AVFormatContext **fmt_ctx_ptr, const char *filename)
1345 {
1346     int err, i;
1347     AVFormatContext *fmt_ctx = NULL;
1348     AVDictionaryEntry *t;
1349
1350     if ((err = avformat_open_input(&fmt_ctx, filename, iformat, &format_opts)) < 0) {
1351         print_error(filename, err);
1352         return err;
1353     }
1354     if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
1355         av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
1356         return AVERROR_OPTION_NOT_FOUND;
1357     }
1358
1359
1360     /* fill the streams in the format context */
1361     if ((err = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
1362         print_error(filename, err);
1363         return err;
1364     }
1365
1366     av_dump_format(fmt_ctx, 0, filename, 0);
1367
1368     /* bind a decoder to each input stream */
1369     for (i = 0; i < fmt_ctx->nb_streams; i++) {
1370         AVStream *stream = fmt_ctx->streams[i];
1371         AVCodec *codec;
1372
1373         if (!(codec = avcodec_find_decoder(stream->codec->codec_id))) {
1374             av_log(NULL, AV_LOG_ERROR, "Unsupported codec with id %d for input stream %d\n",
1375                    stream->codec->codec_id, stream->index);
1376         } else if (avcodec_open2(stream->codec, codec, NULL) < 0) {
1377             av_log(NULL, AV_LOG_ERROR, "Error while opening codec for input stream %d\n",
1378                    stream->index);
1379         }
1380     }
1381
1382     *fmt_ctx_ptr = fmt_ctx;
1383     return 0;
1384 }
1385
1386 #define PRINT_CHAPTER(name) do {                                        \
1387     if (do_show_ ## name) {                                             \
1388         writer_print_chapter_header(wctx, #name);                       \
1389         show_ ## name (wctx, fmt_ctx);                                  \
1390         writer_print_chapter_footer(wctx, #name);                       \
1391     }                                                                   \
1392 } while (0)
1393
1394 static int probe_file(const char *filename)
1395 {
1396     AVFormatContext *fmt_ctx;
1397     int ret;
1398     const Writer *w;
1399     char *buf;
1400     char *w_name = NULL, *w_args = NULL;
1401     WriterContext *wctx;
1402
1403     writer_register_all();
1404
1405     if (!print_format)
1406         print_format = av_strdup("default");
1407     w_name = av_strtok(print_format, "=", &buf);
1408     w_args = buf;
1409
1410     w = writer_get_by_name(w_name);
1411     if (!w) {
1412         av_log(NULL, AV_LOG_ERROR, "Unknown output format with name '%s'\n", w_name);
1413         ret = AVERROR(EINVAL);
1414         goto end;
1415     }
1416
1417     if ((ret = writer_open(&wctx, w, w_args, NULL)) < 0)
1418         goto end;
1419
1420     writer_print_header(wctx);
1421     ret = open_input_file(&fmt_ctx, filename);
1422     if (ret >= 0) {
1423         PRINT_CHAPTER(packets);
1424         PRINT_CHAPTER(streams);
1425         PRINT_CHAPTER(format);
1426         avformat_close_input(&fmt_ctx);
1427     } else if (do_show_error) {
1428         show_error(wctx, ret);
1429     }
1430     writer_print_footer(wctx);
1431     writer_close(&wctx);
1432
1433 end:
1434     av_freep(&print_format);
1435
1436     return ret;
1437 }
1438
1439 static void show_usage(void)
1440 {
1441     printf("Simple multimedia streams analyzer\n");
1442     printf("usage: %s [OPTIONS] [INPUT_FILE]\n", program_name);
1443     printf("\n");
1444 }
1445
1446 static int opt_format(const char *opt, const char *arg)
1447 {
1448     iformat = av_find_input_format(arg);
1449     if (!iformat) {
1450         av_log(NULL, AV_LOG_ERROR, "Unknown input format: %s\n", arg);
1451         return AVERROR(EINVAL);
1452     }
1453     return 0;
1454 }
1455
1456 static void opt_input_file(void *optctx, const char *arg)
1457 {
1458     if (input_filename) {
1459         av_log(NULL, AV_LOG_ERROR, "Argument '%s' provided as input filename, but '%s' was already specified.\n",
1460                arg, input_filename);
1461         exit(1);
1462     }
1463     if (!strcmp(arg, "-"))
1464         arg = "pipe:";
1465     input_filename = arg;
1466 }
1467
1468 static int opt_help(const char *opt, const char *arg)
1469 {
1470     av_log_set_callback(log_callback_help);
1471     show_usage();
1472     show_help_options(options, "Main options:\n", 0, 0);
1473     printf("\n");
1474
1475     show_help_children(avformat_get_class(), AV_OPT_FLAG_DECODING_PARAM);
1476
1477     return 0;
1478 }
1479
1480 static int opt_pretty(const char *opt, const char *arg)
1481 {
1482     show_value_unit              = 1;
1483     use_value_prefix             = 1;
1484     use_byte_value_binary_prefix = 1;
1485     use_value_sexagesimal_format = 1;
1486     return 0;
1487 }
1488
1489 static const OptionDef options[] = {
1490 #include "cmdutils_common_opts.h"
1491     { "f", HAS_ARG, {(void*)opt_format}, "force format", "format" },
1492     { "unit", OPT_BOOL, {(void*)&show_value_unit}, "show unit of the displayed values" },
1493     { "prefix", OPT_BOOL, {(void*)&use_value_prefix}, "use SI prefixes for the displayed values" },
1494     { "byte_binary_prefix", OPT_BOOL, {(void*)&use_byte_value_binary_prefix},
1495       "use binary prefixes for byte units" },
1496     { "sexagesimal", OPT_BOOL,  {(void*)&use_value_sexagesimal_format},
1497       "use sexagesimal format HOURS:MM:SS.MICROSECONDS for time units" },
1498     { "pretty", 0, {(void*)&opt_pretty},
1499       "prettify the format of displayed values, make it more human readable" },
1500     { "print_format", OPT_STRING | HAS_ARG, {(void*)&print_format},
1501       "set the output printing format (available formats are: default, compact, csv, json, xml)", "format" },
1502     { "show_error",   OPT_BOOL, {(void*)&do_show_error} ,  "show probing error" },
1503     { "show_format",  OPT_BOOL, {(void*)&do_show_format} , "show format/container info" },
1504     { "show_packets", OPT_BOOL, {(void*)&do_show_packets}, "show packets info" },
1505     { "show_streams", OPT_BOOL, {(void*)&do_show_streams}, "show streams info" },
1506     { "show_private_data", OPT_BOOL, {(void*)&show_private_data}, "show private data" },
1507     { "private",           OPT_BOOL, {(void*)&show_private_data}, "same as show_private_data" },
1508     { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
1509     { "i", HAS_ARG, {(void *)opt_input_file}, "read specified file", "input_file"},
1510     { NULL, },
1511 };
1512
1513 int main(int argc, char **argv)
1514 {
1515     int ret;
1516
1517     parse_loglevel(argc, argv, options);
1518     av_register_all();
1519     avformat_network_init();
1520     init_opts();
1521 #if CONFIG_AVDEVICE
1522     avdevice_register_all();
1523 #endif
1524
1525     show_banner(argc, argv, options);
1526     parse_options(NULL, argc, argv, options, opt_input_file);
1527
1528     if (!input_filename) {
1529         show_usage();
1530         av_log(NULL, AV_LOG_ERROR, "You have to specify one input file.\n");
1531         av_log(NULL, AV_LOG_ERROR, "Use -h to get full help or, even better, run 'man %s'.\n", program_name);
1532         exit(1);
1533     }
1534
1535     ret = probe_file(input_filename);
1536
1537     avformat_network_deinit();
1538
1539     return ret;
1540 }