2 * ffprobe : Simple Media Prober based on the FFmpeg libraries
3 * Copyright (c) 2007-2010 Stefano Sabatini
5 * This file is part of FFmpeg.
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.
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.
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
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"
32 const char program_name[] = "ffprobe";
33 const int program_birth_year = 2007;
35 static int do_show_format = 0;
36 static int do_show_packets = 0;
37 static int do_show_streams = 0;
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;
44 static char *print_format;
46 static const OptionDef options[];
49 static const char *input_filename;
50 static AVInputFormat *iformat = NULL;
52 static const char *binary_unit_prefixes [] = { "", "Ki", "Mi", "Gi", "Ti", "Pi" };
53 static const char *decimal_unit_prefixes[] = { "", "K" , "M" , "G" , "T" , "P" };
55 static const char *unit_second_str = "s" ;
56 static const char *unit_hertz_str = "Hz" ;
57 static const char *unit_byte_str = "byte" ;
58 static const char *unit_bit_per_second_str = "bit/s";
60 void exit_program(int ret)
65 static char *value_string(char *buf, int buf_size, double val, const char *unit)
67 if (unit == unit_second_str && use_value_sexagesimal_format) {
71 mins = (int)secs / 60;
72 secs = secs - mins * 60;
75 snprintf(buf, buf_size, "%d:%02d:%09.6f", hours, mins, secs);
76 } else if (use_value_prefix) {
77 const char *prefix_string;
80 if (unit == unit_byte_str && use_byte_value_binary_prefix) {
81 index = (int) (log(val)/log(2)) / 10;
82 index = av_clip(index, 0, FF_ARRAY_ELEMS(binary_unit_prefixes) -1);
83 val /= pow(2, index*10);
84 prefix_string = binary_unit_prefixes[index];
86 index = (int) (log10(val)) / 3;
87 index = av_clip(index, 0, FF_ARRAY_ELEMS(decimal_unit_prefixes) -1);
88 val /= pow(10, index*3);
89 prefix_string = decimal_unit_prefixes[index];
92 snprintf(buf, buf_size, "%.3f%s%s%s", val, prefix_string || show_value_unit ? " " : "",
93 prefix_string, show_value_unit ? unit : "");
95 snprintf(buf, buf_size, "%f%s%s", val, show_value_unit ? " " : "",
96 show_value_unit ? unit : "");
102 static char *time_value_string(char *buf, int buf_size, int64_t val, const AVRational *time_base)
104 if (val == AV_NOPTS_VALUE) {
105 snprintf(buf, buf_size, "N/A");
107 value_string(buf, buf_size, val * av_q2d(*time_base), unit_second_str);
113 static char *ts_value_string (char *buf, int buf_size, int64_t ts)
115 if (ts == AV_NOPTS_VALUE) {
116 snprintf(buf, buf_size, "N/A");
118 snprintf(buf, buf_size, "%"PRId64, ts);
127 const char *item_sep; ///< separator between key/value couples
128 const char *items_sep; ///< separator between sets of key/value couples
129 const char *section_sep; ///< separator between sections (streams, packets, ...)
130 const char *header, *footer;
131 void (*print_section_start)(const char *, int);
132 void (*print_section_end) (const char *, int);
133 void (*print_header)(const char *);
134 void (*print_footer)(const char *);
135 void (*print_integer)(const char *, int);
136 void (*print_string)(const char *, const char *);
137 void (*show_tags)(struct writer *w, AVDictionary *dict);
143 static void json_print_header(const char *section)
148 static char *json_escape_str(const char *s)
150 static const char json_escape[] = {'"', '\\', '\b', '\f', '\n', '\r', '\t', 0};
151 static const char json_subst[] = {'"', '\\', 'b', 'f', 'n', 'r', 't', 0};
155 // compute the length of the escaped string
156 for (i = 0; s[i]; i++) {
157 if (strchr(json_escape, s[i])) len += 2; // simple escape
158 else if ((unsigned char)s[i] < 32) len += 6; // handle non-printable chars
159 else len += 1; // char copy
162 p = ret = av_malloc(len + 1);
165 for (i = 0; s[i]; i++) {
166 char *q = strchr(json_escape, s[i]);
169 *p++ = json_subst[q - json_escape];
170 } else if ((unsigned char)s[i] < 32) {
171 snprintf(p, 7, "\\u00%02x", s[i] & 0xff);
181 static void json_print_str(const char *key, const char *value)
183 char *key_esc = json_escape_str(key);
184 char *value_esc = json_escape_str(value);
185 printf(" \"%s\": \"%s\"",
186 key_esc ? key_esc : "",
187 value_esc ? value_esc : "");
192 static void json_print_int(const char *key, int value)
194 char *key_esc = json_escape_str(key);
195 printf(" \"%s\": %d", key_esc ? key_esc : "", value);
199 static void json_print_footer(const char *section)
204 static void json_print_section_start(const char *section, int multiple_entries)
206 char *section_esc = json_escape_str(section);
207 printf("\n \"%s\":%s", section_esc ? section_esc : "",
208 multiple_entries ? " [" : " ");
209 av_free(section_esc);
212 static void json_print_section_end(const char *section, int multiple_entries)
214 if (multiple_entries)
221 static void default_print_header(const char *section)
223 printf("[%s]\n", section);
226 static void default_print_str(const char *key, const char *value)
228 printf("%s=%s", key, value);
231 static void default_print_int(const char *key, int value)
233 printf("%s=%d", key, value);
236 static void default_print_footer(const char *section)
238 printf("\n[/%s]", section);
249 static char *fast_asprintf(struct print_buf *pbuf, const char *fmt, ...)
255 len = vsnprintf(NULL, 0, fmt, va);
260 if (pbuf->len < len) {
261 char *p = av_realloc(pbuf->s, len + 1);
269 len = vsnprintf(pbuf->s, len + 1, fmt, va);
281 #define print_fmt0(k, f, ...) do { \
282 if (fast_asprintf(&pbuf, f, __VA_ARGS__)) \
283 w->print_string(k, pbuf.s); \
285 #define print_fmt( k, f, ...) do { \
287 printf("%s", w->item_sep); \
288 print_fmt0(k, f, __VA_ARGS__); \
291 #define print_int0(k, v) w->print_integer(k, v)
292 #define print_int( k, v) do { \
294 printf("%s", w->item_sep); \
298 #define print_str0(k, v) print_fmt0(k, "%s", v)
299 #define print_str( k, v) print_fmt (k, "%s", v)
302 static void show_packet(struct writer *w, AVFormatContext *fmt_ctx, AVPacket *pkt, int packet_idx)
305 AVStream *st = fmt_ctx->streams[pkt->stream_index];
306 struct print_buf pbuf = {.s = NULL};
309 printf("%s", w->items_sep);
310 w->print_header("PACKET");
311 print_str0("codec_type", av_x_if_null(av_get_media_type_string(st->codec->codec_type), "unknown"));
312 print_int("stream_index", pkt->stream_index);
313 print_str("pts", ts_value_string (val_str, sizeof(val_str), pkt->pts));
314 print_str("pts_time", time_value_string(val_str, sizeof(val_str), pkt->pts, &st->time_base));
315 print_str("dts", ts_value_string (val_str, sizeof(val_str), pkt->dts));
316 print_str("dts_time", time_value_string(val_str, sizeof(val_str), pkt->dts, &st->time_base));
317 print_str("duration", ts_value_string (val_str, sizeof(val_str), pkt->duration));
318 print_str("duration_time", time_value_string(val_str, sizeof(val_str), pkt->duration, &st->time_base));
319 print_str("size", value_string (val_str, sizeof(val_str), pkt->size, unit_byte_str));
320 print_fmt("pos", "%"PRId64, pkt->pos);
321 print_fmt("flags", "%c", pkt->flags & AV_PKT_FLAG_KEY ? 'K' : '_');
322 w->print_footer("PACKET");
327 static void show_packets(struct writer *w, AVFormatContext *fmt_ctx)
332 av_init_packet(&pkt);
334 while (!av_read_frame(fmt_ctx, &pkt))
335 show_packet(w, fmt_ctx, &pkt, i++);
338 static void json_show_tags(struct writer *w, AVDictionary *dict)
340 AVDictionaryEntry *tag = NULL;
341 struct print_buf pbuf = {.s = NULL};
346 printf(",\n \"tags\": {\n");
347 while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
349 print_str0(tag->key, tag->value);
352 print_str(tag->key, tag->value);
359 static void default_show_tags(struct writer *w, AVDictionary *dict)
361 AVDictionaryEntry *tag = NULL;
362 struct print_buf pbuf = {.s = NULL};
363 while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
365 print_str0(tag->key, tag->value);
370 static void show_stream(struct writer *w, AVFormatContext *fmt_ctx, int stream_idx)
372 AVStream *stream = fmt_ctx->streams[stream_idx];
373 AVCodecContext *dec_ctx;
376 AVRational display_aspect_ratio;
377 struct print_buf pbuf = {.s = NULL};
380 printf("%s", w->items_sep);
381 w->print_header("STREAM");
383 print_int0("index", stream->index);
385 if ((dec_ctx = stream->codec)) {
386 if ((dec = dec_ctx->codec)) {
387 print_str("codec_name", dec->name);
388 print_str("codec_long_name", dec->long_name);
390 print_str("codec_name", "unknown");
393 print_str("codec_type", av_x_if_null(av_get_media_type_string(dec_ctx->codec_type), "unknown"));
394 print_fmt("codec_time_base", "%d/%d", dec_ctx->time_base.num, dec_ctx->time_base.den);
396 /* print AVI/FourCC tag */
397 av_get_codec_tag_string(val_str, sizeof(val_str), dec_ctx->codec_tag);
398 print_str("codec_tag_string", val_str);
399 print_fmt("codec_tag", "0x%04x", dec_ctx->codec_tag);
401 switch (dec_ctx->codec_type) {
402 case AVMEDIA_TYPE_VIDEO:
403 print_int("width", dec_ctx->width);
404 print_int("height", dec_ctx->height);
405 print_int("has_b_frames", dec_ctx->has_b_frames);
406 if (dec_ctx->sample_aspect_ratio.num) {
407 print_fmt("sample_aspect_ratio", "%d:%d",
408 dec_ctx->sample_aspect_ratio.num,
409 dec_ctx->sample_aspect_ratio.den);
410 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
411 dec_ctx->width * dec_ctx->sample_aspect_ratio.num,
412 dec_ctx->height * dec_ctx->sample_aspect_ratio.den,
414 print_fmt("display_aspect_ratio", "%d:%d",
415 display_aspect_ratio.num,
416 display_aspect_ratio.den);
418 print_str("pix_fmt", av_x_if_null(av_get_pix_fmt_name(dec_ctx->pix_fmt), "unknown"));
419 print_int("level", dec_ctx->level);
422 case AVMEDIA_TYPE_AUDIO:
423 print_str("sample_rate", value_string(val_str, sizeof(val_str), dec_ctx->sample_rate, unit_hertz_str));
424 print_int("channels", dec_ctx->channels);
425 print_int("bits_per_sample", av_get_bits_per_sample(dec_ctx->codec_id));
429 print_str("codec_type", "unknown");
432 if (fmt_ctx->iformat->flags & AVFMT_SHOW_IDS)
433 print_fmt("id", "0x%x", stream->id);
434 print_fmt("r_frame_rate", "%d/%d", stream->r_frame_rate.num, stream->r_frame_rate.den);
435 print_fmt("avg_frame_rate", "%d/%d", stream->avg_frame_rate.num, stream->avg_frame_rate.den);
436 print_fmt("time_base", "%d/%d", stream->time_base.num, stream->time_base.den);
437 print_str("start_time", time_value_string(val_str, sizeof(val_str), stream->start_time, &stream->time_base));
438 print_str("duration", time_value_string(val_str, sizeof(val_str), stream->duration, &stream->time_base));
439 if (stream->nb_frames)
440 print_fmt("nb_frames", "%"PRId64, stream->nb_frames);
442 w->show_tags(w, stream->metadata);
444 w->print_footer("STREAM");
449 static void show_streams(struct writer *w, AVFormatContext *fmt_ctx)
452 for (i = 0; i < fmt_ctx->nb_streams; i++)
453 show_stream(w, fmt_ctx, i);
456 static void show_format(struct writer *w, AVFormatContext *fmt_ctx)
459 struct print_buf pbuf = {.s = NULL};
461 w->print_header("FORMAT");
462 print_str0("filename", fmt_ctx->filename);
463 print_int("nb_streams", fmt_ctx->nb_streams);
464 print_str("format_name", fmt_ctx->iformat->name);
465 print_str("format_long_name", fmt_ctx->iformat->long_name);
466 print_str("start_time", time_value_string(val_str, sizeof(val_str), fmt_ctx->start_time, &AV_TIME_BASE_Q));
467 print_str("duration", time_value_string(val_str, sizeof(val_str), fmt_ctx->duration, &AV_TIME_BASE_Q));
468 print_str("size", value_string(val_str, sizeof(val_str), fmt_ctx->file_size, unit_byte_str));
469 print_str("bit_rate", value_string(val_str, sizeof(val_str), fmt_ctx->bit_rate, unit_bit_per_second_str));
470 w->show_tags(w, fmt_ctx->metadata);
471 w->print_footer("FORMAT");
476 static int open_input_file(AVFormatContext **fmt_ctx_ptr, const char *filename)
479 AVFormatContext *fmt_ctx = NULL;
480 AVDictionaryEntry *t;
482 if ((err = avformat_open_input(&fmt_ctx, filename, iformat, &format_opts)) < 0) {
483 print_error(filename, err);
486 if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
487 av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
488 return AVERROR_OPTION_NOT_FOUND;
492 /* fill the streams in the format context */
493 if ((err = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
494 print_error(filename, err);
498 av_dump_format(fmt_ctx, 0, filename, 0);
500 /* bind a decoder to each input stream */
501 for (i = 0; i < fmt_ctx->nb_streams; i++) {
502 AVStream *stream = fmt_ctx->streams[i];
505 if (!(codec = avcodec_find_decoder(stream->codec->codec_id))) {
506 fprintf(stderr, "Unsupported codec with id %d for input stream %d\n",
507 stream->codec->codec_id, stream->index);
508 } else if (avcodec_open2(stream->codec, codec, NULL) < 0) {
509 fprintf(stderr, "Error while opening codec for input stream %d\n",
514 *fmt_ctx_ptr = fmt_ctx;
518 #define WRITER_FUNC(func) \
519 .print_header = func ## _print_header, \
520 .print_footer = func ## _print_footer, \
521 .print_integer = func ## _print_int, \
522 .print_string = func ## _print_str, \
523 .show_tags = func ## _show_tags
525 static struct writer writers[] = {{
531 WRITER_FUNC(default),
539 .print_section_start = json_print_section_start,
540 .print_section_end = json_print_section_end,
545 static int get_writer(const char *name)
550 for (i = 0; i < FF_ARRAY_ELEMS(writers); i++)
551 if (!strcmp(writers[i].name, name))
556 #define SECTION_PRINT(name, multiple_entries, left) do { \
557 if (do_show_ ## name) { \
558 if (w->print_section_start) \
559 w->print_section_start(#name, multiple_entries); \
560 show_ ## name (w, fmt_ctx); \
561 if (w->print_section_end) \
562 w->print_section_end(#name, multiple_entries); \
564 printf("%s", w->section_sep); \
568 static int probe_file(const char *filename)
570 AVFormatContext *fmt_ctx;
574 writer_id = get_writer(print_format);
576 fprintf(stderr, "Invalid output format '%s'\n", print_format);
577 return AVERROR(EINVAL);
579 w = &writers[writer_id];
581 if ((ret = open_input_file(&fmt_ctx, filename)))
585 printf("%s", w->header);
587 SECTION_PRINT(packets, 1, do_show_streams || do_show_format);
588 SECTION_PRINT(streams, 1, do_show_format);
589 SECTION_PRINT(format, 0, 0);
592 printf("%s", w->footer);
594 av_close_input_file(fmt_ctx);
598 static void show_usage(void)
600 printf("Simple multimedia streams analyzer\n");
601 printf("usage: %s [OPTIONS] [INPUT_FILE]\n", program_name);
605 static int opt_format(const char *opt, const char *arg)
607 iformat = av_find_input_format(arg);
609 fprintf(stderr, "Unknown input format: %s\n", arg);
610 return AVERROR(EINVAL);
615 static void opt_input_file(void *optctx, const char *arg)
617 if (input_filename) {
618 fprintf(stderr, "Argument '%s' provided as input filename, but '%s' was already specified.\n",
619 arg, input_filename);
622 if (!strcmp(arg, "-"))
624 input_filename = arg;
627 static int opt_help(const char *opt, const char *arg)
629 const AVClass *class = avformat_get_class();
630 av_log_set_callback(log_callback_help);
632 show_help_options(options, "Main options:\n", 0, 0);
634 av_opt_show2(&class, NULL,
635 AV_OPT_FLAG_DECODING_PARAM, 0);
639 static int opt_pretty(const char *opt, const char *arg)
642 use_value_prefix = 1;
643 use_byte_value_binary_prefix = 1;
644 use_value_sexagesimal_format = 1;
648 static const OptionDef options[] = {
649 #include "cmdutils_common_opts.h"
650 { "f", HAS_ARG, {(void*)opt_format}, "force format", "format" },
651 { "unit", OPT_BOOL, {(void*)&show_value_unit}, "show unit of the displayed values" },
652 { "prefix", OPT_BOOL, {(void*)&use_value_prefix}, "use SI prefixes for the displayed values" },
653 { "byte_binary_prefix", OPT_BOOL, {(void*)&use_byte_value_binary_prefix},
654 "use binary prefixes for byte units" },
655 { "sexagesimal", OPT_BOOL, {(void*)&use_value_sexagesimal_format},
656 "use sexagesimal format HOURS:MM:SS.MICROSECONDS for time units" },
657 { "pretty", 0, {(void*)&opt_pretty},
658 "prettify the format of displayed values, make it more human readable" },
659 { "print_format", OPT_STRING | HAS_ARG, {(void*)&print_format}, "set the output printing format (available formats are: default, json)", "format" },
660 { "show_format", OPT_BOOL, {(void*)&do_show_format} , "show format/container info" },
661 { "show_packets", OPT_BOOL, {(void*)&do_show_packets}, "show packets info" },
662 { "show_streams", OPT_BOOL, {(void*)&do_show_streams}, "show streams info" },
663 { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
664 { "i", HAS_ARG, {(void *)opt_input_file}, "read specified file", "input_file"},
668 int main(int argc, char **argv)
672 parse_loglevel(argc, argv, options);
676 avdevice_register_all();
680 parse_options(NULL, argc, argv, options, opt_input_file);
682 if (!input_filename) {
684 fprintf(stderr, "You have to specify one input file.\n");
685 fprintf(stderr, "Use -h to get full help or, even better, run 'man %s'.\n", program_name);
689 ret = probe_file(input_filename);