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