]> git.sesse.net Git - ffmpeg/blob - ffprobe.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / ffprobe.c
1 /*
2  * ffprobe : Simple Media Prober based on the FFmpeg libraries
3  * Copyright (c) 2007-2010 Stefano Sabatini
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "config.h"
23
24 #include "libavformat/avformat.h"
25 #include "libavcodec/avcodec.h"
26 #include "libavutil/avstring.h"
27 #include "libavutil/opt.h"
28 #include "libavutil/pixdesc.h"
29 #include "libavutil/dict.h"
30 #include "libavdevice/avdevice.h"
31 #include "cmdutils.h"
32
33 const char program_name[] = "ffprobe";
34 const int program_birth_year = 2007;
35
36 static int do_show_format  = 0;
37 static int do_show_packets = 0;
38 static int do_show_streams = 0;
39
40 static int show_value_unit              = 0;
41 static int use_value_prefix             = 0;
42 static int use_byte_value_binary_prefix = 0;
43 static int use_value_sexagesimal_format = 0;
44
45 static char *print_format;
46
47 static const OptionDef options[];
48
49 /* FFprobe context */
50 static const char *input_filename;
51 static AVInputFormat *iformat = NULL;
52
53 static const char *binary_unit_prefixes [] = { "", "Ki", "Mi", "Gi", "Ti", "Pi" };
54 static const char *decimal_unit_prefixes[] = { "", "K" , "M" , "G" , "T" , "P"  };
55
56 static const char *unit_second_str          = "s"    ;
57 static const char *unit_hertz_str           = "Hz"   ;
58 static const char *unit_byte_str            = "byte" ;
59 static const char *unit_bit_per_second_str  = "bit/s";
60
61 void exit_program(int ret)
62 {
63     exit(ret);
64 }
65
66 struct unit_value {
67     union { double d; int i; } val;
68     const char *unit;
69 };
70
71 static char *value_string(char *buf, int buf_size, struct unit_value uv)
72 {
73     double vald;
74     int show_float = 0;
75
76     if (uv.unit == unit_second_str) {
77         vald = uv.val.d;
78         show_float = 1;
79     } else {
80         vald = uv.val.i;
81     }
82
83     if (uv.unit == unit_second_str && use_value_sexagesimal_format) {
84         double secs;
85         int hours, mins;
86         secs  = vald;
87         mins  = (int)secs / 60;
88         secs  = secs - mins * 60;
89         hours = mins / 60;
90         mins %= 60;
91         snprintf(buf, buf_size, "%d:%02d:%09.6f", hours, mins, secs);
92     } else if (use_value_prefix) {
93         const char *prefix_string;
94         int index, l;
95
96         if (uv.unit == unit_byte_str && use_byte_value_binary_prefix) {
97             index = (int) (log(vald)/log(2)) / 10;
98             index = av_clip(index, 0, FF_ARRAY_ELEMS(binary_unit_prefixes) -1);
99             vald /= pow(2, index*10);
100             prefix_string = binary_unit_prefixes[index];
101         } else {
102             index = (int) (log10(vald)) / 3;
103             index = av_clip(index, 0, FF_ARRAY_ELEMS(decimal_unit_prefixes) -1);
104             vald /= pow(10, index*3);
105             prefix_string = decimal_unit_prefixes[index];
106         }
107
108         if (show_float || vald != (int)vald) l = snprintf(buf, buf_size, "%.3f", vald);
109         else                                 l = snprintf(buf, buf_size, "%d",   (int)vald);
110         snprintf(buf+l, buf_size-l, "%s%s%s", prefix_string || show_value_unit ? " " : "",
111                  prefix_string, show_value_unit ? uv.unit : "");
112     } else {
113         int l;
114
115         if (show_float) l = snprintf(buf, buf_size, "%.3f", vald);
116         else            l = snprintf(buf, buf_size, "%d",   (int)vald);
117         snprintf(buf+l, buf_size-l, "%s%s", show_value_unit ? " " : "",
118                  show_value_unit ? uv.unit : "");
119     }
120
121     return buf;
122 }
123
124 static char *time_value_string(char *buf, int buf_size, int64_t val, const AVRational *time_base)
125 {
126     if (val == AV_NOPTS_VALUE) {
127         snprintf(buf, buf_size, "N/A");
128     } else {
129         double d = val * av_q2d(*time_base);
130         value_string(buf, buf_size, (struct unit_value){.val.d=d, .unit=unit_second_str});
131     }
132
133     return buf;
134 }
135
136 static char *ts_value_string (char *buf, int buf_size, int64_t ts)
137 {
138     if (ts == AV_NOPTS_VALUE) {
139         snprintf(buf, buf_size, "N/A");
140     } else {
141         snprintf(buf, buf_size, "%"PRId64, ts);
142     }
143
144     return buf;
145 }
146
147 /* WRITERS API */
148
149 typedef struct WriterContext WriterContext;
150
151 typedef struct Writer {
152     int priv_size;                  ///< private size for the writer context
153     const char *name;
154
155     int  (*init)  (WriterContext *wctx, const char *args, void *opaque);
156     void (*uninit)(WriterContext *wctx);
157
158     void (*print_header)(WriterContext *ctx);
159     void (*print_footer)(WriterContext *ctx);
160
161     void (*print_chapter_header)(WriterContext *wctx, const char *);
162     void (*print_chapter_footer)(WriterContext *wctx, const char *);
163     void (*print_section_header)(WriterContext *wctx, const char *);
164     void (*print_section_footer)(WriterContext *wctx, const char *);
165     void (*print_integer)       (WriterContext *wctx, const char *, int);
166     void (*print_string)        (WriterContext *wctx, const char *, const char *);
167     void (*show_tags)           (WriterContext *wctx, AVDictionary *dict);
168 } Writer;
169
170 struct WriterContext {
171     const AVClass *class;           ///< class of the writer
172     const Writer *writer;           ///< the Writer of which this is an instance
173     char *name;                     ///< name of this writer instance
174     void *priv;                     ///< private data for use by the filter
175     unsigned int nb_item;           ///< number of the item printed in the given section, starting at 0
176     unsigned int nb_section;        ///< number of the section printed in the given section sequence, starting at 0
177     unsigned int nb_chapter;        ///< number of the chapter, starting at 0
178 };
179
180 static const char *writer_get_name(void *p)
181 {
182     WriterContext *wctx = p;
183     return wctx->writer->name;
184 }
185
186 static const AVClass writer_class = {
187     "Writer",
188     writer_get_name,
189     NULL,
190     LIBAVUTIL_VERSION_INT,
191 };
192
193 static void writer_close(WriterContext **wctx)
194 {
195     if (*wctx && (*wctx)->writer->uninit)
196         (*wctx)->writer->uninit(*wctx);
197
198     av_freep(&((*wctx)->priv));
199     av_freep(wctx);
200 }
201
202 static int writer_open(WriterContext **wctx, const Writer *writer,
203                        const char *args, void *opaque)
204 {
205     int ret = 0;
206
207     if (!(*wctx = av_malloc(sizeof(WriterContext)))) {
208         ret = AVERROR(ENOMEM);
209         goto fail;
210     }
211
212     if (!((*wctx)->priv = av_mallocz(writer->priv_size))) {
213         ret = AVERROR(ENOMEM);
214         goto fail;
215     }
216
217     (*wctx)->class = &writer_class;
218     (*wctx)->writer = writer;
219     if ((*wctx)->writer->init)
220         ret = (*wctx)->writer->init(*wctx, args, opaque);
221     if (ret < 0)
222         goto fail;
223
224     return 0;
225
226 fail:
227     writer_close(wctx);
228     return ret;
229 }
230
231 static inline void writer_print_header(WriterContext *wctx)
232 {
233     if (wctx->writer->print_header)
234         wctx->writer->print_header(wctx);
235     wctx->nb_chapter = 0;
236 }
237
238 static inline void writer_print_footer(WriterContext *wctx)
239 {
240     if (wctx->writer->print_footer)
241         wctx->writer->print_footer(wctx);
242 }
243
244 static inline void writer_print_chapter_header(WriterContext *wctx,
245                                                const char *header)
246 {
247     if (wctx->writer->print_chapter_header)
248         wctx->writer->print_chapter_header(wctx, header);
249     wctx->nb_section = 0;
250 }
251
252 static inline void writer_print_chapter_footer(WriterContext *wctx,
253                                                const char *footer)
254 {
255     if (wctx->writer->print_chapter_footer)
256         wctx->writer->print_chapter_footer(wctx, footer);
257     wctx->nb_chapter++;
258 }
259
260 static inline void writer_print_section_header(WriterContext *wctx,
261                                                const char *header)
262 {
263     if (wctx->writer->print_section_header)
264         wctx->writer->print_section_header(wctx, header);
265     wctx->nb_item = 0;
266 }
267
268 static inline void writer_print_section_footer(WriterContext *wctx,
269                                                const char *footer)
270 {
271     if (wctx->writer->print_section_footer)
272         wctx->writer->print_section_footer(wctx, footer);
273     wctx->nb_section++;
274 }
275
276 static inline void writer_print_integer(WriterContext *wctx,
277                                         const char *key, int val)
278 {
279     wctx->writer->print_integer(wctx, key, val);
280     wctx->nb_item++;
281 }
282
283 static inline void writer_print_string(WriterContext *wctx,
284                                        const char *key, const char *val)
285 {
286     wctx->writer->print_string(wctx, key, val);
287     wctx->nb_item++;
288 }
289
290 static inline void writer_show_tags(WriterContext *wctx, AVDictionary *dict)
291 {
292     wctx->writer->show_tags(wctx, dict);
293 }
294
295 #define MAX_REGISTERED_WRITERS_NB 64
296
297 static Writer *registered_writers[MAX_REGISTERED_WRITERS_NB + 1];
298
299 static int writer_register(Writer *writer)
300 {
301     static int next_registered_writer_idx = 0;
302
303     if (next_registered_writer_idx == MAX_REGISTERED_WRITERS_NB)
304         return AVERROR(ENOMEM);
305
306     registered_writers[next_registered_writer_idx++] = writer;
307     return 0;
308 }
309
310 static Writer *writer_get_by_name(const char *name)
311 {
312     int i;
313
314     for (i = 0; registered_writers[i]; i++)
315         if (!strcmp(registered_writers[i]->name, name))
316             return registered_writers[i];
317
318     return NULL;
319 }
320
321 /* Print helpers */
322
323 struct print_buf {
324     char *s;
325     int len;
326 };
327
328 static char *fast_asprintf(struct print_buf *pbuf, const char *fmt, ...)
329 {
330     va_list va;
331     int len;
332
333     va_start(va, fmt);
334     len = vsnprintf(NULL, 0, fmt, va);
335     va_end(va);
336     if (len < 0)
337         goto fail;
338
339     if (pbuf->len < len) {
340         char *p = av_realloc(pbuf->s, len + 1);
341         if (!p)
342             goto fail;
343         pbuf->s   = p;
344         pbuf->len = len;
345     }
346
347     va_start(va, fmt);
348     len = vsnprintf(pbuf->s, len + 1, fmt, va);
349     va_end(va);
350     if (len < 0)
351         goto fail;
352     return pbuf->s;
353
354 fail:
355     av_freep(&pbuf->s);
356     pbuf->len = 0;
357     return NULL;
358 }
359
360 #define ESCAPE_INIT_BUF_SIZE 256
361
362 #define ESCAPE_CHECK_SIZE(src, size, max_size)                          \
363     if (size > max_size) {                                              \
364         char buf[64];                                                   \
365         snprintf(buf, sizeof(buf), "%s", src);                          \
366         av_log(log_ctx, AV_LOG_WARNING,                                 \
367                "String '%s...' with is too big\n", buf);                \
368         return "FFPROBE_TOO_BIG_STRING";                                \
369     }
370
371 #define ESCAPE_REALLOC_BUF(dst_size_p, dst_p, src, size)                \
372     if (*dst_size_p < size) {                                           \
373         char *q = av_realloc(*dst_p, size);                             \
374         if (!q) {                                                       \
375             char buf[64];                                               \
376             snprintf(buf, sizeof(buf), "%s", src);                      \
377             av_log(log_ctx, AV_LOG_WARNING,                             \
378                    "String '%s...' could not be escaped\n", buf);       \
379             return "FFPROBE_THIS_STRING_COULD_NOT_BE_ESCAPED";          \
380         }                                                               \
381         *dst_size_p = size;                                             \
382         *dst = q;                                                       \
383     }
384
385 /* WRITERS */
386
387 /* Default output */
388
389 static void default_print_footer(WriterContext *wctx)
390 {
391     printf("\n");
392 }
393
394 static void default_print_chapter_header(WriterContext *wctx, const char *chapter)
395 {
396     if (wctx->nb_chapter)
397         printf("\n");
398 }
399
400 /* lame uppercasing routine, assumes the string is lower case ASCII */
401 static inline char *upcase_string(char *dst, size_t dst_size, const char *src)
402 {
403     int i;
404     for (i = 0; src[i] && i < dst_size-1; i++)
405         dst[i] = src[i]-32;
406     dst[i] = 0;
407     return dst;
408 }
409
410 static void default_print_section_header(WriterContext *wctx, const char *section)
411 {
412     char buf[32];
413
414     if (wctx->nb_section)
415         printf("\n");
416     printf("[%s]\n", upcase_string(buf, sizeof(buf), section));
417 }
418
419 static void default_print_section_footer(WriterContext *wctx, const char *section)
420 {
421     char buf[32];
422
423     printf("[/%s]", upcase_string(buf, sizeof(buf), section));
424 }
425
426 static void default_print_str(WriterContext *wctx, const char *key, const char *value)
427 {
428     printf("%s=%s\n", key, value);
429 }
430
431 static void default_print_int(WriterContext *wctx, const char *key, int value)
432 {
433     printf("%s=%d\n", key, value);
434 }
435
436 static void default_show_tags(WriterContext *wctx, AVDictionary *dict)
437 {
438     AVDictionaryEntry *tag = NULL;
439     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
440         printf("TAG:");
441         writer_print_string(wctx, tag->key, tag->value);
442     }
443 }
444
445 static Writer default_writer = {
446     .name                  = "default",
447     .print_footer          = default_print_footer,
448     .print_chapter_header  = default_print_chapter_header,
449     .print_section_header  = default_print_section_header,
450     .print_section_footer  = default_print_section_footer,
451     .print_integer         = default_print_int,
452     .print_string          = default_print_str,
453     .show_tags             = default_show_tags
454 };
455
456 /* JSON output */
457
458 typedef struct {
459     int multiple_entries; ///< tells if the given chapter requires multiple entries
460     char *buf;
461     size_t buf_size;
462 } JSONContext;
463
464 static av_cold int json_init(WriterContext *wctx, const char *args, void *opaque)
465 {
466     JSONContext *json = wctx->priv;
467
468     json->buf_size = ESCAPE_INIT_BUF_SIZE;
469     if (!(json->buf = av_malloc(json->buf_size)))
470         return AVERROR(ENOMEM);
471
472     return 0;
473 }
474
475 static av_cold void json_uninit(WriterContext *wctx)
476 {
477     JSONContext *json = wctx->priv;
478     av_freep(&json->buf);
479 }
480
481 static const char *json_escape_str(char **dst, size_t *dst_size, const char *src,
482                                    void *log_ctx)
483 {
484     static const char json_escape[] = {'"', '\\', '\b', '\f', '\n', '\r', '\t', 0};
485     static const char json_subst[]  = {'"', '\\',  'b',  'f',  'n',  'r',  't', 0};
486     const char *p;
487     char *q;
488     size_t size = 1;
489
490     // compute the length of the escaped string
491     for (p = src; *p; p++) {
492         ESCAPE_CHECK_SIZE(src, size, SIZE_MAX-6);
493         if (strchr(json_escape, *p))     size += 2; // simple escape
494         else if ((unsigned char)*p < 32) size += 6; // handle non-printable chars
495         else                             size += 1; // char copy
496     }
497     ESCAPE_REALLOC_BUF(dst_size, dst, src, size);
498
499     q = *dst;
500     for (p = src; *p; p++) {
501         char *s = strchr(json_escape, *p);
502         if (s) {
503             *q++ = '\\';
504             *q++ = json_subst[s - json_escape];
505         } else if ((unsigned char)*p < 32) {
506             snprintf(q, 7, "\\u00%02x", *p & 0xff);
507             q += 6;
508         } else {
509             *q++ = *p;
510         }
511     }
512     *q = 0;
513     return *dst;
514 }
515
516 static void json_print_header(WriterContext *wctx)
517 {
518     printf("{");
519 }
520
521 static void json_print_footer(WriterContext *wctx)
522 {
523     printf("\n}\n");
524 }
525
526 static void json_print_chapter_header(WriterContext *wctx, const char *chapter)
527 {
528     JSONContext *json = wctx->priv;
529
530     if (wctx->nb_chapter)
531         printf(",");
532     json->multiple_entries = !strcmp(chapter, "packets") || !strcmp(chapter, "streams");
533     printf("\n  \"%s\":%s", json_escape_str(&json->buf, &json->buf_size, chapter, wctx),
534            json->multiple_entries ? " [" : " ");
535 }
536
537 static void json_print_chapter_footer(WriterContext *wctx, const char *chapter)
538 {
539     JSONContext *json = wctx->priv;
540
541     if (json->multiple_entries)
542         printf("]");
543 }
544
545 static void json_print_section_header(WriterContext *wctx, const char *section)
546 {
547     if (wctx->nb_section) printf(",");
548     printf("{\n");
549 }
550
551 static void json_print_section_footer(WriterContext *wctx, const char *section)
552 {
553     printf("\n  }");
554 }
555
556 static inline void json_print_item_str(WriterContext *wctx,
557                                        const char *key, const char *value,
558                                        const char *indent)
559 {
560     JSONContext *json = wctx->priv;
561
562     printf("%s\"%s\":", indent, json_escape_str(&json->buf, &json->buf_size, key,   wctx));
563     printf(" \"%s\"",           json_escape_str(&json->buf, &json->buf_size, value, wctx));
564 }
565
566 #define INDENT "    "
567
568 static void json_print_str(WriterContext *wctx, const char *key, const char *value)
569 {
570     if (wctx->nb_item) printf(",\n");
571     json_print_item_str(wctx, key, value, INDENT);
572 }
573
574 static void json_print_int(WriterContext *wctx, const char *key, int value)
575 {
576     JSONContext *json = wctx->priv;
577
578     if (wctx->nb_item) printf(",\n");
579     printf(INDENT "\"%s\": %d",
580            json_escape_str(&json->buf, &json->buf_size, key, wctx), value);
581 }
582
583 static void json_show_tags(WriterContext *wctx, AVDictionary *dict)
584 {
585     AVDictionaryEntry *tag = NULL;
586     int is_first = 1;
587     if (!dict)
588         return;
589     printf(",\n" INDENT "\"tags\": {\n");
590     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
591         if (is_first) is_first = 0;
592         else          printf(",\n");
593         json_print_item_str(wctx, tag->key, tag->value, INDENT INDENT);
594     }
595     printf("\n    }");
596 }
597
598 static Writer json_writer = {
599     .name         = "json",
600     .priv_size    = sizeof(JSONContext),
601
602     .init                 = json_init,
603     .uninit               = json_uninit,
604     .print_header         = json_print_header,
605     .print_footer         = json_print_footer,
606     .print_chapter_header = json_print_chapter_header,
607     .print_chapter_footer = json_print_chapter_footer,
608     .print_section_header = json_print_section_header,
609     .print_section_footer = json_print_section_footer,
610     .print_integer        = json_print_int,
611     .print_string         = json_print_str,
612     .show_tags            = json_show_tags,
613 };
614
615 static void writer_register_all(void)
616 {
617     static int initialized;
618
619     if (initialized)
620         return;
621     initialized = 1;
622
623     writer_register(&default_writer);
624     writer_register(&json_writer);
625 }
626
627 #define print_fmt(k, f, ...) do {              \
628     if (fast_asprintf(&pbuf, f, __VA_ARGS__))  \
629         writer_print_string(w, k, pbuf.s);     \
630 } while (0)
631
632 #define print_int(k, v)         writer_print_integer(w, k, v)
633 #define print_str(k, v)         writer_print_string(w, k, v)
634 #define print_ts(k, v)          writer_print_string(w, k, ts_value_string  (val_str, sizeof(val_str), v))
635 #define print_time(k, v, tb)    writer_print_string(w, k, time_value_string(val_str, sizeof(val_str), v, tb))
636 #define print_val(k, v, u)      writer_print_string(w, k, value_string     (val_str, sizeof(val_str), \
637                                                     (struct unit_value){.val.i = v, .unit=u}))
638 #define print_section_header(s) writer_print_section_header(w, s)
639 #define print_section_footer(s) writer_print_section_footer(w, s)
640 #define show_tags(metadata)     writer_show_tags(w, metadata)
641
642 static void show_packet(WriterContext *w, AVFormatContext *fmt_ctx, AVPacket *pkt, int packet_idx)
643 {
644     char val_str[128];
645     AVStream *st = fmt_ctx->streams[pkt->stream_index];
646     struct print_buf pbuf = {.s = NULL};
647
648     print_section_header("packet");
649     print_str("codec_type",       av_x_if_null(av_get_media_type_string(st->codec->codec_type), "unknown"));
650     print_int("stream_index",     pkt->stream_index);
651     print_ts  ("pts",             pkt->pts);
652     print_time("pts_time",        pkt->pts, &st->time_base);
653     print_ts  ("dts",             pkt->dts);
654     print_time("dts_time",        pkt->dts, &st->time_base);
655     print_ts  ("duration",        pkt->duration);
656     print_time("duration_time",   pkt->duration, &st->time_base);
657     print_val("size",             pkt->size, unit_byte_str);
658     print_fmt("pos",   "%"PRId64, pkt->pos);
659     print_fmt("flags", "%c",      pkt->flags & AV_PKT_FLAG_KEY ? 'K' : '_');
660     print_section_footer("packet");
661
662     av_free(pbuf.s);
663     fflush(stdout);
664 }
665
666 static void show_packets(WriterContext *w, AVFormatContext *fmt_ctx)
667 {
668     AVPacket pkt;
669     int i = 0;
670
671     av_init_packet(&pkt);
672
673     while (!av_read_frame(fmt_ctx, &pkt))
674         show_packet(w, fmt_ctx, &pkt, i++);
675 }
676
677 static void show_stream(WriterContext *w, AVFormatContext *fmt_ctx, int stream_idx)
678 {
679     AVStream *stream = fmt_ctx->streams[stream_idx];
680     AVCodecContext *dec_ctx;
681     AVCodec *dec;
682     char val_str[128];
683     AVRational display_aspect_ratio;
684     struct print_buf pbuf = {.s = NULL};
685
686     print_section_header("stream");
687
688     print_int("index", stream->index);
689
690     if ((dec_ctx = stream->codec)) {
691         if ((dec = dec_ctx->codec)) {
692             print_str("codec_name",      dec->name);
693             print_str("codec_long_name", dec->long_name);
694         } else {
695             print_str("codec_name",      "unknown");
696         }
697
698         print_str("codec_type", av_x_if_null(av_get_media_type_string(dec_ctx->codec_type), "unknown"));
699         print_fmt("codec_time_base", "%d/%d", dec_ctx->time_base.num, dec_ctx->time_base.den);
700
701         /* print AVI/FourCC tag */
702         av_get_codec_tag_string(val_str, sizeof(val_str), dec_ctx->codec_tag);
703         print_str("codec_tag_string",    val_str);
704         print_fmt("codec_tag", "0x%04x", dec_ctx->codec_tag);
705
706         switch (dec_ctx->codec_type) {
707         case AVMEDIA_TYPE_VIDEO:
708             print_int("width",        dec_ctx->width);
709             print_int("height",       dec_ctx->height);
710             print_int("has_b_frames", dec_ctx->has_b_frames);
711             if (dec_ctx->sample_aspect_ratio.num) {
712                 print_fmt("sample_aspect_ratio", "%d:%d",
713                           dec_ctx->sample_aspect_ratio.num,
714                           dec_ctx->sample_aspect_ratio.den);
715                 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
716                           dec_ctx->width  * dec_ctx->sample_aspect_ratio.num,
717                           dec_ctx->height * dec_ctx->sample_aspect_ratio.den,
718                           1024*1024);
719                 print_fmt("display_aspect_ratio", "%d:%d",
720                           display_aspect_ratio.num,
721                           display_aspect_ratio.den);
722             }
723             print_str("pix_fmt", av_x_if_null(av_get_pix_fmt_name(dec_ctx->pix_fmt), "unknown"));
724             print_int("level",   dec_ctx->level);
725             break;
726
727         case AVMEDIA_TYPE_AUDIO:
728             print_str("sample_fmt",
729                       av_x_if_null(av_get_sample_fmt_name(dec_ctx->sample_fmt), "unknown"));
730             print_val("sample_rate",     dec_ctx->sample_rate, unit_hertz_str);
731             print_int("channels",        dec_ctx->channels);
732             print_int("bits_per_sample", av_get_bits_per_sample(dec_ctx->codec_id));
733             break;
734         }
735     } else {
736         print_str("codec_type", "unknown");
737     }
738     if (dec_ctx->codec && dec_ctx->codec->priv_class) {
739         const AVOption *opt = NULL;
740         while (opt = av_opt_next(dec_ctx->priv_data,opt)) {
741             uint8_t *str;
742             if (opt->flags) continue;
743             if (av_opt_get(dec_ctx->priv_data, opt->name, 0, &str) >= 0) {
744                 print_str(opt->name, str);
745                 av_free(str);
746             }
747         }
748     }
749
750     if (fmt_ctx->iformat->flags & AVFMT_SHOW_IDS)
751         print_fmt("id", "0x%x", stream->id);
752     print_fmt("r_frame_rate",   "%d/%d", stream->r_frame_rate.num,   stream->r_frame_rate.den);
753     print_fmt("avg_frame_rate", "%d/%d", stream->avg_frame_rate.num, stream->avg_frame_rate.den);
754     print_fmt("time_base",      "%d/%d", stream->time_base.num,      stream->time_base.den);
755     print_time("start_time",    stream->start_time, &stream->time_base);
756     print_time("duration",      stream->duration,   &stream->time_base);
757     if (stream->nb_frames)
758         print_fmt("nb_frames", "%"PRId64, stream->nb_frames);
759
760     show_tags(stream->metadata);
761
762     print_section_footer("stream");
763     av_free(pbuf.s);
764     fflush(stdout);
765 }
766
767 static void show_streams(WriterContext *w, AVFormatContext *fmt_ctx)
768 {
769     int i;
770     for (i = 0; i < fmt_ctx->nb_streams; i++)
771         show_stream(w, fmt_ctx, i);
772 }
773
774 static void show_format(WriterContext *w, AVFormatContext *fmt_ctx)
775 {
776     char val_str[128];
777     int64_t size = avio_size(fmt_ctx->pb);
778     struct print_buf pbuf = {.s = NULL};
779
780     print_section_header("format");
781     print_str("filename",         fmt_ctx->filename);
782     print_int("nb_streams",       fmt_ctx->nb_streams);
783     print_str("format_name",      fmt_ctx->iformat->name);
784     print_str("format_long_name", fmt_ctx->iformat->long_name);
785     print_time("start_time",      fmt_ctx->start_time, &AV_TIME_BASE_Q);
786     print_time("duration",        fmt_ctx->duration,   &AV_TIME_BASE_Q);
787     if (size >= 0)
788         print_val("size",         size, unit_byte_str);
789     print_val("bit_rate",         fmt_ctx->bit_rate, unit_bit_per_second_str);
790     show_tags(fmt_ctx->metadata);
791     print_section_footer("format");
792     av_free(pbuf.s);
793     fflush(stdout);
794 }
795
796 static int open_input_file(AVFormatContext **fmt_ctx_ptr, const char *filename)
797 {
798     int err, i;
799     AVFormatContext *fmt_ctx = NULL;
800     AVDictionaryEntry *t;
801
802     if ((err = avformat_open_input(&fmt_ctx, filename, iformat, &format_opts)) < 0) {
803         print_error(filename, err);
804         return err;
805     }
806     if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
807         av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
808         return AVERROR_OPTION_NOT_FOUND;
809     }
810
811
812     /* fill the streams in the format context */
813     if ((err = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
814         print_error(filename, err);
815         return err;
816     }
817
818     av_dump_format(fmt_ctx, 0, filename, 0);
819
820     /* bind a decoder to each input stream */
821     for (i = 0; i < fmt_ctx->nb_streams; i++) {
822         AVStream *stream = fmt_ctx->streams[i];
823         AVCodec *codec;
824
825         if (!(codec = avcodec_find_decoder(stream->codec->codec_id))) {
826             fprintf(stderr, "Unsupported codec with id %d for input stream %d\n",
827                     stream->codec->codec_id, stream->index);
828         } else if (avcodec_open2(stream->codec, codec, NULL) < 0) {
829             fprintf(stderr, "Error while opening codec for input stream %d\n",
830                     stream->index);
831         }
832     }
833
834     *fmt_ctx_ptr = fmt_ctx;
835     return 0;
836 }
837
838 #define PRINT_CHAPTER(name) do {                                        \
839     if (do_show_ ## name) {                                             \
840         writer_print_chapter_header(wctx, #name);                       \
841         show_ ## name (wctx, fmt_ctx);                                  \
842         writer_print_chapter_footer(wctx, #name);                       \
843     }                                                                   \
844 } while (0)
845
846 static int probe_file(const char *filename)
847 {
848     AVFormatContext *fmt_ctx;
849     int ret;
850     Writer *w;
851     char *buf;
852     char *w_name = NULL, *w_args = NULL;
853     WriterContext *wctx;
854
855     writer_register_all();
856
857     if (!print_format)
858         print_format = av_strdup("default");
859     w_name = av_strtok(print_format, "=", &buf);
860     w_args = buf;
861
862     w = writer_get_by_name(w_name);
863     if (!w) {
864         av_log(NULL, AV_LOG_ERROR, "Unknown output format with name '%s'\n", w_name);
865         ret = AVERROR(EINVAL);
866         goto end;
867     }
868
869     if ((ret = writer_open(&wctx, w, w_args, NULL)) < 0)
870         goto end;
871     if ((ret = open_input_file(&fmt_ctx, filename)))
872         goto end;
873
874     writer_print_header(wctx);
875     PRINT_CHAPTER(packets);
876     PRINT_CHAPTER(streams);
877     PRINT_CHAPTER(format);
878     writer_print_footer(wctx);
879
880     av_close_input_file(fmt_ctx);
881     writer_close(&wctx);
882
883 end:
884     av_freep(&print_format);
885
886     return ret;
887 }
888
889 static void show_usage(void)
890 {
891     printf("Simple multimedia streams analyzer\n");
892     printf("usage: %s [OPTIONS] [INPUT_FILE]\n", program_name);
893     printf("\n");
894 }
895
896 static int opt_format(const char *opt, const char *arg)
897 {
898     iformat = av_find_input_format(arg);
899     if (!iformat) {
900         fprintf(stderr, "Unknown input format: %s\n", arg);
901         return AVERROR(EINVAL);
902     }
903     return 0;
904 }
905
906 static void opt_input_file(void *optctx, const char *arg)
907 {
908     if (input_filename) {
909         fprintf(stderr, "Argument '%s' provided as input filename, but '%s' was already specified.\n",
910                 arg, input_filename);
911         exit(1);
912     }
913     if (!strcmp(arg, "-"))
914         arg = "pipe:";
915     input_filename = arg;
916 }
917
918 static int opt_help(const char *opt, const char *arg)
919 {
920     av_log_set_callback(log_callback_help);
921     show_usage();
922     show_help_options(options, "Main options:\n", 0, 0);
923     printf("\n");
924
925     show_help_children(avformat_get_class(), AV_OPT_FLAG_DECODING_PARAM);
926
927     return 0;
928 }
929
930 static int opt_pretty(const char *opt, const char *arg)
931 {
932     show_value_unit              = 1;
933     use_value_prefix             = 1;
934     use_byte_value_binary_prefix = 1;
935     use_value_sexagesimal_format = 1;
936     return 0;
937 }
938
939 static const OptionDef options[] = {
940 #include "cmdutils_common_opts.h"
941     { "f", HAS_ARG, {(void*)opt_format}, "force format", "format" },
942     { "unit", OPT_BOOL, {(void*)&show_value_unit}, "show unit of the displayed values" },
943     { "prefix", OPT_BOOL, {(void*)&use_value_prefix}, "use SI prefixes for the displayed values" },
944     { "byte_binary_prefix", OPT_BOOL, {(void*)&use_byte_value_binary_prefix},
945       "use binary prefixes for byte units" },
946     { "sexagesimal", OPT_BOOL,  {(void*)&use_value_sexagesimal_format},
947       "use sexagesimal format HOURS:MM:SS.MICROSECONDS for time units" },
948     { "pretty", 0, {(void*)&opt_pretty},
949       "prettify the format of displayed values, make it more human readable" },
950     { "print_format", OPT_STRING | HAS_ARG, {(void*)&print_format}, "set the output printing format (available formats are: default, json)", "format" },
951     { "show_format",  OPT_BOOL, {(void*)&do_show_format} , "show format/container info" },
952     { "show_packets", OPT_BOOL, {(void*)&do_show_packets}, "show packets info" },
953     { "show_streams", OPT_BOOL, {(void*)&do_show_streams}, "show streams info" },
954     { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
955     { "i", HAS_ARG, {(void *)opt_input_file}, "read specified file", "input_file"},
956     { NULL, },
957 };
958
959 int main(int argc, char **argv)
960 {
961     int ret;
962
963     parse_loglevel(argc, argv, options);
964     av_register_all();
965     avformat_network_init();
966     init_opts();
967 #if CONFIG_AVDEVICE
968     avdevice_register_all();
969 #endif
970
971     show_banner();
972     parse_options(NULL, argc, argv, options, opt_input_file);
973
974     if (!input_filename) {
975         show_usage();
976         fprintf(stderr, "You have to specify one input file.\n");
977         fprintf(stderr, "Use -h to get full help or, even better, run 'man %s'.\n", program_name);
978         exit(1);
979     }
980
981     ret = probe_file(input_filename);
982
983     avformat_network_deinit();
984
985     return ret;
986 }