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;
47 static const OptionDef options[];
50 static const char *input_filename;
51 static AVInputFormat *iformat = NULL;
53 static const char *binary_unit_prefixes [] = { "", "Ki", "Mi", "Gi", "Ti", "Pi" };
54 static const char *decimal_unit_prefixes[] = { "", "K" , "M" , "G" , "T" , "P" };
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";
61 void exit_program(int ret)
66 static char *value_string(char *buf, int buf_size, double val, const char *unit)
68 if (unit == unit_second_str && use_value_sexagesimal_format) {
72 mins = (int)secs / 60;
73 secs = secs - 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;
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];
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];
93 snprintf(buf, buf_size, "%.3f%s%s%s", val, prefix_string || show_value_unit ? " " : "",
94 prefix_string, show_value_unit ? unit : "");
96 snprintf(buf, buf_size, "%f%s%s", val, show_value_unit ? " " : "",
97 show_value_unit ? unit : "");
103 static char *time_value_string(char *buf, int buf_size, int64_t val, const AVRational *time_base)
105 if (val == AV_NOPTS_VALUE) {
106 snprintf(buf, buf_size, "N/A");
108 value_string(buf, buf_size, val * av_q2d(*time_base), unit_second_str);
114 static char *ts_value_string (char *buf, int buf_size, int64_t ts)
116 if (ts == AV_NOPTS_VALUE) {
117 snprintf(buf, buf_size, "N/A");
119 snprintf(buf, buf_size, "%"PRId64, ts);
128 const char *item_sep; ///< separator between key/value couples
129 const char *items_sep; ///< separator between sets of key/value couples
130 const char *section_sep; ///< separator between sections (streams, packets, ...)
131 const char *header, *footer;
132 void (*print_section_start)(const char *, int);
133 void (*print_section_end) (const char *, int);
134 void (*print_header)(const char *);
135 void (*print_footer)(const char *);
136 void (*print_integer)(const char *, int);
137 void (*print_string)(const char *, const char *);
138 void (*show_tags)(struct writer *w, AVDictionary *dict);
144 static void json_print_header(const char *section)
149 static char *json_escape_str(const char *s)
151 static const char json_escape[] = {'"', '\\', '\b', '\f', '\n', '\r', '\t', 0};
152 static const char json_subst[] = {'"', '\\', 'b', 'f', 'n', 'r', 't', 0};
156 // compute the length of the escaped string
157 for (i = 0; s[i]; i++) {
158 if (strchr(json_escape, s[i])) len += 2; // simple escape
159 else if ((unsigned char)s[i] < 32) len += 6; // handle non-printable chars
160 else len += 1; // char copy
163 p = ret = av_malloc(len + 1);
166 for (i = 0; s[i]; i++) {
167 char *q = strchr(json_escape, s[i]);
170 *p++ = json_subst[q - json_escape];
171 } else if ((unsigned char)s[i] < 32) {
172 snprintf(p, 7, "\\u00%02x", s[i] & 0xff);
182 static void json_print_str(const char *key, const char *value)
184 char *key_esc = json_escape_str(key);
185 char *value_esc = json_escape_str(value);
186 printf(" \"%s\": \"%s\"",
187 key_esc ? key_esc : "",
188 value_esc ? value_esc : "");
193 static void json_print_int(const char *key, int value)
195 char *key_esc = json_escape_str(key);
196 printf(" \"%s\": %d", key_esc ? key_esc : "", value);
200 static void json_print_footer(const char *section)
205 static void json_print_section_start(const char *section, int multiple_entries)
207 char *section_esc = json_escape_str(section);
208 printf("\n \"%s\":%s", section_esc ? section_esc : "",
209 multiple_entries ? " [" : " ");
210 av_free(section_esc);
213 static void json_print_section_end(const char *section, int multiple_entries)
215 if (multiple_entries)
222 static void default_print_header(const char *section)
224 printf("[%s]\n", section);
227 static void default_print_str(const char *key, const char *value)
229 printf("%s=%s", key, value);
232 static void default_print_int(const char *key, int value)
234 printf("%s=%d", key, value);
237 static void default_print_footer(const char *section)
239 printf("\n[/%s]", section);
250 static char *fast_asprintf(struct print_buf *pbuf, const char *fmt, ...)
256 len = vsnprintf(NULL, 0, fmt, va);
261 if (pbuf->len < len) {
262 char *p = av_realloc(pbuf->s, len + 1);
270 len = vsnprintf(pbuf->s, len + 1, fmt, va);
282 #define print_fmt0(k, f, ...) do { \
283 if (fast_asprintf(&pbuf, f, __VA_ARGS__)) \
284 w->print_string(k, pbuf.s); \
286 #define print_fmt( k, f, ...) do { \
288 printf("%s", w->item_sep); \
289 print_fmt0(k, f, __VA_ARGS__); \
292 #define print_int0(k, v) w->print_integer(k, v)
293 #define print_int( k, v) do { \
295 printf("%s", w->item_sep); \
299 #define print_str0(k, v) print_fmt0(k, "%s", v)
300 #define print_str( k, v) print_fmt (k, "%s", v)
303 static void show_packet(struct writer *w, AVFormatContext *fmt_ctx, AVPacket *pkt, int packet_idx)
306 AVStream *st = fmt_ctx->streams[pkt->stream_index];
307 struct print_buf pbuf = {.s = NULL};
310 printf("%s", w->items_sep);
311 w->print_header("PACKET");
312 print_str0("codec_type", av_x_if_null(av_get_media_type_string(st->codec->codec_type), "unknown"));
313 print_int("stream_index", pkt->stream_index);
314 print_str("pts", ts_value_string (val_str, sizeof(val_str), pkt->pts));
315 print_str("pts_time", time_value_string(val_str, sizeof(val_str), pkt->pts, &st->time_base));
316 print_str("dts", ts_value_string (val_str, sizeof(val_str), pkt->dts));
317 print_str("dts_time", time_value_string(val_str, sizeof(val_str), pkt->dts, &st->time_base));
318 print_str("duration", ts_value_string (val_str, sizeof(val_str), pkt->duration));
319 print_str("duration_time", time_value_string(val_str, sizeof(val_str), pkt->duration, &st->time_base));
320 print_str("size", value_string (val_str, sizeof(val_str), pkt->size, unit_byte_str));
321 print_fmt("pos", "%"PRId64, pkt->pos);
322 print_fmt("flags", "%c", pkt->flags & AV_PKT_FLAG_KEY ? 'K' : '_');
323 w->print_footer("PACKET");
328 static void show_packets(struct writer *w, AVFormatContext *fmt_ctx)
333 av_init_packet(&pkt);
335 while (!av_read_frame(fmt_ctx, &pkt))
336 show_packet(w, fmt_ctx, &pkt, i++);
339 static void json_show_tags(struct writer *w, AVDictionary *dict)
341 AVDictionaryEntry *tag = NULL;
342 struct print_buf pbuf = {.s = NULL};
347 printf(",\n \"tags\": {\n");
348 while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
350 print_str0(tag->key, tag->value);
353 print_str(tag->key, tag->value);
360 static void default_show_tags(struct writer *w, AVDictionary *dict)
362 AVDictionaryEntry *tag = NULL;
363 struct print_buf pbuf = {.s = NULL};
364 while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
366 print_str0(tag->key, tag->value);
371 static void show_stream(struct writer *w, AVFormatContext *fmt_ctx, int stream_idx)
373 AVStream *stream = fmt_ctx->streams[stream_idx];
374 AVCodecContext *dec_ctx;
377 AVRational display_aspect_ratio;
378 struct print_buf pbuf = {.s = NULL};
381 printf("%s", w->items_sep);
382 w->print_header("STREAM");
384 print_int0("index", stream->index);
386 if ((dec_ctx = stream->codec)) {
387 if ((dec = dec_ctx->codec)) {
388 print_str("codec_name", dec->name);
389 print_str("codec_long_name", dec->long_name);
391 print_str("codec_name", "unknown");
394 print_str("codec_type", av_x_if_null(av_get_media_type_string(dec_ctx->codec_type), "unknown"));
395 print_fmt("codec_time_base", "%d/%d", dec_ctx->time_base.num, dec_ctx->time_base.den);
397 /* print AVI/FourCC tag */
398 av_get_codec_tag_string(val_str, sizeof(val_str), dec_ctx->codec_tag);
399 print_str("codec_tag_string", val_str);
400 print_fmt("codec_tag", "0x%04x", dec_ctx->codec_tag);
402 switch (dec_ctx->codec_type) {
403 case AVMEDIA_TYPE_VIDEO:
404 print_int("width", dec_ctx->width);
405 print_int("height", dec_ctx->height);
406 print_int("has_b_frames", dec_ctx->has_b_frames);
407 if (dec_ctx->sample_aspect_ratio.num) {
408 print_fmt("sample_aspect_ratio", "%d:%d",
409 dec_ctx->sample_aspect_ratio.num,
410 dec_ctx->sample_aspect_ratio.den);
411 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
412 dec_ctx->width * dec_ctx->sample_aspect_ratio.num,
413 dec_ctx->height * dec_ctx->sample_aspect_ratio.den,
415 print_fmt("display_aspect_ratio", "%d:%d",
416 display_aspect_ratio.num,
417 display_aspect_ratio.den);
419 print_str("pix_fmt", dec_ctx->pix_fmt != PIX_FMT_NONE ? av_pix_fmt_descriptors[dec_ctx->pix_fmt].name : "unknown");
420 print_int("level", dec_ctx->level);
423 case AVMEDIA_TYPE_AUDIO:
424 print_str("sample_rate", value_string(val_str, sizeof(val_str), dec_ctx->sample_rate, unit_hertz_str));
425 print_int("channels", dec_ctx->channels);
426 print_int("bits_per_sample", av_get_bits_per_sample(dec_ctx->codec_id));
430 print_str("codec_type", "unknown");
433 if (fmt_ctx->iformat->flags & AVFMT_SHOW_IDS)
434 print_fmt("id=", "0x%x", stream->id);
435 print_fmt("r_frame_rate", "%d/%d", stream->r_frame_rate.num, stream->r_frame_rate.den);
436 print_fmt("avg_frame_rate", "%d/%d", stream->avg_frame_rate.num, stream->avg_frame_rate.den);
437 print_fmt("time_base", "%d/%d", stream->time_base.num, stream->time_base.den);
438 print_str("start_time", time_value_string(val_str, sizeof(val_str), stream->start_time, &stream->time_base));
439 print_str("duration", time_value_string(val_str, sizeof(val_str), stream->duration, &stream->time_base));
440 if (stream->nb_frames)
441 print_fmt("nb_frames", "%"PRId64, stream->nb_frames);
443 w->show_tags(w, stream->metadata);
445 w->print_footer("STREAM");
450 static void show_streams(struct writer *w, AVFormatContext *fmt_ctx)
453 for (i = 0; i < fmt_ctx->nb_streams; i++)
454 show_stream(w, fmt_ctx, i);
457 static void show_format(struct writer *w, AVFormatContext *fmt_ctx)
460 struct print_buf pbuf = {.s = NULL};
462 w->print_header("FORMAT");
463 print_str0("filename", fmt_ctx->filename);
464 print_int("nb_streams", fmt_ctx->nb_streams);
465 print_str("format_name", fmt_ctx->iformat->name);
466 print_str("format_long_name", fmt_ctx->iformat->long_name);
467 print_str("start_time", time_value_string(val_str, sizeof(val_str), fmt_ctx->start_time, &AV_TIME_BASE_Q));
468 print_str("duration", time_value_string(val_str, sizeof(val_str), fmt_ctx->duration, &AV_TIME_BASE_Q));
469 print_str("size", value_string(val_str, sizeof(val_str), fmt_ctx->file_size, unit_byte_str));
470 print_str("bit_rate", value_string(val_str, sizeof(val_str), fmt_ctx->bit_rate, unit_bit_per_second_str));
471 w->show_tags(w, fmt_ctx->metadata);
472 w->print_footer("FORMAT");
477 static int open_input_file(AVFormatContext **fmt_ctx_ptr, const char *filename)
480 AVFormatContext *fmt_ctx = NULL;
481 AVDictionaryEntry *t;
483 if ((err = avformat_open_input(&fmt_ctx, filename, iformat, &format_opts)) < 0) {
484 print_error(filename, err);
487 if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
488 av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
489 return AVERROR_OPTION_NOT_FOUND;
493 /* fill the streams in the format context */
494 if ((err = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
495 print_error(filename, err);
499 av_dump_format(fmt_ctx, 0, filename, 0);
501 /* bind a decoder to each input stream */
502 for (i = 0; i < fmt_ctx->nb_streams; i++) {
503 AVStream *stream = fmt_ctx->streams[i];
506 if (!(codec = avcodec_find_decoder(stream->codec->codec_id))) {
507 fprintf(stderr, "Unsupported codec with id %d for input stream %d\n",
508 stream->codec->codec_id, stream->index);
509 } else if (avcodec_open2(stream->codec, codec, NULL) < 0) {
510 fprintf(stderr, "Error while opening codec for input stream %d\n",
515 *fmt_ctx_ptr = fmt_ctx;
519 #define WRITER_FUNC(func) \
520 .print_header = func ## _print_header, \
521 .print_footer = func ## _print_footer, \
522 .print_integer = func ## _print_int, \
523 .print_string = func ## _print_str, \
524 .show_tags = func ## _show_tags
526 static struct writer writers[] = {{
532 WRITER_FUNC(default),
540 .print_section_start = json_print_section_start,
541 .print_section_end = json_print_section_end,
546 static int get_writer(const char *name)
551 for (i = 0; i < FF_ARRAY_ELEMS(writers); i++)
552 if (!strcmp(writers[i].name, name))
557 #define SECTION_PRINT(name, multiple_entries, left) do { \
558 if (do_show_ ## name) { \
559 if (w->print_section_start) \
560 w->print_section_start(#name, multiple_entries); \
561 show_ ## name (w, fmt_ctx); \
562 if (w->print_section_end) \
563 w->print_section_end(#name, multiple_entries); \
565 printf("%s", w->section_sep); \
569 static int probe_file(const char *filename)
571 AVFormatContext *fmt_ctx;
575 writer_id = get_writer(print_format);
577 fprintf(stderr, "Invalid output format '%s'\n", print_format);
578 return AVERROR(EINVAL);
580 w = &writers[writer_id];
582 if ((ret = open_input_file(&fmt_ctx, filename)))
586 printf("%s", w->header);
588 SECTION_PRINT(packets, 1, do_show_streams || do_show_format);
589 SECTION_PRINT(streams, 1, do_show_format);
590 SECTION_PRINT(format, 0, 0);
593 printf("%s", w->footer);
595 av_close_input_file(fmt_ctx);
599 static void show_usage(void)
601 printf("Simple multimedia streams analyzer\n");
602 printf("usage: %s [OPTIONS] [INPUT_FILE]\n", program_name);
606 static int opt_format(const char *opt, const char *arg)
608 iformat = av_find_input_format(arg);
610 fprintf(stderr, "Unknown input format: %s\n", arg);
611 return AVERROR(EINVAL);
616 static void opt_input_file(void *optctx, const char *arg)
618 if (input_filename) {
619 fprintf(stderr, "Argument '%s' provided as input filename, but '%s' was already specified.\n",
620 arg, input_filename);
623 if (!strcmp(arg, "-"))
625 input_filename = arg;
628 static int opt_help(const char *opt, const char *arg)
630 const AVClass *class = avformat_get_class();
631 av_log_set_callback(log_callback_help);
633 show_help_options(options, "Main options:\n", 0, 0);
635 av_opt_show2(&class, NULL,
636 AV_OPT_FLAG_DECODING_PARAM, 0);
640 static int opt_pretty(const char *opt, const char *arg)
643 use_value_prefix = 1;
644 use_byte_value_binary_prefix = 1;
645 use_value_sexagesimal_format = 1;
649 static const OptionDef options[] = {
650 #include "cmdutils_common_opts.h"
651 { "f", HAS_ARG, {(void*)opt_format}, "force format", "format" },
652 { "unit", OPT_BOOL, {(void*)&show_value_unit}, "show unit of the displayed values" },
653 { "prefix", OPT_BOOL, {(void*)&use_value_prefix}, "use SI prefixes for the displayed values" },
654 { "byte_binary_prefix", OPT_BOOL, {(void*)&use_byte_value_binary_prefix},
655 "use binary prefixes for byte units" },
656 { "sexagesimal", OPT_BOOL, {(void*)&use_value_sexagesimal_format},
657 "use sexagesimal format HOURS:MM:SS.MICROSECONDS for time units" },
658 { "pretty", 0, {(void*)&opt_pretty},
659 "prettify the format of displayed values, make it more human readable" },
660 { "print_format", OPT_STRING | HAS_ARG, {(void*)&print_format}, "set the output printing format (available formats are: default, json)", "format" },
661 { "show_format", OPT_BOOL, {(void*)&do_show_format} , "show format/container info" },
662 { "show_packets", OPT_BOOL, {(void*)&do_show_packets}, "show packets info" },
663 { "show_streams", OPT_BOOL, {(void*)&do_show_streams}, "show streams info" },
664 { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
665 { "i", HAS_ARG, {(void *)opt_input_file}, "read specified file", "input_file"},
669 int main(int argc, char **argv)
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);