]> git.sesse.net Git - ffmpeg/blob - ffprobe.c
ffprobe: replace fmt callback with str callback.
[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/opt.h"
27 #include "libavutil/pixdesc.h"
28 #include "libavutil/dict.h"
29 #include "libavdevice/avdevice.h"
30 #include "cmdutils.h"
31
32 const char program_name[] = "ffprobe";
33 const int program_birth_year = 2007;
34
35 static int do_show_format  = 0;
36 static int do_show_packets = 0;
37 static int do_show_streams = 0;
38
39 static int show_value_unit              = 0;
40 static int use_value_prefix             = 0;
41 static int use_byte_value_binary_prefix = 0;
42 static int use_value_sexagesimal_format = 0;
43
44 static char *print_format;
45
46 /* globals */
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 static const char *media_type_string(enum AVMediaType media_type)
126 {
127     const char *s = av_get_media_type_string(media_type);
128     return s ? s : "unknown";
129 }
130
131
132 struct writer {
133     const char *name;
134     const char *item_sep;           ///< separator between key/value couples
135     const char *items_sep;          ///< separator between sets of key/value couples
136     const char *section_sep;        ///< separator between sections (streams, packets, ...)
137     const char *header, *footer;
138     void (*print_header)(const char *);
139     void (*print_footer)(const char *);
140     void (*print_int_f)(const char *, int);
141     void (*print_str_f)(const char *, const char *);
142     void (*show_tags)(struct writer *w, AVDictionary *dict);
143 };
144
145
146 /* Default output */
147
148 static void default_print_header(const char *section)
149 {
150     printf("[%s]\n", section);
151 }
152
153 static void default_print_str(const char *key, const char *value)
154 {
155     printf("%s=%s", key, value);
156 }
157
158 static void default_print_int(const char *key, int value)
159 {
160     printf("%s=%d", key, value);
161 }
162
163 static void default_print_footer(const char *section)
164 {
165     printf("\n[/%s]", section);
166 }
167
168
169 /* Print helpers */
170
171 struct print_buf {
172     char *s;
173     int len;
174 };
175
176 static char *fast_asprintf(struct print_buf *pbuf, const char *fmt, ...)
177 {
178     va_list va;
179     int len;
180
181     va_start(va, fmt);
182     len = vsnprintf(NULL, 0, fmt, va);
183     va_end(va);
184     if (len < 0)
185         goto fail;
186
187     if (pbuf->len < len) {
188         char *p = av_realloc(pbuf->s, len + 1);
189         if (!p)
190             goto fail;
191         pbuf->s   = p;
192         pbuf->len = len;
193     }
194
195     va_start(va, fmt);
196     len = vsnprintf(pbuf->s, len + 1, fmt, va);
197     va_end(va);
198     if (len < 0)
199         goto fail;
200     return pbuf->s;
201
202 fail:
203     av_freep(&pbuf->s);
204     pbuf->len = 0;
205     return NULL;
206 }
207
208 #define print_fmt0(k, f, ...) do {             \
209     if (fast_asprintf(&pbuf, f, __VA_ARGS__))  \
210         w->print_str_f(k, pbuf.s);             \
211 } while (0)
212 #define print_fmt( k, f, ...) do {     \
213     if (w->item_sep)                   \
214         printf("%s", w->item_sep);     \
215     print_fmt0(k, f, __VA_ARGS__);     \
216 } while (0)
217
218 #define print_int0(k, v) w->print_int_f(k, v)
219 #define print_int( k, v) do {      \
220     if (w->item_sep)               \
221         printf("%s", w->item_sep); \
222     print_int0(k, v);              \
223 } while (0)
224
225 #define print_str0(k, v) print_fmt0(k, "%s", v)
226 #define print_str( k, v) print_fmt (k, "%s", v)
227
228
229 static void show_packet(struct writer *w, AVFormatContext *fmt_ctx, AVPacket *pkt, int packet_idx)
230 {
231     char val_str[128];
232     AVStream *st = fmt_ctx->streams[pkt->stream_index];
233     struct print_buf pbuf = {.s = NULL};
234
235     if (packet_idx)
236         printf("%s", w->items_sep);
237     w->print_header("PACKET");
238     print_str0("codec_type",      media_type_string(st->codec->codec_type));
239     print_int("stream_index",     pkt->stream_index);
240     print_str("pts",              ts_value_string  (val_str, sizeof(val_str), pkt->pts));
241     print_str("pts_time",         time_value_string(val_str, sizeof(val_str), pkt->pts, &st->time_base));
242     print_str("dts",              ts_value_string  (val_str, sizeof(val_str), pkt->dts));
243     print_str("dts_time",         time_value_string(val_str, sizeof(val_str), pkt->dts, &st->time_base));
244     print_str("duration",         ts_value_string  (val_str, sizeof(val_str), pkt->duration));
245     print_str("duration_time",    time_value_string(val_str, sizeof(val_str), pkt->duration, &st->time_base));
246     print_str("size",             value_string     (val_str, sizeof(val_str), pkt->size, unit_byte_str));
247     print_fmt("pos",   "%"PRId64, pkt->pos);
248     print_fmt("flags", "%c",      pkt->flags & AV_PKT_FLAG_KEY ? 'K' : '_');
249     w->print_footer("PACKET");
250     av_free(pbuf.s);
251     fflush(stdout);
252 }
253
254 static void show_packets(struct writer *w, AVFormatContext *fmt_ctx)
255 {
256     AVPacket pkt;
257     int i = 0;
258
259     av_init_packet(&pkt);
260
261     while (!av_read_frame(fmt_ctx, &pkt))
262         show_packet(w, fmt_ctx, &pkt, i++);
263 }
264
265 static void default_show_tags(struct writer *w, AVDictionary *dict)
266 {
267     AVDictionaryEntry *tag = NULL;
268     struct print_buf pbuf = {.s = NULL};
269     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
270         printf("\nTAG:");
271         print_str0(tag->key, tag->value);
272     }
273     av_free(pbuf.s);
274 }
275
276 static void show_stream(struct writer *w, AVFormatContext *fmt_ctx, int stream_idx)
277 {
278     AVStream *stream = fmt_ctx->streams[stream_idx];
279     AVCodecContext *dec_ctx;
280     AVCodec *dec;
281     char val_str[128];
282     AVRational display_aspect_ratio;
283     struct print_buf pbuf = {.s = NULL};
284
285     if (stream_idx)
286         printf("%s", w->items_sep);
287     w->print_header("STREAM");
288
289     print_int0("index", stream->index);
290
291     if ((dec_ctx = stream->codec)) {
292         if ((dec = dec_ctx->codec)) {
293             print_str("codec_name",      dec->name);
294             print_str("codec_long_name", dec->long_name);
295         } else {
296             print_str("codec_name",      "unknown");
297         }
298
299         print_str("codec_type",               media_type_string(dec_ctx->codec_type));
300         print_fmt("codec_time_base", "%d/%d", dec_ctx->time_base.num, dec_ctx->time_base.den);
301
302         /* print AVI/FourCC tag */
303         av_get_codec_tag_string(val_str, sizeof(val_str), dec_ctx->codec_tag);
304         print_str("codec_tag_string",    val_str);
305         print_fmt("codec_tag", "0x%04x", dec_ctx->codec_tag);
306
307         switch (dec_ctx->codec_type) {
308         case AVMEDIA_TYPE_VIDEO:
309             print_int("width",        dec_ctx->width);
310             print_int("height",       dec_ctx->height);
311             print_int("has_b_frames", dec_ctx->has_b_frames);
312             if (dec_ctx->sample_aspect_ratio.num) {
313                 print_fmt("sample_aspect_ratio", "%d:%d",
314                           dec_ctx->sample_aspect_ratio.num,
315                           dec_ctx->sample_aspect_ratio.den);
316                 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
317                           dec_ctx->width  * dec_ctx->sample_aspect_ratio.num,
318                           dec_ctx->height * dec_ctx->sample_aspect_ratio.den,
319                           1024*1024);
320                 print_fmt("display_aspect_ratio", "%d:%d",
321                           display_aspect_ratio.num,
322                           display_aspect_ratio.den);
323             }
324             print_str("pix_fmt", dec_ctx->pix_fmt != PIX_FMT_NONE ? av_pix_fmt_descriptors[dec_ctx->pix_fmt].name : "unknown");
325             print_int("level",   dec_ctx->level);
326             break;
327
328         case AVMEDIA_TYPE_AUDIO:
329             print_str("sample_rate",     value_string(val_str, sizeof(val_str), dec_ctx->sample_rate, unit_hertz_str));
330             print_int("channels",        dec_ctx->channels);
331             print_int("bits_per_sample", av_get_bits_per_sample(dec_ctx->codec_id));
332             break;
333         }
334     } else {
335         print_str("codec_type", "unknown");
336     }
337
338     if (fmt_ctx->iformat->flags & AVFMT_SHOW_IDS)
339         print_fmt("id=", "0x%x", stream->id);
340     print_fmt("r_frame_rate",   "%d/%d", stream->r_frame_rate.num,   stream->r_frame_rate.den);
341     print_fmt("avg_frame_rate", "%d/%d", stream->avg_frame_rate.num, stream->avg_frame_rate.den);
342     print_fmt("time_base",      "%d/%d", stream->time_base.num,      stream->time_base.den);
343     print_str("start_time", time_value_string(val_str, sizeof(val_str), stream->start_time, &stream->time_base));
344     print_str("duration",   time_value_string(val_str, sizeof(val_str), stream->duration,   &stream->time_base));
345     if (stream->nb_frames)
346         print_fmt("nb_frames", "%"PRId64, stream->nb_frames);
347
348     w->show_tags(w, stream->metadata);
349
350     w->print_footer("STREAM");
351     av_free(pbuf.s);
352     fflush(stdout);
353 }
354
355 static void show_streams(struct writer *w, AVFormatContext *fmt_ctx)
356 {
357     int i;
358     for (i = 0; i < fmt_ctx->nb_streams; i++)
359         show_stream(w, fmt_ctx, i);
360 }
361
362 static void show_format(struct writer *w, AVFormatContext *fmt_ctx)
363 {
364     char val_str[128];
365     struct print_buf pbuf = {.s = NULL};
366
367     w->print_header("FORMAT");
368     print_str0("filename",        fmt_ctx->filename);
369     print_int("nb_streams",       fmt_ctx->nb_streams);
370     print_str("format_name",      fmt_ctx->iformat->name);
371     print_str("format_long_name", fmt_ctx->iformat->long_name);
372     print_str("start_time",       time_value_string(val_str, sizeof(val_str), fmt_ctx->start_time, &AV_TIME_BASE_Q));
373     print_str("duration",         time_value_string(val_str, sizeof(val_str), fmt_ctx->duration,   &AV_TIME_BASE_Q));
374     print_str("size",             value_string(val_str, sizeof(val_str), fmt_ctx->file_size, unit_byte_str));
375     print_str("bit_rate",         value_string(val_str, sizeof(val_str), fmt_ctx->bit_rate,  unit_bit_per_second_str));
376     w->show_tags(w, fmt_ctx->metadata);
377     w->print_footer("FORMAT");
378     av_free(pbuf.s);
379     fflush(stdout);
380 }
381
382 static int open_input_file(AVFormatContext **fmt_ctx_ptr, const char *filename)
383 {
384     int err, i;
385     AVFormatContext *fmt_ctx = NULL;
386     AVDictionaryEntry *t;
387
388     if ((err = avformat_open_input(&fmt_ctx, filename, iformat, &format_opts)) < 0) {
389         print_error(filename, err);
390         return err;
391     }
392     if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
393         av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
394         return AVERROR_OPTION_NOT_FOUND;
395     }
396
397
398     /* fill the streams in the format context */
399     if ((err = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
400         print_error(filename, err);
401         return err;
402     }
403
404     av_dump_format(fmt_ctx, 0, filename, 0);
405
406     /* bind a decoder to each input stream */
407     for (i = 0; i < fmt_ctx->nb_streams; i++) {
408         AVStream *stream = fmt_ctx->streams[i];
409         AVCodec *codec;
410
411         if (!(codec = avcodec_find_decoder(stream->codec->codec_id))) {
412             fprintf(stderr, "Unsupported codec with id %d for input stream %d\n",
413                     stream->codec->codec_id, stream->index);
414         } else if (avcodec_open2(stream->codec, codec, NULL) < 0) {
415             fprintf(stderr, "Error while opening codec for input stream %d\n",
416                     stream->index);
417         }
418     }
419
420     *fmt_ctx_ptr = fmt_ctx;
421     return 0;
422 }
423
424 #define WRITER_FUNC(func)                  \
425     .print_header = func ## _print_header, \
426     .print_footer = func ## _print_footer, \
427     .print_int_f  = func ## _print_int,    \
428     .print_str_f  = func ## _print_str,    \
429     .show_tags    = func ## _show_tags
430
431 static struct writer writers[] = {{
432         .name         = "default",
433         .item_sep     = "\n",
434         .items_sep    = "\n",
435         .section_sep  = "\n",
436         .footer       = "\n",
437         WRITER_FUNC(default),
438     }
439 };
440
441 static int get_writer(const char *name)
442 {
443     int i;
444     if (!name)
445         return 0;
446     for (i = 0; i < FF_ARRAY_ELEMS(writers); i++)
447         if (!strcmp(writers[i].name, name))
448             return i;
449     return -1;
450 }
451
452 #define SECTION_PRINT(name, left) do {                        \
453     if (do_show_ ## name) {                                   \
454         show_ ## name (w, fmt_ctx);                           \
455         if (left)                                             \
456             printf("%s", w->section_sep);                     \
457     }                                                         \
458 } while (0)
459
460 static int probe_file(const char *filename)
461 {
462     AVFormatContext *fmt_ctx;
463     int ret, writer_id;
464     struct writer *w;
465
466     writer_id = get_writer(print_format);
467     if (writer_id < 0) {
468         fprintf(stderr, "Invalid output format '%s'\n", print_format);
469         return AVERROR(EINVAL);
470     }
471     w = &writers[writer_id];
472
473     if ((ret = open_input_file(&fmt_ctx, filename)))
474         return ret;
475
476     if (w->header)
477         printf("%s", w->header);
478
479     SECTION_PRINT(packets, do_show_streams || do_show_format);
480     SECTION_PRINT(streams, do_show_format);
481     SECTION_PRINT(format,  0);
482
483     if (w->footer)
484         printf("%s", w->footer);
485
486     av_close_input_file(fmt_ctx);
487     return 0;
488 }
489
490 static void show_usage(void)
491 {
492     printf("Simple multimedia streams analyzer\n");
493     printf("usage: %s [OPTIONS] [INPUT_FILE]\n", program_name);
494     printf("\n");
495 }
496
497 static int opt_format(const char *opt, const char *arg)
498 {
499     iformat = av_find_input_format(arg);
500     if (!iformat) {
501         fprintf(stderr, "Unknown input format: %s\n", arg);
502         return AVERROR(EINVAL);
503     }
504     return 0;
505 }
506
507 static void opt_input_file(void *optctx, const char *arg)
508 {
509     if (input_filename) {
510         fprintf(stderr, "Argument '%s' provided as input filename, but '%s' was already specified.\n",
511                 arg, input_filename);
512         exit(1);
513     }
514     if (!strcmp(arg, "-"))
515         arg = "pipe:";
516     input_filename = arg;
517 }
518
519 static int opt_help(const char *opt, const char *arg)
520 {
521     const AVClass *class = avformat_get_class();
522     av_log_set_callback(log_callback_help);
523     show_usage();
524     show_help_options(options, "Main options:\n", 0, 0);
525     printf("\n");
526     av_opt_show2(&class, NULL,
527                  AV_OPT_FLAG_DECODING_PARAM, 0);
528     return 0;
529 }
530
531 static int opt_pretty(const char *opt, const char *arg)
532 {
533     show_value_unit              = 1;
534     use_value_prefix             = 1;
535     use_byte_value_binary_prefix = 1;
536     use_value_sexagesimal_format = 1;
537     return 0;
538 }
539
540 static const OptionDef options[] = {
541 #include "cmdutils_common_opts.h"
542     { "f", HAS_ARG, {(void*)opt_format}, "force format", "format" },
543     { "unit", OPT_BOOL, {(void*)&show_value_unit}, "show unit of the displayed values" },
544     { "prefix", OPT_BOOL, {(void*)&use_value_prefix}, "use SI prefixes for the displayed values" },
545     { "byte_binary_prefix", OPT_BOOL, {(void*)&use_byte_value_binary_prefix},
546       "use binary prefixes for byte units" },
547     { "sexagesimal", OPT_BOOL,  {(void*)&use_value_sexagesimal_format},
548       "use sexagesimal format HOURS:MM:SS.MICROSECONDS for time units" },
549     { "pretty", 0, {(void*)&opt_pretty},
550       "prettify the format of displayed values, make it more human readable" },
551     { "show_format",  OPT_BOOL, {(void*)&do_show_format} , "show format/container info" },
552     { "show_packets", OPT_BOOL, {(void*)&do_show_packets}, "show packets info" },
553     { "show_streams", OPT_BOOL, {(void*)&do_show_streams}, "show streams info" },
554     { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
555     { "i", HAS_ARG, {(void *)opt_input_file}, "read specified file", "input_file"},
556     { NULL, },
557 };
558
559 int main(int argc, char **argv)
560 {
561     int ret;
562
563     av_register_all();
564     init_opts();
565 #if CONFIG_AVDEVICE
566     avdevice_register_all();
567 #endif
568
569     show_banner();
570     parse_options(NULL, argc, argv, options, opt_input_file);
571
572     if (!input_filename) {
573         show_usage();
574         fprintf(stderr, "You have to specify one input file.\n");
575         fprintf(stderr, "Use -h to get full help or, even better, run 'man %s'.\n", program_name);
576         exit(1);
577     }
578
579     ret = probe_file(input_filename);
580
581     return ret;
582 }