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