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