]> git.sesse.net Git - ffmpeg/blob - ffprobe.c
sdl: use AV_OPT_TYPE_IMAGE_SIZE.
[ffmpeg] / ffprobe.c
1 /*
2  * Copyright (c) 2007-2010 Stefano Sabatini
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 /**
22  * @file
23  * simple media prober based on the FFmpeg libraries
24  */
25
26 #include "config.h"
27 #include "version.h"
28
29 #include "libavformat/avformat.h"
30 #include "libavcodec/avcodec.h"
31 #include "libavutil/avstring.h"
32 #include "libavutil/bprint.h"
33 #include "libavutil/opt.h"
34 #include "libavutil/pixdesc.h"
35 #include "libavutil/dict.h"
36 #include "libavutil/timecode.h"
37 #include "libavdevice/avdevice.h"
38 #include "libswscale/swscale.h"
39 #include "libswresample/swresample.h"
40 #include "libpostproc/postprocess.h"
41 #include "cmdutils.h"
42
43 const char program_name[] = "ffprobe";
44 const int program_birth_year = 2007;
45
46 static int do_count_frames = 0;
47 static int do_count_packets = 0;
48 static int do_read_frames  = 0;
49 static int do_read_packets = 0;
50 static int do_show_error   = 0;
51 static int do_show_format  = 0;
52 static int do_show_frames  = 0;
53 static AVDictionary *fmt_entries_to_show = NULL;
54 static int nb_fmt_entries_to_show;
55 static int do_show_packets = 0;
56 static int do_show_streams = 0;
57 static int do_show_program_version  = 0;
58 static int do_show_library_versions = 0;
59
60 static int show_value_unit              = 0;
61 static int use_value_prefix             = 0;
62 static int use_byte_value_binary_prefix = 0;
63 static int use_value_sexagesimal_format = 0;
64 static int show_private_data            = 1;
65
66 static char *print_format;
67
68 static const OptionDef options[];
69
70 /* FFprobe context */
71 static const char *input_filename;
72 static AVInputFormat *iformat = NULL;
73
74 static const char *const binary_unit_prefixes [] = { "", "Ki", "Mi", "Gi", "Ti", "Pi" };
75 static const char *const decimal_unit_prefixes[] = { "", "K" , "M" , "G" , "T" , "P"  };
76
77 static const char unit_second_str[]         = "s"    ;
78 static const char unit_hertz_str[]          = "Hz"   ;
79 static const char unit_byte_str[]           = "byte" ;
80 static const char unit_bit_per_second_str[] = "bit/s";
81 static uint64_t *nb_streams_packets;
82 static uint64_t *nb_streams_frames;
83
84 void av_noreturn exit_program(int ret)
85 {
86     av_dict_free(&fmt_entries_to_show);
87     exit(ret);
88 }
89
90 struct unit_value {
91     union { double d; long long int i; } val;
92     const char *unit;
93 };
94
95 static char *value_string(char *buf, int buf_size, struct unit_value uv)
96 {
97     double vald;
98     int show_float = 0;
99
100     if (uv.unit == unit_second_str) {
101         vald = uv.val.d;
102         show_float = 1;
103     } else {
104         vald = uv.val.i;
105     }
106
107     if (uv.unit == unit_second_str && use_value_sexagesimal_format) {
108         double secs;
109         int hours, mins;
110         secs  = vald;
111         mins  = (int)secs / 60;
112         secs  = secs - mins * 60;
113         hours = mins / 60;
114         mins %= 60;
115         snprintf(buf, buf_size, "%d:%02d:%09.6f", hours, mins, secs);
116     } else {
117         const char *prefix_string = "";
118         int l;
119
120         if (use_value_prefix && vald > 1) {
121             long long int index;
122
123             if (uv.unit == unit_byte_str && use_byte_value_binary_prefix) {
124                 index = (long long int) (log(vald)/log(2)) / 10;
125                 index = av_clip(index, 0, FF_ARRAY_ELEMS(binary_unit_prefixes) - 1);
126                 vald /= pow(2, index * 10);
127                 prefix_string = binary_unit_prefixes[index];
128             } else {
129                 index = (long long int) (log10(vald)) / 3;
130                 index = av_clip(index, 0, FF_ARRAY_ELEMS(decimal_unit_prefixes) - 1);
131                 vald /= pow(10, index * 3);
132                 prefix_string = decimal_unit_prefixes[index];
133             }
134         }
135
136         if (show_float || (use_value_prefix && vald != (long long int)vald))
137             l = snprintf(buf, buf_size, "%f", vald);
138         else
139             l = snprintf(buf, buf_size, "%lld", (long long int)vald);
140         snprintf(buf+l, buf_size-l, "%s%s%s", *prefix_string || show_value_unit ? " " : "",
141                  prefix_string, show_value_unit ? uv.unit : "");
142     }
143
144     return buf;
145 }
146
147 /* WRITERS API */
148
149 typedef struct WriterContext WriterContext;
150
151 #define WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS 1
152 #define WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER 2
153
154 typedef struct Writer {
155     int priv_size;                  ///< private size for the writer context
156     const char *name;
157
158     int  (*init)  (WriterContext *wctx, const char *args, void *opaque);
159     void (*uninit)(WriterContext *wctx);
160
161     void (*print_header)(WriterContext *ctx);
162     void (*print_footer)(WriterContext *ctx);
163
164     void (*print_chapter_header)(WriterContext *wctx, const char *);
165     void (*print_chapter_footer)(WriterContext *wctx, const char *);
166     void (*print_section_header)(WriterContext *wctx, const char *);
167     void (*print_section_footer)(WriterContext *wctx, const char *);
168     void (*print_integer)       (WriterContext *wctx, const char *, long long int);
169     void (*print_string)        (WriterContext *wctx, const char *, const char *);
170     void (*show_tags)           (WriterContext *wctx, AVDictionary *dict);
171     int flags;                  ///< a combination or WRITER_FLAG_*
172 } Writer;
173
174 struct WriterContext {
175     const AVClass *class;           ///< class of the writer
176     const Writer *writer;           ///< the Writer of which this is an instance
177     char *name;                     ///< name of this writer instance
178     void *priv;                     ///< private data for use by the filter
179     unsigned int nb_item;           ///< number of the item printed in the given section, starting at 0
180     unsigned int nb_section;        ///< number of the section printed in the given section sequence, starting at 0
181     unsigned int nb_chapter;        ///< number of the chapter, starting at 0
182
183     int is_fmt_chapter;             ///< tells if the current chapter is "format", required by the print_format_entry option
184 };
185
186 static const char *writer_get_name(void *p)
187 {
188     WriterContext *wctx = p;
189     return wctx->writer->name;
190 }
191
192 static const AVClass writer_class = {
193     "Writer",
194     writer_get_name,
195     NULL,
196     LIBAVUTIL_VERSION_INT,
197 };
198
199 static void writer_close(WriterContext **wctx)
200 {
201     if (!*wctx)
202         return;
203
204     if ((*wctx)->writer->uninit)
205         (*wctx)->writer->uninit(*wctx);
206     av_freep(&((*wctx)->priv));
207     av_freep(wctx);
208 }
209
210 static int writer_open(WriterContext **wctx, const Writer *writer,
211                        const char *args, void *opaque)
212 {
213     int ret = 0;
214
215     if (!(*wctx = av_malloc(sizeof(WriterContext)))) {
216         ret = AVERROR(ENOMEM);
217         goto fail;
218     }
219
220     if (!((*wctx)->priv = av_mallocz(writer->priv_size))) {
221         ret = AVERROR(ENOMEM);
222         goto fail;
223     }
224
225     (*wctx)->class = &writer_class;
226     (*wctx)->writer = writer;
227     if ((*wctx)->writer->init)
228         ret = (*wctx)->writer->init(*wctx, args, opaque);
229     if (ret < 0)
230         goto fail;
231
232     return 0;
233
234 fail:
235     writer_close(wctx);
236     return ret;
237 }
238
239 static inline void writer_print_header(WriterContext *wctx)
240 {
241     if (wctx->writer->print_header)
242         wctx->writer->print_header(wctx);
243     wctx->nb_chapter = 0;
244 }
245
246 static inline void writer_print_footer(WriterContext *wctx)
247 {
248     if (wctx->writer->print_footer)
249         wctx->writer->print_footer(wctx);
250 }
251
252 static inline void writer_print_chapter_header(WriterContext *wctx,
253                                                const char *chapter)
254 {
255     if (wctx->writer->print_chapter_header)
256         wctx->writer->print_chapter_header(wctx, chapter);
257     wctx->nb_section = 0;
258
259     wctx->is_fmt_chapter = !strcmp(chapter, "format");
260 }
261
262 static inline void writer_print_chapter_footer(WriterContext *wctx,
263                                                const char *chapter)
264 {
265     if (wctx->writer->print_chapter_footer)
266         wctx->writer->print_chapter_footer(wctx, chapter);
267     wctx->nb_chapter++;
268 }
269
270 static inline void writer_print_section_header(WriterContext *wctx,
271                                                const char *section)
272 {
273     if (wctx->writer->print_section_header)
274         wctx->writer->print_section_header(wctx, section);
275     wctx->nb_item = 0;
276 }
277
278 static inline void writer_print_section_footer(WriterContext *wctx,
279                                                const char *section)
280 {
281     if (wctx->writer->print_section_footer)
282         wctx->writer->print_section_footer(wctx, section);
283     wctx->nb_section++;
284 }
285
286 static inline void writer_print_integer(WriterContext *wctx,
287                                         const char *key, long long int val)
288 {
289     if (!wctx->is_fmt_chapter || !fmt_entries_to_show || av_dict_get(fmt_entries_to_show, key, NULL, 0)) {
290         wctx->writer->print_integer(wctx, key, val);
291         wctx->nb_item++;
292     }
293 }
294
295 static inline void writer_print_string(WriterContext *wctx,
296                                        const char *key, const char *val, int opt)
297 {
298     if (opt && !(wctx->writer->flags & WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS))
299         return;
300     if (!wctx->is_fmt_chapter || !fmt_entries_to_show || av_dict_get(fmt_entries_to_show, key, NULL, 0)) {
301         wctx->writer->print_string(wctx, key, val);
302         wctx->nb_item++;
303     }
304 }
305
306 static void writer_print_time(WriterContext *wctx, const char *key,
307                               int64_t ts, const AVRational *time_base)
308 {
309     char buf[128];
310
311     if (!wctx->is_fmt_chapter || !fmt_entries_to_show || av_dict_get(fmt_entries_to_show, key, NULL, 0)) {
312         if (ts == AV_NOPTS_VALUE) {
313             writer_print_string(wctx, key, "N/A", 1);
314         } else {
315             double d = ts * av_q2d(*time_base);
316             value_string(buf, sizeof(buf), (struct unit_value){.val.d=d, .unit=unit_second_str});
317             writer_print_string(wctx, key, buf, 0);
318         }
319     }
320 }
321
322 static void writer_print_ts(WriterContext *wctx, const char *key, int64_t ts)
323 {
324     if (ts == AV_NOPTS_VALUE) {
325         writer_print_string(wctx, key, "N/A", 1);
326     } else {
327         writer_print_integer(wctx, key, ts);
328     }
329 }
330
331 static inline void writer_show_tags(WriterContext *wctx, AVDictionary *dict)
332 {
333     wctx->writer->show_tags(wctx, dict);
334 }
335
336 #define MAX_REGISTERED_WRITERS_NB 64
337
338 static const Writer *registered_writers[MAX_REGISTERED_WRITERS_NB + 1];
339
340 static int writer_register(const Writer *writer)
341 {
342     static int next_registered_writer_idx = 0;
343
344     if (next_registered_writer_idx == MAX_REGISTERED_WRITERS_NB)
345         return AVERROR(ENOMEM);
346
347     registered_writers[next_registered_writer_idx++] = writer;
348     return 0;
349 }
350
351 static const Writer *writer_get_by_name(const char *name)
352 {
353     int i;
354
355     for (i = 0; registered_writers[i]; i++)
356         if (!strcmp(registered_writers[i]->name, name))
357             return registered_writers[i];
358
359     return NULL;
360 }
361
362
363 /* WRITERS */
364
365 /* Default output */
366
367 typedef struct DefaultContext {
368     const AVClass *class;
369     int nokey;
370     int noprint_wrappers;
371 } DefaultContext;
372
373 #define OFFSET(x) offsetof(DefaultContext, x)
374
375 static const AVOption default_options[] = {
376     { "noprint_wrappers", "do not print headers and footers", OFFSET(noprint_wrappers), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
377     { "nw",               "do not print headers and footers", OFFSET(noprint_wrappers), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
378     { "nokey",          "force no key printing",     OFFSET(nokey),          AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
379     { "nk",             "force no key printing",     OFFSET(nokey),          AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
380     {NULL},
381 };
382
383 static const char *default_get_name(void *ctx)
384 {
385     return "default";
386 }
387
388 static const AVClass default_class = {
389     "DefaultContext",
390     default_get_name,
391     default_options
392 };
393
394 static av_cold int default_init(WriterContext *wctx, const char *args, void *opaque)
395 {
396     DefaultContext *def = wctx->priv;
397     int err;
398
399     def->class = &default_class;
400     av_opt_set_defaults(def);
401
402     if (nb_fmt_entries_to_show == 1)
403         def->nokey = 1;
404
405     if (args &&
406         (err = (av_set_options_string(def, args, "=", ":"))) < 0) {
407         av_log(wctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
408         return err;
409     }
410
411     return 0;
412 }
413
414 static void default_print_footer(WriterContext *wctx)
415 {
416     DefaultContext *def = wctx->priv;
417
418     if (!def->noprint_wrappers)
419         printf("\n");
420 }
421
422 static void default_print_chapter_header(WriterContext *wctx, const char *chapter)
423 {
424     DefaultContext *def = wctx->priv;
425
426     if (!def->noprint_wrappers && wctx->nb_chapter)
427         printf("\n");
428 }
429
430 /* lame uppercasing routine, assumes the string is lower case ASCII */
431 static inline char *upcase_string(char *dst, size_t dst_size, const char *src)
432 {
433     int i;
434     for (i = 0; src[i] && i < dst_size-1; i++)
435         dst[i] = av_toupper(src[i]);
436     dst[i] = 0;
437     return dst;
438 }
439
440 static void default_print_section_header(WriterContext *wctx, const char *section)
441 {
442     DefaultContext *def = wctx->priv;
443     char buf[32];
444
445     if (wctx->nb_section)
446         printf("\n");
447     if (!def->noprint_wrappers)
448         printf("[%s]\n", upcase_string(buf, sizeof(buf), section));
449 }
450
451 static void default_print_section_footer(WriterContext *wctx, const char *section)
452 {
453     DefaultContext *def = wctx->priv;
454     char buf[32];
455
456     if (!def->noprint_wrappers)
457         printf("[/%s]", upcase_string(buf, sizeof(buf), section));
458 }
459
460 static void default_print_str(WriterContext *wctx, const char *key, const char *value)
461 {
462     DefaultContext *def = wctx->priv;
463     if (!def->nokey)
464         printf("%s=", key);
465     printf("%s\n", value);
466 }
467
468 static void default_print_int(WriterContext *wctx, const char *key, long long int value)
469 {
470     DefaultContext *def = wctx->priv;
471
472     if (!def->nokey)
473         printf("%s=", key);
474     printf("%lld\n", value);
475 }
476
477 static void default_show_tags(WriterContext *wctx, AVDictionary *dict)
478 {
479     AVDictionaryEntry *tag = NULL;
480     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
481         if (!fmt_entries_to_show || (tag->key && av_dict_get(fmt_entries_to_show, tag->key, NULL, 0)))
482             printf("TAG:");
483         writer_print_string(wctx, tag->key, tag->value, 0);
484     }
485 }
486
487 static const Writer default_writer = {
488     .name                  = "default",
489     .priv_size             = sizeof(DefaultContext),
490     .init                  = default_init,
491     .print_footer          = default_print_footer,
492     .print_chapter_header  = default_print_chapter_header,
493     .print_section_header  = default_print_section_header,
494     .print_section_footer  = default_print_section_footer,
495     .print_integer         = default_print_int,
496     .print_string          = default_print_str,
497     .show_tags             = default_show_tags,
498     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
499 };
500
501 /* Compact output */
502
503 /**
504  * Escape \n, \r, \\ and sep characters contained in s, and print the
505  * resulting string.
506  */
507 static const char *c_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
508 {
509     const char *p;
510
511     for (p = src; *p; p++) {
512         switch (*src) {
513         case '\n': av_bprintf(dst, "%s", "\\n");  break;
514         case '\r': av_bprintf(dst, "%s", "\\r");  break;
515         case '\\': av_bprintf(dst, "%s", "\\\\"); break;
516         default:
517             if (*p == sep)
518                 av_bprint_chars(dst, '\\', 1);
519             av_bprint_chars(dst, *p, 1);
520         }
521     }
522     return dst->str;
523 }
524
525 /**
526  * Quote fields containing special characters, check RFC4180.
527  */
528 static const char *csv_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
529 {
530     const char *p;
531     int quote = 0;
532
533     /* check if input needs quoting */
534     for (p = src; *p; p++)
535         if (*p == '"' || *p == sep || *p == '\n' || *p == '\r')
536             quote = 1;
537
538     if (quote)
539         av_bprint_chars(dst, '\"', 1);
540
541     for (p = src; *p; p++) {
542         if (*p == '"')
543             av_bprint_chars(dst, '\"', 1);
544         av_bprint_chars(dst, *p, 1);
545     }
546     if (quote)
547         av_bprint_chars(dst, '\"', 1);
548     return dst->str;
549 }
550
551 static const char *none_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
552 {
553     return src;
554 }
555
556 typedef struct CompactContext {
557     const AVClass *class;
558     char *item_sep_str;
559     char item_sep;
560     int nokey;
561     char *escape_mode_str;
562     const char * (*escape_str)(AVBPrint *dst, const char *src, const char sep, void *log_ctx);
563 } CompactContext;
564
565 #undef OFFSET
566 #define OFFSET(x) offsetof(CompactContext, x)
567
568 static const AVOption compact_options[]= {
569     {"item_sep", "set item separator",    OFFSET(item_sep_str),    AV_OPT_TYPE_STRING, {.str="|"},  CHAR_MIN, CHAR_MAX },
570     {"s",        "set item separator",    OFFSET(item_sep_str),    AV_OPT_TYPE_STRING, {.str="|"},  CHAR_MIN, CHAR_MAX },
571     {"nokey",    "force no key printing", OFFSET(nokey),           AV_OPT_TYPE_INT,    {.dbl=0},    0,        1        },
572     {"nk",       "force no key printing", OFFSET(nokey),           AV_OPT_TYPE_INT,    {.dbl=0},    0,        1        },
573     {"escape",   "set escape mode",       OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"},  CHAR_MIN, CHAR_MAX },
574     {"e",        "set escape mode",       OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"},  CHAR_MIN, CHAR_MAX },
575     {NULL},
576 };
577
578 static const char *compact_get_name(void *ctx)
579 {
580     return "compact";
581 }
582
583 static const AVClass compact_class = {
584     "CompactContext",
585     compact_get_name,
586     compact_options
587 };
588
589 static av_cold int compact_init(WriterContext *wctx, const char *args, void *opaque)
590 {
591     CompactContext *compact = wctx->priv;
592     int err;
593
594     compact->class = &compact_class;
595     av_opt_set_defaults(compact);
596
597     if (args &&
598         (err = (av_set_options_string(compact, args, "=", ":"))) < 0) {
599         av_log(wctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
600         return err;
601     }
602     if (strlen(compact->item_sep_str) != 1) {
603         av_log(wctx, AV_LOG_ERROR, "Item separator '%s' specified, but must contain a single character\n",
604                compact->item_sep_str);
605         return AVERROR(EINVAL);
606     }
607     compact->item_sep = compact->item_sep_str[0];
608
609     if      (!strcmp(compact->escape_mode_str, "none")) compact->escape_str = none_escape_str;
610     else if (!strcmp(compact->escape_mode_str, "c"   )) compact->escape_str = c_escape_str;
611     else if (!strcmp(compact->escape_mode_str, "csv" )) compact->escape_str = csv_escape_str;
612     else {
613         av_log(wctx, AV_LOG_ERROR, "Unknown escape mode '%s'\n", compact->escape_mode_str);
614         return AVERROR(EINVAL);
615     }
616
617     return 0;
618 }
619
620 static av_cold void compact_uninit(WriterContext *wctx)
621 {
622     CompactContext *compact = wctx->priv;
623
624     av_freep(&compact->item_sep_str);
625     av_freep(&compact->escape_mode_str);
626 }
627
628 static void compact_print_section_header(WriterContext *wctx, const char *section)
629 {
630     CompactContext *compact = wctx->priv;
631
632     printf("%s%c", section, compact->item_sep);
633 }
634
635 static void compact_print_section_footer(WriterContext *wctx, const char *section)
636 {
637     printf("\n");
638 }
639
640 static void compact_print_str(WriterContext *wctx, const char *key, const char *value)
641 {
642     CompactContext *compact = wctx->priv;
643     AVBPrint buf;
644
645     if (wctx->nb_item) printf("%c", compact->item_sep);
646     if (!compact->nokey)
647         printf("%s=", key);
648     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
649     printf("%s", compact->escape_str(&buf, value, compact->item_sep, wctx));
650     av_bprint_finalize(&buf, NULL);
651 }
652
653 static void compact_print_int(WriterContext *wctx, const char *key, long long int value)
654 {
655     CompactContext *compact = wctx->priv;
656
657     if (wctx->nb_item) printf("%c", compact->item_sep);
658     if (!compact->nokey)
659         printf("%s=", key);
660     printf("%lld", value);
661 }
662
663 static void compact_show_tags(WriterContext *wctx, AVDictionary *dict)
664 {
665     CompactContext *compact = wctx->priv;
666     AVDictionaryEntry *tag = NULL;
667     AVBPrint buf;
668
669     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
670         if (wctx->nb_item) printf("%c", compact->item_sep);
671
672         if (!compact->nokey) {
673             av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
674             printf("tag:%s=", compact->escape_str(&buf, tag->key, compact->item_sep, wctx));
675             av_bprint_finalize(&buf, NULL);
676         }
677
678         av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
679         printf("%s", compact->escape_str(&buf, tag->value, compact->item_sep, wctx));
680         av_bprint_finalize(&buf, NULL);
681     }
682 }
683
684 static const Writer compact_writer = {
685     .name                 = "compact",
686     .priv_size            = sizeof(CompactContext),
687     .init                 = compact_init,
688     .uninit               = compact_uninit,
689     .print_section_header = compact_print_section_header,
690     .print_section_footer = compact_print_section_footer,
691     .print_integer        = compact_print_int,
692     .print_string         = compact_print_str,
693     .show_tags            = compact_show_tags,
694     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
695 };
696
697 /* CSV output */
698
699 static av_cold int csv_init(WriterContext *wctx, const char *args, void *opaque)
700 {
701     return compact_init(wctx, "item_sep=,:nokey=1:escape=csv", opaque);
702 }
703
704 static const Writer csv_writer = {
705     .name                 = "csv",
706     .priv_size            = sizeof(CompactContext),
707     .init                 = csv_init,
708     .uninit               = compact_uninit,
709     .print_section_header = compact_print_section_header,
710     .print_section_footer = compact_print_section_footer,
711     .print_integer        = compact_print_int,
712     .print_string         = compact_print_str,
713     .show_tags            = compact_show_tags,
714     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
715 };
716
717 /* JSON output */
718
719 typedef struct {
720     const AVClass *class;
721     int multiple_entries; ///< tells if the given chapter requires multiple entries
722     int print_packets_and_frames;
723     int indent_level;
724     int compact;
725     const char *item_sep, *item_start_end;
726 } JSONContext;
727
728 #undef OFFSET
729 #define OFFSET(x) offsetof(JSONContext, x)
730
731 static const AVOption json_options[]= {
732     { "compact", "enable compact output", OFFSET(compact), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
733     { "c",       "enable compact output", OFFSET(compact), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
734     { NULL }
735 };
736
737 static const char *json_get_name(void *ctx)
738 {
739     return "json";
740 }
741
742 static const AVClass json_class = {
743     "JSONContext",
744     json_get_name,
745     json_options
746 };
747
748 static av_cold int json_init(WriterContext *wctx, const char *args, void *opaque)
749 {
750     JSONContext *json = wctx->priv;
751     int err;
752
753     json->class = &json_class;
754     av_opt_set_defaults(json);
755
756     if (args &&
757         (err = (av_set_options_string(json, args, "=", ":"))) < 0) {
758         av_log(wctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
759         return err;
760     }
761
762     json->item_sep       = json->compact ? ", " : ",\n";
763     json->item_start_end = json->compact ? " "  : "\n";
764
765     return 0;
766 }
767
768 static const char *json_escape_str(AVBPrint *dst, const char *src, void *log_ctx)
769 {
770     static const char json_escape[] = {'"', '\\', '\b', '\f', '\n', '\r', '\t', 0};
771     static const char json_subst[]  = {'"', '\\',  'b',  'f',  'n',  'r',  't', 0};
772     const char *p;
773
774     for (p = src; *p; p++) {
775         char *s = strchr(json_escape, *p);
776         if (s) {
777             av_bprint_chars(dst, '\\', 1);
778             av_bprint_chars(dst, json_subst[s - json_escape], 1);
779         } else if ((unsigned char)*p < 32) {
780             av_bprintf(dst, "\\u00%02x", *p & 0xff);
781         } else {
782             av_bprint_chars(dst, *p, 1);
783         }
784     }
785     return dst->str;
786 }
787
788 static void json_print_header(WriterContext *wctx)
789 {
790     JSONContext *json = wctx->priv;
791     printf("{");
792     json->indent_level++;
793 }
794
795 static void json_print_footer(WriterContext *wctx)
796 {
797     JSONContext *json = wctx->priv;
798     json->indent_level--;
799     printf("\n}\n");
800 }
801
802 #define JSON_INDENT() printf("%*c", json->indent_level * 4, ' ')
803
804 static void json_print_chapter_header(WriterContext *wctx, const char *chapter)
805 {
806     JSONContext *json = wctx->priv;
807     AVBPrint buf;
808
809     if (wctx->nb_chapter)
810         printf(",");
811     printf("\n");
812     json->multiple_entries = !strcmp(chapter, "packets") || !strcmp(chapter, "frames" ) ||
813                              !strcmp(chapter, "packets_and_frames") ||
814                              !strcmp(chapter, "streams") || !strcmp(chapter, "library_versions");
815     if (json->multiple_entries) {
816         JSON_INDENT();
817         av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
818         printf("\"%s\": [\n", json_escape_str(&buf, chapter, wctx));
819         av_bprint_finalize(&buf, NULL);
820         json->print_packets_and_frames = !strcmp(chapter, "packets_and_frames");
821         json->indent_level++;
822     }
823 }
824
825 static void json_print_chapter_footer(WriterContext *wctx, const char *chapter)
826 {
827     JSONContext *json = wctx->priv;
828
829     if (json->multiple_entries) {
830         printf("\n");
831         json->indent_level--;
832         JSON_INDENT();
833         printf("]");
834     }
835 }
836
837 static void json_print_section_header(WriterContext *wctx, const char *section)
838 {
839     JSONContext *json = wctx->priv;
840
841     if (wctx->nb_section)
842         printf(",\n");
843     JSON_INDENT();
844     if (!json->multiple_entries)
845         printf("\"%s\": ", section);
846     printf("{%s", json->item_start_end);
847     json->indent_level++;
848     /* this is required so the parser can distinguish between packets and frames */
849     if (json->print_packets_and_frames) {
850         if (!json->compact)
851             JSON_INDENT();
852         printf("\"type\": \"%s\"%s", section, json->item_sep);
853     }
854 }
855
856 static void json_print_section_footer(WriterContext *wctx, const char *section)
857 {
858     JSONContext *json = wctx->priv;
859
860     printf("%s", json->item_start_end);
861     json->indent_level--;
862     if (!json->compact)
863         JSON_INDENT();
864     printf("}");
865 }
866
867 static inline void json_print_item_str(WriterContext *wctx,
868                                        const char *key, const char *value)
869 {
870     AVBPrint buf;
871
872     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
873     printf("\"%s\":", json_escape_str(&buf, key,   wctx));
874     av_bprint_finalize(&buf, NULL);
875
876     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
877     printf(" \"%s\"", json_escape_str(&buf, value, wctx));
878     av_bprint_finalize(&buf, NULL);
879 }
880
881 static void json_print_str(WriterContext *wctx, const char *key, const char *value)
882 {
883     JSONContext *json = wctx->priv;
884
885     if (wctx->nb_item) printf("%s", json->item_sep);
886     if (!json->compact)
887         JSON_INDENT();
888     json_print_item_str(wctx, key, value);
889 }
890
891 static void json_print_int(WriterContext *wctx, const char *key, long long int value)
892 {
893     JSONContext *json = wctx->priv;
894     AVBPrint buf;
895
896     if (wctx->nb_item) printf("%s", json->item_sep);
897     if (!json->compact)
898         JSON_INDENT();
899
900     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
901     printf("\"%s\": %lld", json_escape_str(&buf, key, wctx), value);
902     av_bprint_finalize(&buf, NULL);
903 }
904
905 static void json_show_tags(WriterContext *wctx, AVDictionary *dict)
906 {
907     JSONContext *json = wctx->priv;
908     AVDictionaryEntry *tag = NULL;
909     int is_first = 1;
910     if (!dict)
911         return;
912     printf("%s", json->item_sep);
913     if (!json->compact)
914         JSON_INDENT();
915     printf("\"tags\": {%s", json->item_start_end);
916     json->indent_level++;
917     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
918         if (is_first) is_first = 0;
919         else          printf("%s", json->item_sep);
920         if (!json->compact)
921             JSON_INDENT();
922         json_print_item_str(wctx, tag->key, tag->value);
923     }
924     json->indent_level--;
925     printf("%s", json->item_start_end);
926     if (!json->compact)
927         JSON_INDENT();
928     printf("}");
929 }
930
931 static const Writer json_writer = {
932     .name                 = "json",
933     .priv_size            = sizeof(JSONContext),
934     .init                 = json_init,
935     .print_header         = json_print_header,
936     .print_footer         = json_print_footer,
937     .print_chapter_header = json_print_chapter_header,
938     .print_chapter_footer = json_print_chapter_footer,
939     .print_section_header = json_print_section_header,
940     .print_section_footer = json_print_section_footer,
941     .print_integer        = json_print_int,
942     .print_string         = json_print_str,
943     .show_tags            = json_show_tags,
944     .flags = WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
945 };
946
947 /* XML output */
948
949 typedef struct {
950     const AVClass *class;
951     int within_tag;
952     int multiple_entries; ///< tells if the given chapter requires multiple entries
953     int indent_level;
954     int fully_qualified;
955     int xsd_strict;
956 } XMLContext;
957
958 #undef OFFSET
959 #define OFFSET(x) offsetof(XMLContext, x)
960
961 static const AVOption xml_options[] = {
962     {"fully_qualified", "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_INT, {.dbl=0},  0, 1 },
963     {"q",               "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_INT, {.dbl=0},  0, 1 },
964     {"xsd_strict",      "ensure that the output is XSD compliant",         OFFSET(xsd_strict),      AV_OPT_TYPE_INT, {.dbl=0},  0, 1 },
965     {"x",               "ensure that the output is XSD compliant",         OFFSET(xsd_strict),      AV_OPT_TYPE_INT, {.dbl=0},  0, 1 },
966     {NULL},
967 };
968
969 static const char *xml_get_name(void *ctx)
970 {
971     return "xml";
972 }
973
974 static const AVClass xml_class = {
975     "XMLContext",
976     xml_get_name,
977     xml_options
978 };
979
980 static av_cold int xml_init(WriterContext *wctx, const char *args, void *opaque)
981 {
982     XMLContext *xml = wctx->priv;
983     int err;
984
985     xml->class = &xml_class;
986     av_opt_set_defaults(xml);
987
988     if (args &&
989         (err = (av_set_options_string(xml, args, "=", ":"))) < 0) {
990         av_log(wctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
991         return err;
992     }
993
994     if (xml->xsd_strict) {
995         xml->fully_qualified = 1;
996 #define CHECK_COMPLIANCE(opt, opt_name)                                 \
997         if (opt) {                                                      \
998             av_log(wctx, AV_LOG_ERROR,                                  \
999                    "XSD-compliant output selected but option '%s' was selected, XML output may be non-compliant.\n" \
1000                    "You need to disable such option with '-no%s'\n", opt_name, opt_name); \
1001             return AVERROR(EINVAL);                                     \
1002         }
1003         CHECK_COMPLIANCE(show_private_data, "private");
1004         CHECK_COMPLIANCE(show_value_unit,   "unit");
1005         CHECK_COMPLIANCE(use_value_prefix,  "prefix");
1006
1007         if (do_show_frames && do_show_packets) {
1008             av_log(wctx, AV_LOG_ERROR,
1009                    "Interleaved frames and packets are not allowed in XSD. "
1010                    "Select only one between the -show_frames and the -show_packets options.\n");
1011             return AVERROR(EINVAL);
1012         }
1013     }
1014
1015     return 0;
1016 }
1017
1018 static const char *xml_escape_str(AVBPrint *dst, const char *src, void *log_ctx)
1019 {
1020     const char *p;
1021
1022     for (p = src; *p; p++) {
1023         switch (*p) {
1024         case '&' : av_bprintf(dst, "%s", "&amp;");  break;
1025         case '<' : av_bprintf(dst, "%s", "&lt;");   break;
1026         case '>' : av_bprintf(dst, "%s", "&gt;");   break;
1027         case '\"': av_bprintf(dst, "%s", "&quot;"); break;
1028         case '\'': av_bprintf(dst, "%s", "&apos;"); break;
1029         default: av_bprint_chars(dst, *p, 1);
1030         }
1031     }
1032
1033     return dst->str;
1034 }
1035
1036 static void xml_print_header(WriterContext *wctx)
1037 {
1038     XMLContext *xml = wctx->priv;
1039     const char *qual = " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' "
1040         "xmlns:ffprobe='http://www.ffmpeg.org/schema/ffprobe' "
1041         "xsi:schemaLocation='http://www.ffmpeg.org/schema/ffprobe ffprobe.xsd'";
1042
1043     printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1044     printf("<%sffprobe%s>\n",
1045            xml->fully_qualified ? "ffprobe:" : "",
1046            xml->fully_qualified ? qual : "");
1047
1048     xml->indent_level++;
1049 }
1050
1051 static void xml_print_footer(WriterContext *wctx)
1052 {
1053     XMLContext *xml = wctx->priv;
1054
1055     xml->indent_level--;
1056     printf("</%sffprobe>\n", xml->fully_qualified ? "ffprobe:" : "");
1057 }
1058
1059 #define XML_INDENT() printf("%*c", xml->indent_level * 4, ' ')
1060
1061 static void xml_print_chapter_header(WriterContext *wctx, const char *chapter)
1062 {
1063     XMLContext *xml = wctx->priv;
1064
1065     if (wctx->nb_chapter)
1066         printf("\n");
1067     xml->multiple_entries = !strcmp(chapter, "packets") || !strcmp(chapter, "frames") ||
1068                             !strcmp(chapter, "packets_and_frames") ||
1069                             !strcmp(chapter, "streams") || !strcmp(chapter, "library_versions");
1070
1071     if (xml->multiple_entries) {
1072         XML_INDENT(); printf("<%s>\n", chapter);
1073         xml->indent_level++;
1074     }
1075 }
1076
1077 static void xml_print_chapter_footer(WriterContext *wctx, const char *chapter)
1078 {
1079     XMLContext *xml = wctx->priv;
1080
1081     if (xml->multiple_entries) {
1082         xml->indent_level--;
1083         XML_INDENT(); printf("</%s>\n", chapter);
1084     }
1085 }
1086
1087 static void xml_print_section_header(WriterContext *wctx, const char *section)
1088 {
1089     XMLContext *xml = wctx->priv;
1090
1091     XML_INDENT(); printf("<%s ", section);
1092     xml->within_tag = 1;
1093 }
1094
1095 static void xml_print_section_footer(WriterContext *wctx, const char *section)
1096 {
1097     XMLContext *xml = wctx->priv;
1098
1099     if (xml->within_tag)
1100         printf("/>\n");
1101     else {
1102         XML_INDENT(); printf("</%s>\n", section);
1103     }
1104 }
1105
1106 static void xml_print_str(WriterContext *wctx, const char *key, const char *value)
1107 {
1108     AVBPrint buf;
1109
1110     if (wctx->nb_item)
1111         printf(" ");
1112     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
1113     printf("%s=\"%s\"", key, xml_escape_str(&buf, value, wctx));
1114     av_bprint_finalize(&buf, NULL);
1115 }
1116
1117 static void xml_print_int(WriterContext *wctx, const char *key, long long int value)
1118 {
1119     if (wctx->nb_item)
1120         printf(" ");
1121     printf("%s=\"%lld\"", key, value);
1122 }
1123
1124 static void xml_show_tags(WriterContext *wctx, AVDictionary *dict)
1125 {
1126     XMLContext *xml = wctx->priv;
1127     AVDictionaryEntry *tag = NULL;
1128     int is_first = 1;
1129     AVBPrint buf;
1130
1131     xml->indent_level++;
1132     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
1133         if (is_first) {
1134             /* close section tag */
1135             printf(">\n");
1136             xml->within_tag = 0;
1137             is_first = 0;
1138         }
1139         XML_INDENT();
1140
1141         av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
1142         printf("<tag key=\"%s\"", xml_escape_str(&buf, tag->key, wctx));
1143         av_bprint_finalize(&buf, NULL);
1144
1145         av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
1146         printf(" value=\"%s\"/>\n", xml_escape_str(&buf, tag->value, wctx));
1147         av_bprint_finalize(&buf, NULL);
1148     }
1149     xml->indent_level--;
1150 }
1151
1152 static Writer xml_writer = {
1153     .name                 = "xml",
1154     .priv_size            = sizeof(XMLContext),
1155     .init                 = xml_init,
1156     .print_header         = xml_print_header,
1157     .print_footer         = xml_print_footer,
1158     .print_chapter_header = xml_print_chapter_header,
1159     .print_chapter_footer = xml_print_chapter_footer,
1160     .print_section_header = xml_print_section_header,
1161     .print_section_footer = xml_print_section_footer,
1162     .print_integer        = xml_print_int,
1163     .print_string         = xml_print_str,
1164     .show_tags            = xml_show_tags,
1165     .flags = WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
1166 };
1167
1168 static void writer_register_all(void)
1169 {
1170     static int initialized;
1171
1172     if (initialized)
1173         return;
1174     initialized = 1;
1175
1176     writer_register(&default_writer);
1177     writer_register(&compact_writer);
1178     writer_register(&csv_writer);
1179     writer_register(&json_writer);
1180     writer_register(&xml_writer);
1181 }
1182
1183 #define print_fmt(k, f, ...) do {              \
1184     av_bprint_clear(&pbuf);                    \
1185     av_bprintf(&pbuf, f, __VA_ARGS__);         \
1186     writer_print_string(w, k, pbuf.str, 0);    \
1187 } while (0)
1188
1189 #define print_int(k, v)         writer_print_integer(w, k, v)
1190 #define print_str(k, v)         writer_print_string(w, k, v, 0)
1191 #define print_str_opt(k, v)     writer_print_string(w, k, v, 1)
1192 #define print_time(k, v, tb)    writer_print_time(w, k, v, tb)
1193 #define print_ts(k, v)          writer_print_ts(w, k, v)
1194 #define print_val(k, v, u)      writer_print_string(w, k, \
1195     value_string(val_str, sizeof(val_str), (struct unit_value){.val.i = v, .unit=u}), 0)
1196 #define print_section_header(s) writer_print_section_header(w, s)
1197 #define print_section_footer(s) writer_print_section_footer(w, s)
1198 #define show_tags(metadata)     writer_show_tags(w, metadata)
1199
1200 static void show_packet(WriterContext *w, AVFormatContext *fmt_ctx, AVPacket *pkt, int packet_idx)
1201 {
1202     char val_str[128];
1203     AVStream *st = fmt_ctx->streams[pkt->stream_index];
1204     AVBPrint pbuf;
1205     const char *s;
1206
1207     av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
1208
1209     print_section_header("packet");
1210     s = av_get_media_type_string(st->codec->codec_type);
1211     if (s) print_str    ("codec_type", s);
1212     else   print_str_opt("codec_type", "unknown");
1213     print_int("stream_index",     pkt->stream_index);
1214     print_ts  ("pts",             pkt->pts);
1215     print_time("pts_time",        pkt->pts, &st->time_base);
1216     print_ts  ("dts",             pkt->dts);
1217     print_time("dts_time",        pkt->dts, &st->time_base);
1218     print_ts  ("duration",        pkt->duration);
1219     print_time("duration_time",   pkt->duration, &st->time_base);
1220     print_val("size",             pkt->size, unit_byte_str);
1221     if (pkt->pos != -1) print_fmt    ("pos", "%"PRId64, pkt->pos);
1222     else                print_str_opt("pos", "N/A");
1223     print_fmt("flags", "%c",      pkt->flags & AV_PKT_FLAG_KEY ? 'K' : '_');
1224     print_section_footer("packet");
1225
1226     av_bprint_finalize(&pbuf, NULL);
1227     fflush(stdout);
1228 }
1229
1230 static void show_frame(WriterContext *w, AVFrame *frame, AVStream *stream)
1231 {
1232     AVBPrint pbuf;
1233     const char *s;
1234
1235     av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
1236
1237     print_section_header("frame");
1238
1239     s = av_get_media_type_string(stream->codec->codec_type);
1240     if (s) print_str    ("media_type", s);
1241     else   print_str_opt("media_type", "unknown");
1242     print_int("key_frame",              frame->key_frame);
1243     print_ts  ("pkt_pts",               frame->pkt_pts);
1244     print_time("pkt_pts_time",          frame->pkt_pts, &stream->time_base);
1245     print_ts  ("pkt_dts",               frame->pkt_dts);
1246     print_time("pkt_dts_time",          frame->pkt_dts, &stream->time_base);
1247     if (frame->pkt_pos != -1) print_fmt    ("pkt_pos", "%"PRId64, frame->pkt_pos);
1248     else                      print_str_opt("pkt_pos", "N/A");
1249
1250     switch (stream->codec->codec_type) {
1251     case AVMEDIA_TYPE_VIDEO:
1252         print_int("width",                  frame->width);
1253         print_int("height",                 frame->height);
1254         s = av_get_pix_fmt_name(frame->format);
1255         if (s) print_str    ("pix_fmt", s);
1256         else   print_str_opt("pix_fmt", "unknown");
1257         if (frame->sample_aspect_ratio.num) {
1258             print_fmt("sample_aspect_ratio", "%d:%d",
1259                       frame->sample_aspect_ratio.num,
1260                       frame->sample_aspect_ratio.den);
1261         } else {
1262             print_str_opt("sample_aspect_ratio", "N/A");
1263         }
1264         print_fmt("pict_type",              "%c", av_get_picture_type_char(frame->pict_type));
1265         print_int("coded_picture_number",   frame->coded_picture_number);
1266         print_int("display_picture_number", frame->display_picture_number);
1267         print_int("interlaced_frame",       frame->interlaced_frame);
1268         print_int("top_field_first",        frame->top_field_first);
1269         print_int("repeat_pict",            frame->repeat_pict);
1270         print_int("reference",              frame->reference);
1271         break;
1272
1273     case AVMEDIA_TYPE_AUDIO:
1274         s = av_get_sample_fmt_name(frame->format);
1275         if (s) print_str    ("sample_fmt", s);
1276         else   print_str_opt("sample_fmt", "unknown");
1277         print_int("nb_samples",         frame->nb_samples);
1278         break;
1279     }
1280
1281     print_section_footer("frame");
1282
1283     av_bprint_finalize(&pbuf, NULL);
1284     fflush(stdout);
1285 }
1286
1287 static av_always_inline int get_decoded_frame(AVFormatContext *fmt_ctx,
1288                                               AVFrame *frame, int *got_frame,
1289                                               AVPacket *pkt)
1290 {
1291     AVCodecContext *dec_ctx = fmt_ctx->streams[pkt->stream_index]->codec;
1292     int ret = 0;
1293
1294     *got_frame = 0;
1295     switch (dec_ctx->codec_type) {
1296     case AVMEDIA_TYPE_VIDEO:
1297         ret = avcodec_decode_video2(dec_ctx, frame, got_frame, pkt);
1298         break;
1299
1300     case AVMEDIA_TYPE_AUDIO:
1301         ret = avcodec_decode_audio4(dec_ctx, frame, got_frame, pkt);
1302         break;
1303     }
1304
1305     return ret;
1306 }
1307
1308 static void read_packets(WriterContext *w, AVFormatContext *fmt_ctx)
1309 {
1310     AVPacket pkt, pkt1;
1311     AVFrame frame;
1312     int i = 0, ret, got_frame;
1313
1314     av_init_packet(&pkt);
1315
1316     while (!av_read_frame(fmt_ctx, &pkt)) {
1317         if (do_read_packets) {
1318             if (do_show_packets)
1319                 show_packet(w, fmt_ctx, &pkt, i++);
1320             nb_streams_packets[pkt.stream_index]++;
1321         }
1322         if (do_read_frames) {
1323             pkt1 = pkt;
1324             while (pkt1.size) {
1325                 avcodec_get_frame_defaults(&frame);
1326                 ret = get_decoded_frame(fmt_ctx, &frame, &got_frame, &pkt1);
1327                 if (ret < 0 || !got_frame)
1328                     break;
1329                 if (do_show_frames)
1330                     show_frame(w, &frame, fmt_ctx->streams[pkt.stream_index]);
1331                 pkt1.data += ret;
1332                 pkt1.size -= ret;
1333                 nb_streams_frames[pkt.stream_index]++;
1334             }
1335         }
1336         av_free_packet(&pkt);
1337     }
1338     av_init_packet(&pkt);
1339     pkt.data = NULL;
1340     pkt.size = 0;
1341     //Flush remaining frames that are cached in the decoder
1342     for (i = 0; i < fmt_ctx->nb_streams; i++) {
1343         pkt.stream_index = i;
1344         while (get_decoded_frame(fmt_ctx, &frame, &got_frame, &pkt) >= 0 && got_frame) {
1345             if (do_read_frames) {
1346                 if (do_show_frames)
1347                     show_frame(w, &frame, fmt_ctx->streams[pkt.stream_index]);
1348                 nb_streams_frames[pkt.stream_index]++;
1349             }
1350         }
1351     }
1352 }
1353
1354 static void show_stream(WriterContext *w, AVFormatContext *fmt_ctx, int stream_idx)
1355 {
1356     AVStream *stream = fmt_ctx->streams[stream_idx];
1357     AVCodecContext *dec_ctx;
1358     AVCodec *dec;
1359     char val_str[128];
1360     const char *s;
1361     AVRational display_aspect_ratio;
1362     AVBPrint pbuf;
1363
1364     av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
1365
1366     print_section_header("stream");
1367
1368     print_int("index", stream->index);
1369
1370     if ((dec_ctx = stream->codec)) {
1371         if ((dec = dec_ctx->codec)) {
1372             print_str("codec_name",      dec->name);
1373             print_str("codec_long_name", dec->long_name);
1374         } else {
1375             print_str_opt("codec_name",      "unknown");
1376             print_str_opt("codec_long_name", "unknown");
1377         }
1378
1379         s = av_get_media_type_string(dec_ctx->codec_type);
1380         if (s) print_str    ("codec_type", s);
1381         else   print_str_opt("codec_type", "unknown");
1382         print_fmt("codec_time_base", "%d/%d", dec_ctx->time_base.num, dec_ctx->time_base.den);
1383
1384         /* print AVI/FourCC tag */
1385         av_get_codec_tag_string(val_str, sizeof(val_str), dec_ctx->codec_tag);
1386         print_str("codec_tag_string",    val_str);
1387         print_fmt("codec_tag", "0x%04x", dec_ctx->codec_tag);
1388
1389         switch (dec_ctx->codec_type) {
1390         case AVMEDIA_TYPE_VIDEO:
1391             print_int("width",        dec_ctx->width);
1392             print_int("height",       dec_ctx->height);
1393             print_int("has_b_frames", dec_ctx->has_b_frames);
1394             if (dec_ctx->sample_aspect_ratio.num) {
1395                 print_fmt("sample_aspect_ratio", "%d:%d",
1396                           dec_ctx->sample_aspect_ratio.num,
1397                           dec_ctx->sample_aspect_ratio.den);
1398                 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
1399                           dec_ctx->width  * dec_ctx->sample_aspect_ratio.num,
1400                           dec_ctx->height * dec_ctx->sample_aspect_ratio.den,
1401                           1024*1024);
1402                 print_fmt("display_aspect_ratio", "%d:%d",
1403                           display_aspect_ratio.num,
1404                           display_aspect_ratio.den);
1405             } else {
1406                 print_str_opt("sample_aspect_ratio", "N/A");
1407                 print_str_opt("display_aspect_ratio", "N/A");
1408             }
1409             s = av_get_pix_fmt_name(dec_ctx->pix_fmt);
1410             if (s) print_str    ("pix_fmt", s);
1411             else   print_str_opt("pix_fmt", "unknown");
1412             print_int("level",   dec_ctx->level);
1413             if (dec_ctx->timecode_frame_start >= 0) {
1414                 char tcbuf[AV_TIMECODE_STR_SIZE];
1415                 av_timecode_make_mpeg_tc_string(tcbuf, dec_ctx->timecode_frame_start);
1416                 print_str("timecode", tcbuf);
1417             } else {
1418                 print_str_opt("timecode", "N/A");
1419             }
1420             break;
1421
1422         case AVMEDIA_TYPE_AUDIO:
1423             s = av_get_sample_fmt_name(dec_ctx->sample_fmt);
1424             if (s) print_str    ("sample_fmt", s);
1425             else   print_str_opt("sample_fmt", "unknown");
1426             print_val("sample_rate",     dec_ctx->sample_rate, unit_hertz_str);
1427             print_int("channels",        dec_ctx->channels);
1428             print_int("bits_per_sample", av_get_bits_per_sample(dec_ctx->codec_id));
1429             break;
1430         }
1431     } else {
1432         print_str_opt("codec_type", "unknown");
1433     }
1434     if (dec_ctx->codec && dec_ctx->codec->priv_class && show_private_data) {
1435         const AVOption *opt = NULL;
1436         while (opt = av_opt_next(dec_ctx->priv_data,opt)) {
1437             uint8_t *str;
1438             if (opt->flags) continue;
1439             if (av_opt_get(dec_ctx->priv_data, opt->name, 0, &str) >= 0) {
1440                 print_str(opt->name, str);
1441                 av_free(str);
1442             }
1443         }
1444     }
1445
1446     if (fmt_ctx->iformat->flags & AVFMT_SHOW_IDS) print_fmt    ("id", "0x%x", stream->id);
1447     else                                          print_str_opt("id", "N/A");
1448     print_fmt("r_frame_rate",   "%d/%d", stream->r_frame_rate.num,   stream->r_frame_rate.den);
1449     print_fmt("avg_frame_rate", "%d/%d", stream->avg_frame_rate.num, stream->avg_frame_rate.den);
1450     print_fmt("time_base",      "%d/%d", stream->time_base.num,      stream->time_base.den);
1451     print_time("start_time",    stream->start_time, &stream->time_base);
1452     print_time("duration",      stream->duration,   &stream->time_base);
1453     if (dec_ctx->bit_rate > 0) print_val    ("bit_rate", dec_ctx->bit_rate, unit_bit_per_second_str);
1454     else                       print_str_opt("bit_rate", "N/A");
1455     if (stream->nb_frames) print_fmt    ("nb_frames", "%"PRId64, stream->nb_frames);
1456     else                   print_str_opt("nb_frames", "N/A");
1457     if (nb_streams_frames[stream_idx])  print_fmt    ("nb_read_frames", "%"PRIu64, nb_streams_frames[stream_idx]);
1458     else                                print_str_opt("nb_read_frames", "N/A");
1459     if (nb_streams_packets[stream_idx]) print_fmt    ("nb_read_packets", "%"PRIu64, nb_streams_packets[stream_idx]);
1460     else                                print_str_opt("nb_read_packets", "N/A");
1461     show_tags(stream->metadata);
1462
1463     print_section_footer("stream");
1464     av_bprint_finalize(&pbuf, NULL);
1465     fflush(stdout);
1466 }
1467
1468 static void show_streams(WriterContext *w, AVFormatContext *fmt_ctx)
1469 {
1470     int i;
1471     for (i = 0; i < fmt_ctx->nb_streams; i++)
1472         show_stream(w, fmt_ctx, i);
1473 }
1474
1475 static void show_format(WriterContext *w, AVFormatContext *fmt_ctx)
1476 {
1477     char val_str[128];
1478     int64_t size = fmt_ctx->pb ? avio_size(fmt_ctx->pb) : -1;
1479
1480     print_section_header("format");
1481     print_str("filename",         fmt_ctx->filename);
1482     print_int("nb_streams",       fmt_ctx->nb_streams);
1483     print_str("format_name",      fmt_ctx->iformat->name);
1484     print_str("format_long_name", fmt_ctx->iformat->long_name);
1485     print_time("start_time",      fmt_ctx->start_time, &AV_TIME_BASE_Q);
1486     print_time("duration",        fmt_ctx->duration,   &AV_TIME_BASE_Q);
1487     if (size >= 0) print_val    ("size", size, unit_byte_str);
1488     else           print_str_opt("size", "N/A");
1489     if (fmt_ctx->bit_rate > 0) print_val    ("bit_rate", fmt_ctx->bit_rate, unit_bit_per_second_str);
1490     else                       print_str_opt("bit_rate", "N/A");
1491     show_tags(fmt_ctx->metadata);
1492     print_section_footer("format");
1493     fflush(stdout);
1494 }
1495
1496 static void show_error(WriterContext *w, int err)
1497 {
1498     char errbuf[128];
1499     const char *errbuf_ptr = errbuf;
1500
1501     if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
1502         errbuf_ptr = strerror(AVUNERROR(err));
1503
1504     writer_print_chapter_header(w, "error");
1505     print_section_header("error");
1506     print_int("code", err);
1507     print_str("string", errbuf_ptr);
1508     print_section_footer("error");
1509     writer_print_chapter_footer(w, "error");
1510 }
1511
1512 static int open_input_file(AVFormatContext **fmt_ctx_ptr, const char *filename)
1513 {
1514     int err, i;
1515     AVFormatContext *fmt_ctx = NULL;
1516     AVDictionaryEntry *t;
1517
1518     if ((err = avformat_open_input(&fmt_ctx, filename,
1519                                    iformat, &format_opts)) < 0) {
1520         print_error(filename, err);
1521         return err;
1522     }
1523     if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
1524         av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
1525         return AVERROR_OPTION_NOT_FOUND;
1526     }
1527
1528
1529     /* fill the streams in the format context */
1530     if ((err = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
1531         print_error(filename, err);
1532         return err;
1533     }
1534
1535     av_dump_format(fmt_ctx, 0, filename, 0);
1536
1537     /* bind a decoder to each input stream */
1538     for (i = 0; i < fmt_ctx->nb_streams; i++) {
1539         AVStream *stream = fmt_ctx->streams[i];
1540         AVCodec *codec;
1541
1542         if (!(codec = avcodec_find_decoder(stream->codec->codec_id))) {
1543             av_log(NULL, AV_LOG_ERROR,
1544                     "Unsupported codec with id %d for input stream %d\n",
1545                     stream->codec->codec_id, stream->index);
1546         } else if (avcodec_open2(stream->codec, codec, NULL) < 0) {
1547             av_log(NULL, AV_LOG_ERROR, "Error while opening codec for input stream %d\n",
1548                    stream->index);
1549         }
1550     }
1551
1552     *fmt_ctx_ptr = fmt_ctx;
1553     return 0;
1554 }
1555
1556 static void close_input_file(AVFormatContext **ctx_ptr)
1557 {
1558     int i;
1559     AVFormatContext *fmt_ctx = *ctx_ptr;
1560
1561     /* close decoder for each stream */
1562     for (i = 0; i < fmt_ctx->nb_streams; i++)
1563         if (fmt_ctx->streams[i]->codec->codec_id != CODEC_ID_NONE)
1564             avcodec_close(fmt_ctx->streams[i]->codec);
1565
1566     avformat_close_input(ctx_ptr);
1567 }
1568
1569 #define PRINT_CHAPTER(name) do {                                        \
1570     if (do_show_ ## name) {                                             \
1571         writer_print_chapter_header(wctx, #name);                       \
1572         show_ ## name (wctx, fmt_ctx);                                  \
1573         writer_print_chapter_footer(wctx, #name);                       \
1574     }                                                                   \
1575 } while (0)
1576
1577 static int probe_file(WriterContext *wctx, const char *filename)
1578 {
1579     AVFormatContext *fmt_ctx;
1580     int ret;
1581
1582     do_read_frames = do_show_frames || do_count_frames;
1583     do_read_packets = do_show_packets || do_count_packets;
1584
1585     ret = open_input_file(&fmt_ctx, filename);
1586     if (ret >= 0) {
1587         nb_streams_frames  = av_calloc(fmt_ctx->nb_streams, sizeof(*nb_streams_frames));
1588         nb_streams_packets = av_calloc(fmt_ctx->nb_streams, sizeof(*nb_streams_packets));
1589         if (do_read_frames || do_read_packets) {
1590             const char *chapter;
1591             if (do_show_frames && do_show_packets &&
1592                 wctx->writer->flags & WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER)
1593                 chapter = "packets_and_frames";
1594             else if (do_show_packets && !do_show_frames)
1595                 chapter = "packets";
1596             else // (!do_show_packets && do_show_frames)
1597                 chapter = "frames";
1598             if (do_show_frames || do_show_packets)
1599                 writer_print_chapter_header(wctx, chapter);
1600             read_packets(wctx, fmt_ctx);
1601             if (do_show_frames || do_show_packets)
1602                 writer_print_chapter_footer(wctx, chapter);
1603         }
1604         PRINT_CHAPTER(streams);
1605         PRINT_CHAPTER(format);
1606         close_input_file(&fmt_ctx);
1607         av_freep(&nb_streams_frames);
1608         av_freep(&nb_streams_packets);
1609     }
1610     return ret;
1611 }
1612
1613 static void show_usage(void)
1614 {
1615     av_log(NULL, AV_LOG_INFO, "Simple multimedia streams analyzer\n");
1616     av_log(NULL, AV_LOG_INFO, "usage: %s [OPTIONS] [INPUT_FILE]\n", program_name);
1617     av_log(NULL, AV_LOG_INFO, "\n");
1618 }
1619
1620 static void ffprobe_show_program_version(WriterContext *w)
1621 {
1622     AVBPrint pbuf;
1623     av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
1624
1625     writer_print_chapter_header(w, "program_version");
1626     print_section_header("program_version");
1627     print_str("version", FFMPEG_VERSION);
1628     print_fmt("copyright", "Copyright (c) %d-%d the FFmpeg developers",
1629               program_birth_year, this_year);
1630     print_str("build_date", __DATE__);
1631     print_str("build_time", __TIME__);
1632     print_str("compiler_type", CC_TYPE);
1633     print_str("compiler_version", CC_VERSION);
1634     print_str("configuration", FFMPEG_CONFIGURATION);
1635     print_section_footer("program_version");
1636     writer_print_chapter_footer(w, "program_version");
1637
1638     av_bprint_finalize(&pbuf, NULL);
1639 }
1640
1641 #define SHOW_LIB_VERSION(libname, LIBNAME)                              \
1642     do {                                                                \
1643         if (CONFIG_##LIBNAME) {                                         \
1644             unsigned int version = libname##_version();                 \
1645             print_section_header("library_version");                    \
1646             print_str("name",    "lib" #libname);                       \
1647             print_int("major",   LIB##LIBNAME##_VERSION_MAJOR);         \
1648             print_int("minor",   LIB##LIBNAME##_VERSION_MINOR);         \
1649             print_int("micro",   LIB##LIBNAME##_VERSION_MICRO);         \
1650             print_int("version", version);                              \
1651             print_section_footer("library_version");                    \
1652         }                                                               \
1653     } while (0)
1654
1655 static void ffprobe_show_library_versions(WriterContext *w)
1656 {
1657     writer_print_chapter_header(w, "library_versions");
1658     SHOW_LIB_VERSION(avutil,     AVUTIL);
1659     SHOW_LIB_VERSION(avcodec,    AVCODEC);
1660     SHOW_LIB_VERSION(avformat,   AVFORMAT);
1661     SHOW_LIB_VERSION(avdevice,   AVDEVICE);
1662     SHOW_LIB_VERSION(avfilter,   AVFILTER);
1663     SHOW_LIB_VERSION(swscale,    SWSCALE);
1664     SHOW_LIB_VERSION(swresample, SWRESAMPLE);
1665     SHOW_LIB_VERSION(postproc,   POSTPROC);
1666     writer_print_chapter_footer(w, "library_versions");
1667 }
1668
1669 static int opt_format(const char *opt, const char *arg)
1670 {
1671     iformat = av_find_input_format(arg);
1672     if (!iformat) {
1673         av_log(NULL, AV_LOG_ERROR, "Unknown input format: %s\n", arg);
1674         return AVERROR(EINVAL);
1675     }
1676     return 0;
1677 }
1678
1679 static int opt_show_format_entry(const char *opt, const char *arg)
1680 {
1681     do_show_format = 1;
1682     nb_fmt_entries_to_show++;
1683     av_dict_set(&fmt_entries_to_show, arg, "", 0);
1684     return 0;
1685 }
1686
1687 static void opt_input_file(void *optctx, const char *arg)
1688 {
1689     if (input_filename) {
1690         av_log(NULL, AV_LOG_ERROR,
1691                 "Argument '%s' provided as input filename, but '%s' was already specified.\n",
1692                 arg, input_filename);
1693         exit(1);
1694     }
1695     if (!strcmp(arg, "-"))
1696         arg = "pipe:";
1697     input_filename = arg;
1698 }
1699
1700 static int opt_help(const char *opt, const char *arg)
1701 {
1702     av_log_set_callback(log_callback_help);
1703     show_usage();
1704     show_help_options(options, "Main options:\n", 0, 0);
1705     printf("\n");
1706
1707     show_help_children(avformat_get_class(), AV_OPT_FLAG_DECODING_PARAM);
1708
1709     return 0;
1710 }
1711
1712 static int opt_pretty(const char *opt, const char *arg)
1713 {
1714     show_value_unit              = 1;
1715     use_value_prefix             = 1;
1716     use_byte_value_binary_prefix = 1;
1717     use_value_sexagesimal_format = 1;
1718     return 0;
1719 }
1720
1721 static int opt_show_versions(const char *opt, const char *arg)
1722 {
1723     do_show_program_version  = 1;
1724     do_show_library_versions = 1;
1725     return 0;
1726 }
1727
1728 static const OptionDef options[] = {
1729 #include "cmdutils_common_opts.h"
1730     { "f", HAS_ARG, {(void*)opt_format}, "force format", "format" },
1731     { "unit", OPT_BOOL, {(void*)&show_value_unit}, "show unit of the displayed values" },
1732     { "prefix", OPT_BOOL, {(void*)&use_value_prefix}, "use SI prefixes for the displayed values" },
1733     { "byte_binary_prefix", OPT_BOOL, {(void*)&use_byte_value_binary_prefix},
1734       "use binary prefixes for byte units" },
1735     { "sexagesimal", OPT_BOOL,  {(void*)&use_value_sexagesimal_format},
1736       "use sexagesimal format HOURS:MM:SS.MICROSECONDS for time units" },
1737     { "pretty", 0, {(void*)&opt_pretty},
1738       "prettify the format of displayed values, make it more human readable" },
1739     { "print_format", OPT_STRING | HAS_ARG, {(void*)&print_format},
1740       "set the output printing format (available formats are: default, compact, csv, json, xml)", "format" },
1741     { "show_error",   OPT_BOOL, {(void*)&do_show_error} ,  "show probing error" },
1742     { "show_format",  OPT_BOOL, {(void*)&do_show_format} , "show format/container info" },
1743     { "show_frames",  OPT_BOOL, {(void*)&do_show_frames} , "show frames info" },
1744     { "show_format_entry", HAS_ARG, {(void*)opt_show_format_entry},
1745       "show a particular entry from the format/container info", "entry" },
1746     { "show_packets", OPT_BOOL, {(void*)&do_show_packets}, "show packets info" },
1747     { "show_streams", OPT_BOOL, {(void*)&do_show_streams}, "show streams info" },
1748     { "count_frames", OPT_BOOL, {(void*)&do_count_frames}, "count the number of frames per stream" },
1749     { "count_packets", OPT_BOOL, {(void*)&do_count_packets}, "count the number of packets per stream" },
1750     { "show_program_version",  OPT_BOOL, {(void*)&do_show_program_version},  "show ffprobe version" },
1751     { "show_library_versions", OPT_BOOL, {(void*)&do_show_library_versions}, "show library versions" },
1752     { "show_versions",         0, {(void*)&opt_show_versions}, "show program and library versions" },
1753     { "show_private_data", OPT_BOOL, {(void*)&show_private_data}, "show private data" },
1754     { "private",           OPT_BOOL, {(void*)&show_private_data}, "same as show_private_data" },
1755     { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
1756     { "i", HAS_ARG, {(void *)opt_input_file}, "read specified file", "input_file"},
1757     { NULL, },
1758 };
1759
1760 int main(int argc, char **argv)
1761 {
1762     const Writer *w;
1763     WriterContext *wctx;
1764     char *buf;
1765     char *w_name = NULL, *w_args = NULL;
1766     int ret;
1767
1768     av_log_set_flags(AV_LOG_SKIP_REPEATED);
1769     parse_loglevel(argc, argv, options);
1770     av_register_all();
1771     avformat_network_init();
1772     init_opts();
1773 #if CONFIG_AVDEVICE
1774     avdevice_register_all();
1775 #endif
1776
1777     show_banner(argc, argv, options);
1778     parse_options(NULL, argc, argv, options, opt_input_file);
1779
1780     writer_register_all();
1781
1782     if (!print_format)
1783         print_format = av_strdup("default");
1784     w_name = av_strtok(print_format, "=", &buf);
1785     w_args = buf;
1786
1787     w = writer_get_by_name(w_name);
1788     if (!w) {
1789         av_log(NULL, AV_LOG_ERROR, "Unknown output format with name '%s'\n", w_name);
1790         ret = AVERROR(EINVAL);
1791         goto end;
1792     }
1793
1794     if ((ret = writer_open(&wctx, w, w_args, NULL)) >= 0) {
1795         writer_print_header(wctx);
1796
1797         if (do_show_program_version)
1798             ffprobe_show_program_version(wctx);
1799         if (do_show_library_versions)
1800             ffprobe_show_library_versions(wctx);
1801
1802         if (!input_filename &&
1803             ((do_show_format || do_show_streams || do_show_packets || do_show_error) ||
1804              (!do_show_program_version && !do_show_library_versions))) {
1805             show_usage();
1806             av_log(NULL, AV_LOG_ERROR, "You have to specify one input file.\n");
1807             av_log(NULL, AV_LOG_ERROR, "Use -h to get full help or, even better, run 'man %s'.\n", program_name);
1808             ret = AVERROR(EINVAL);
1809         } else if (input_filename) {
1810             ret = probe_file(wctx, input_filename);
1811             if (ret < 0 && do_show_error)
1812                 show_error(wctx, ret);
1813         }
1814
1815         writer_print_footer(wctx);
1816         writer_close(&wctx);
1817     }
1818
1819 end:
1820     av_freep(&print_format);
1821
1822     uninit_opts();
1823     av_dict_free(&fmt_entries_to_show);
1824
1825     avformat_network_deinit();
1826
1827     return ret;
1828 }