OSDN Git Service

Merge remote-tracking branch 'qatar/master'
[coroid/ffmpeg_saccubus.git] / 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 static char *value_string(char *buf, int buf_size, double val, const char *unit)
62 {
63     if (unit == unit_second_str && use_value_sexagesimal_format) {
64         double secs;
65         int hours, mins;
66         secs  = val;
67         mins  = (int)secs / 60;
68         secs  = secs - mins * 60;
69         hours = mins / 60;
70         mins %= 60;
71         snprintf(buf, buf_size, "%d:%02d:%09.6f", hours, mins, secs);
72     } else if (use_value_prefix) {
73         const char *prefix_string;
74         int index;
75
76         if (unit == unit_byte_str && use_byte_value_binary_prefix) {
77             index = (int) (log(val)/log(2)) / 10;
78             index = av_clip(index, 0, FF_ARRAY_ELEMS(binary_unit_prefixes) -1);
79             val /= pow(2, index*10);
80             prefix_string = binary_unit_prefixes[index];
81         } else {
82             index = (int) (log10(val)) / 3;
83             index = av_clip(index, 0, FF_ARRAY_ELEMS(decimal_unit_prefixes) -1);
84             val /= pow(10, index*3);
85             prefix_string = decimal_unit_prefixes[index];
86         }
87
88         snprintf(buf, buf_size, "%.3f%s%s%s", val, prefix_string || show_value_unit ? " " : "",
89                  prefix_string, show_value_unit ? unit : "");
90     } else {
91         snprintf(buf, buf_size, "%f%s%s", val, show_value_unit ? " " : "",
92                  show_value_unit ? unit : "");
93     }
94
95     return buf;
96 }
97
98 static char *time_value_string(char *buf, int buf_size, int64_t val, const AVRational *time_base)
99 {
100     if (val == AV_NOPTS_VALUE) {
101         snprintf(buf, buf_size, "N/A");
102     } else {
103         value_string(buf, buf_size, val * av_q2d(*time_base), unit_second_str);
104     }
105
106     return buf;
107 }
108
109 static char *ts_value_string (char *buf, int buf_size, int64_t ts)
110 {
111     if (ts == AV_NOPTS_VALUE) {
112         snprintf(buf, buf_size, "N/A");
113     } else {
114         snprintf(buf, buf_size, "%"PRId64, ts);
115     }
116
117     return buf;
118 }
119
120 static const char *media_type_string(enum AVMediaType media_type)
121 {
122     const char *s = av_get_media_type_string(media_type);
123     return s ? s : "unknown";
124 }
125
126
127 struct writer {
128     const char *name;
129     const char *item_sep;           ///< separator between key/value couples
130     const char *items_sep;          ///< separator between sets of key/value couples
131     const char *section_sep;        ///< separator between sections (streams, packets, ...)
132     const char *header, *footer;
133     void (*print_header)(const char *);
134     void (*print_footer)(const char *);
135     void (*print_fmt_f)(const char *, const char *, ...);
136     void (*print_int_f)(const char *, int);
137     void (*show_tags)(struct writer *w, AVDictionary *dict);
138 };
139
140
141 /* Default output */
142
143 static void default_print_header(const char *section)
144 {
145     printf("[%s]\n", section);
146 }
147
148 static void default_print_fmt(const char *key, const char *fmt, ...)
149 {
150     va_list ap;
151     va_start(ap, fmt);
152     printf("%s=", key);
153     vprintf(fmt, ap);
154     va_end(ap);
155 }
156
157 static void default_print_int(const char *key, int value)
158 {
159     printf("%s=%d", key, value);
160 }
161
162 static void default_print_footer(const char *section)
163 {
164     printf("\n[/%s]", section);
165 }
166
167
168 /* Print helpers */
169
170 #define print_fmt0(k, f, a...) w->print_fmt_f(k, f, ##a)
171 #define print_fmt( k, f, a...) do {   \
172     if (w->item_sep)                  \
173         printf("%s", w->item_sep);    \
174     w->print_fmt_f(k, f, ##a);        \
175 } while (0)
176
177 #define print_int0(k, v) w->print_int_f(k, v)
178 #define print_int( k, v) do {      \
179     if (w->item_sep)               \
180         printf("%s", w->item_sep); \
181     print_int0(k, v);              \
182 } while (0)
183
184 #define print_str0(k, v) print_fmt0(k, "%s", v)
185 #define print_str( k, v) print_fmt (k, "%s", v)
186
187
188 static void show_packet(struct writer *w, AVFormatContext *fmt_ctx, AVPacket *pkt, int packet_idx)
189 {
190     char val_str[128];
191     AVStream *st = fmt_ctx->streams[pkt->stream_index];
192
193     if (packet_idx)
194         printf("%s", w->items_sep);
195     w->print_header("PACKET");
196     print_str0("codec_type",      media_type_string(st->codec->codec_type));
197     print_int("stream_index",     pkt->stream_index);
198     print_str("pts",              ts_value_string  (val_str, sizeof(val_str), pkt->pts));
199     print_str("pts_time",         time_value_string(val_str, sizeof(val_str), pkt->pts, &st->time_base));
200     print_str("dts",              ts_value_string  (val_str, sizeof(val_str), pkt->dts));
201     print_str("dts_time",         time_value_string(val_str, sizeof(val_str), pkt->dts, &st->time_base));
202     print_str("duration",         ts_value_string  (val_str, sizeof(val_str), pkt->duration));
203     print_str("duration_time",    time_value_string(val_str, sizeof(val_str), pkt->duration, &st->time_base));
204     print_str("size",             value_string     (val_str, sizeof(val_str), pkt->size, unit_byte_str));
205     print_fmt("pos",   "%"PRId64, pkt->pos);
206     print_fmt("flags", "%c",      pkt->flags & AV_PKT_FLAG_KEY ? 'K' : '_');
207     w->print_footer("PACKET");
208     fflush(stdout);
209 }
210
211 static void show_packets(struct writer *w, AVFormatContext *fmt_ctx)
212 {
213     AVPacket pkt;
214     int i = 0;
215
216     av_init_packet(&pkt);
217
218     while (!av_read_frame(fmt_ctx, &pkt))
219         show_packet(w, fmt_ctx, &pkt, i++);
220 }
221
222 static void default_show_tags(struct writer *w, AVDictionary *dict)
223 {
224     AVDictionaryEntry *tag = NULL;
225     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
226         printf("\nTAG:");
227         print_str0(tag->key, tag->value);
228     }
229 }
230
231 static void show_stream(struct writer *w, AVFormatContext *fmt_ctx, int stream_idx)
232 {
233     AVStream *stream = fmt_ctx->streams[stream_idx];
234     AVCodecContext *dec_ctx;
235     AVCodec *dec;
236     char val_str[128];
237     AVRational display_aspect_ratio;
238
239     if (stream_idx)
240         printf("%s", w->items_sep);
241     w->print_header("STREAM");
242
243     print_int0("index", stream->index);
244
245     if ((dec_ctx = stream->codec)) {
246         if ((dec = dec_ctx->codec)) {
247             print_str("codec_name",      dec->name);
248             print_str("codec_long_name", dec->long_name);
249         } else {
250             print_str("codec_name",      "unknown");
251         }
252
253         print_str("codec_type",               media_type_string(dec_ctx->codec_type));
254         print_fmt("codec_time_base", "%d/%d", dec_ctx->time_base.num, dec_ctx->time_base.den);
255
256         /* print AVI/FourCC tag */
257         av_get_codec_tag_string(val_str, sizeof(val_str), dec_ctx->codec_tag);
258         print_str("codec_tag_string",    val_str);
259         print_fmt("codec_tag", "0x%04x", dec_ctx->codec_tag);
260
261         switch (dec_ctx->codec_type) {
262         case AVMEDIA_TYPE_VIDEO:
263             print_int("width",        dec_ctx->width);
264             print_int("height",       dec_ctx->height);
265             print_int("has_b_frames", dec_ctx->has_b_frames);
266             if (dec_ctx->sample_aspect_ratio.num) {
267                 print_fmt("sample_aspect_ratio", "%d:%d",
268                           dec_ctx->sample_aspect_ratio.num,
269                           dec_ctx->sample_aspect_ratio.den);
270                 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
271                           dec_ctx->width  * dec_ctx->sample_aspect_ratio.num,
272                           dec_ctx->height * dec_ctx->sample_aspect_ratio.den,
273                           1024*1024);
274                 print_fmt("display_aspect_ratio", "%d:%d",
275                           display_aspect_ratio.num,
276                           display_aspect_ratio.den);
277             }
278             print_str("pix_fmt", dec_ctx->pix_fmt != PIX_FMT_NONE ? av_pix_fmt_descriptors[dec_ctx->pix_fmt].name : "unknown");
279             print_int("level",   dec_ctx->level);
280             break;
281
282         case AVMEDIA_TYPE_AUDIO:
283             print_str("sample_rate",     value_string(val_str, sizeof(val_str), dec_ctx->sample_rate, unit_hertz_str));
284             print_int("channels",        dec_ctx->channels);
285             print_int("bits_per_sample", av_get_bits_per_sample(dec_ctx->codec_id));
286             break;
287         }
288     } else {
289         print_fmt("codec_type", "unknown");
290     }
291
292     if (fmt_ctx->iformat->flags & AVFMT_SHOW_IDS)
293         print_fmt("id=", "0x%x", stream->id);
294     print_fmt("r_frame_rate",   "%d/%d", stream->r_frame_rate.num,   stream->r_frame_rate.den);
295     print_fmt("avg_frame_rate", "%d/%d", stream->avg_frame_rate.num, stream->avg_frame_rate.den);
296     print_fmt("time_base",      "%d/%d", stream->time_base.num,      stream->time_base.den);
297     print_str("start_time", time_value_string(val_str, sizeof(val_str), stream->start_time, &stream->time_base));
298     print_str("duration",   time_value_string(val_str, sizeof(val_str), stream->duration,   &stream->time_base));
299     if (stream->nb_frames)
300         print_fmt("nb_frames", "%"PRId64, stream->nb_frames);
301
302     w->show_tags(w, stream->metadata);
303
304     w->print_footer("STREAM");
305     fflush(stdout);
306 }
307
308 static void show_streams(struct writer *w, AVFormatContext *fmt_ctx)
309 {
310     int i;
311     for (i = 0; i < fmt_ctx->nb_streams; i++)
312         show_stream(w, fmt_ctx, i);
313 }
314
315 static void show_format(struct writer *w, AVFormatContext *fmt_ctx)
316 {
317     char val_str[128];
318
319     w->print_header("FORMAT");
320     print_str0("filename",        fmt_ctx->filename);
321     print_int("nb_streams",       fmt_ctx->nb_streams);
322     print_str("format_name",      fmt_ctx->iformat->name);
323     print_str("format_long_name", fmt_ctx->iformat->long_name);
324     print_str("start_time",       time_value_string(val_str, sizeof(val_str), fmt_ctx->start_time, &AV_TIME_BASE_Q));
325     print_str("duration",         time_value_string(val_str, sizeof(val_str), fmt_ctx->duration,   &AV_TIME_BASE_Q));
326     print_str("size",             value_string(val_str, sizeof(val_str), fmt_ctx->file_size, unit_byte_str));
327     print_str("bit_rate",         value_string(val_str, sizeof(val_str), fmt_ctx->bit_rate,  unit_bit_per_second_str));
328     w->show_tags(w, fmt_ctx->metadata);
329     w->print_footer("FORMAT");
330     fflush(stdout);
331 }
332
333 static int open_input_file(AVFormatContext **fmt_ctx_ptr, const char *filename)
334 {
335     int err, i;
336     AVFormatContext *fmt_ctx = NULL;
337     AVDictionaryEntry *t;
338
339     if ((err = avformat_open_input(&fmt_ctx, filename, iformat, &format_opts)) < 0) {
340         print_error(filename, err);
341         return err;
342     }
343     if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
344         av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
345         return AVERROR_OPTION_NOT_FOUND;
346     }
347
348
349     /* fill the streams in the format context */
350     if ((err = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
351         print_error(filename, err);
352         return err;
353     }
354
355     av_dump_format(fmt_ctx, 0, filename, 0);
356
357     /* bind a decoder to each input stream */
358     for (i = 0; i < fmt_ctx->nb_streams; i++) {
359         AVStream *stream = fmt_ctx->streams[i];
360         AVCodec *codec;
361
362         if (!(codec = avcodec_find_decoder(stream->codec->codec_id))) {
363             fprintf(stderr, "Unsupported codec with id %d for input stream %d\n",
364                     stream->codec->codec_id, stream->index);
365         } else if (avcodec_open2(stream->codec, codec, NULL) < 0) {
366             fprintf(stderr, "Error while opening codec for input stream %d\n",
367                     stream->index);
368         }
369     }
370
371     *fmt_ctx_ptr = fmt_ctx;
372     return 0;
373 }
374
375 #define WRITER_FUNC(func)                  \
376     .print_header = func ## _print_header, \
377     .print_footer = func ## _print_footer, \
378     .print_fmt_f  = func ## _print_fmt,    \
379     .print_int_f  = func ## _print_int,    \
380     .show_tags    = func ## _show_tags
381
382 static struct writer writers[] = {{
383         .name         = "default",
384         .item_sep     = "\n",
385         .items_sep    = "\n",
386         .section_sep  = "\n",
387         .footer       = "\n",
388         WRITER_FUNC(default),
389     }
390 };
391
392 static int get_writer(const char *name)
393 {
394     int i;
395     if (!name)
396         return 0;
397     for (i = 0; i < FF_ARRAY_ELEMS(writers); i++)
398         if (!strcmp(writers[i].name, name))
399             return i;
400     return -1;
401 }
402
403 #define SECTION_PRINT(name, left) do {                        \
404     if (do_show_ ## name) {                                   \
405         show_ ## name (w, fmt_ctx);                           \
406         if (left)                                             \
407             printf("%s", w->section_sep);                     \
408     }                                                         \
409 } while (0)
410
411 static int probe_file(const char *filename)
412 {
413     AVFormatContext *fmt_ctx;
414     int ret, writer_id;
415     struct writer *w;
416
417     writer_id = get_writer(print_format);
418     if (writer_id < 0) {
419         fprintf(stderr, "Invalid output format '%s'\n", print_format);
420         return AVERROR(EINVAL);
421     }
422     w = &writers[writer_id];
423
424     if ((ret = open_input_file(&fmt_ctx, filename)))
425         return ret;
426
427     if (w->header)
428         printf("%s", w->header);
429
430     SECTION_PRINT(packets, do_show_streams || do_show_format);
431     SECTION_PRINT(streams, do_show_format);
432     SECTION_PRINT(format,  0);
433
434     if (w->footer)
435         printf("%s", w->footer);
436
437     av_close_input_file(fmt_ctx);
438     return 0;
439 }
440
441 static void show_usage(void)
442 {
443     printf("Simple multimedia streams analyzer\n");
444     printf("usage: %s [OPTIONS] [INPUT_FILE]\n", program_name);
445     printf("\n");
446 }
447
448 static int opt_format(const char *opt, const char *arg)
449 {
450     iformat = av_find_input_format(arg);
451     if (!iformat) {
452         fprintf(stderr, "Unknown input format: %s\n", arg);
453         return AVERROR(EINVAL);
454     }
455     return 0;
456 }
457
458 static int opt_input_file(const char *opt, const char *arg)
459 {
460     if (input_filename) {
461         fprintf(stderr, "Argument '%s' provided as input filename, but '%s' was already specified.\n",
462                 arg, input_filename);
463         exit(1);
464     }
465     if (!strcmp(arg, "-"))
466         arg = "pipe:";
467     input_filename = arg;
468     return 0;
469 }
470
471 static int opt_help(const char *opt, const char *arg)
472 {
473     const AVClass *class = avformat_get_class();
474     av_log_set_callback(log_callback_help);
475     show_usage();
476     show_help_options(options, "Main options:\n", 0, 0);
477     printf("\n");
478     av_opt_show2(&class, NULL,
479                  AV_OPT_FLAG_DECODING_PARAM, 0);
480     return 0;
481 }
482
483 static int opt_pretty(const char *opt, const char *arg)
484 {
485     show_value_unit              = 1;
486     use_value_prefix             = 1;
487     use_byte_value_binary_prefix = 1;
488     use_value_sexagesimal_format = 1;
489     return 0;
490 }
491
492 static const OptionDef options[] = {
493 #include "cmdutils_common_opts.h"
494     { "f", HAS_ARG, {(void*)opt_format}, "force format", "format" },
495     { "unit", OPT_BOOL, {(void*)&show_value_unit}, "show unit of the displayed values" },
496     { "prefix", OPT_BOOL, {(void*)&use_value_prefix}, "use SI prefixes for the displayed values" },
497     { "byte_binary_prefix", OPT_BOOL, {(void*)&use_byte_value_binary_prefix},
498       "use binary prefixes for byte units" },
499     { "sexagesimal", OPT_BOOL,  {(void*)&use_value_sexagesimal_format},
500       "use sexagesimal format HOURS:MM:SS.MICROSECONDS for time units" },
501     { "pretty", 0, {(void*)&opt_pretty},
502       "prettify the format of displayed values, make it more human readable" },
503     { "show_format",  OPT_BOOL, {(void*)&do_show_format} , "show format/container info" },
504     { "show_packets", OPT_BOOL, {(void*)&do_show_packets}, "show packets info" },
505     { "show_streams", OPT_BOOL, {(void*)&do_show_streams}, "show streams info" },
506     { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
507     { "i", HAS_ARG, {(void *)opt_input_file}, "read specified file", "input_file"},
508     { NULL, },
509 };
510
511 int main(int argc, char **argv)
512 {
513     int ret;
514
515     av_register_all();
516     init_opts();
517 #if CONFIG_AVDEVICE
518     avdevice_register_all();
519 #endif
520
521     show_banner();
522     parse_options(argc, argv, options, opt_input_file);
523
524     if (!input_filename) {
525         show_usage();
526         fprintf(stderr, "You have to specify one input file.\n");
527         fprintf(stderr, "Use -h to get full help or, even better, run 'man %s'.\n", program_name);
528         exit(1);
529     }
530
531     ret = probe_file(input_filename);
532
533     return ret;
534 }