]> git.sesse.net Git - ffmpeg/blob - ffprobe.c
mxfdec: remove unused last_index_duration
[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     .priv_size             = sizeof(DefaultContext),
486     .init                  = default_init,
487     .print_footer          = default_print_footer,
488     .print_chapter_header  = default_print_chapter_header,
489     .print_section_header  = default_print_section_header,
490     .print_section_footer  = default_print_section_footer,
491     .print_integer         = default_print_int,
492     .print_string          = default_print_str,
493     .show_tags             = default_show_tags,
494     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
495 };
496
497 /* Compact output */
498
499 /**
500  * Escape \n, \r, \\ and sep characters contained in s, and print the
501  * resulting string.
502  */
503 static const char *c_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
504 {
505     const char *p;
506
507     for (p = src; *p; p++) {
508         switch (*src) {
509         case '\n': av_bprintf(dst, "%s", "\\n");  break;
510         case '\r': av_bprintf(dst, "%s", "\\r");  break;
511         case '\\': av_bprintf(dst, "%s", "\\\\"); break;
512         default:
513             if (*p == sep)
514                 av_bprint_chars(dst, '\\', 1);
515             av_bprint_chars(dst, *p, 1);
516         }
517     }
518     return dst->str;
519 }
520
521 /**
522  * Quote fields containing special characters, check RFC4180.
523  */
524 static const char *csv_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
525 {
526     const char *p;
527     int quote = 0;
528
529     /* check if input needs quoting */
530     for (p = src; *p; p++)
531         if (*p == '"' || *p == sep || *p == '\n' || *p == '\r')
532             quote = 1;
533
534     if (quote)
535         av_bprint_chars(dst, '\"', 1);
536
537     for (p = src; *p; p++) {
538         if (*p == '"')
539             av_bprint_chars(dst, '\"', 1);
540         av_bprint_chars(dst, *p, 1);
541     }
542     if (quote)
543         av_bprint_chars(dst, '\"', 1);
544     return dst->str;
545 }
546
547 static const char *none_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
548 {
549     return src;
550 }
551
552 typedef struct CompactContext {
553     const AVClass *class;
554     char *item_sep_str;
555     char item_sep;
556     int nokey;
557     char *escape_mode_str;
558     const char * (*escape_str)(AVBPrint *dst, const char *src, const char sep, void *log_ctx);
559 } CompactContext;
560
561 #undef OFFSET
562 #define OFFSET(x) offsetof(CompactContext, x)
563
564 static const AVOption compact_options[]= {
565     {"item_sep", "set item separator",    OFFSET(item_sep_str),    AV_OPT_TYPE_STRING, {.str="|"},  CHAR_MIN, CHAR_MAX },
566     {"s",        "set item separator",    OFFSET(item_sep_str),    AV_OPT_TYPE_STRING, {.str="|"},  CHAR_MIN, CHAR_MAX },
567     {"nokey",    "force no key printing", OFFSET(nokey),           AV_OPT_TYPE_INT,    {.dbl=0},    0,        1        },
568     {"nk",       "force no key printing", OFFSET(nokey),           AV_OPT_TYPE_INT,    {.dbl=0},    0,        1        },
569     {"escape",   "set escape mode",       OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"},  CHAR_MIN, CHAR_MAX },
570     {"e",        "set escape mode",       OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"},  CHAR_MIN, CHAR_MAX },
571     {NULL},
572 };
573
574 static const char *compact_get_name(void *ctx)
575 {
576     return "compact";
577 }
578
579 static const AVClass compact_class = {
580     "CompactContext",
581     compact_get_name,
582     compact_options
583 };
584
585 static av_cold int compact_init(WriterContext *wctx, const char *args, void *opaque)
586 {
587     CompactContext *compact = wctx->priv;
588     int err;
589
590     compact->class = &compact_class;
591     av_opt_set_defaults(compact);
592
593     if (args &&
594         (err = (av_set_options_string(compact, args, "=", ":"))) < 0) {
595         av_log(wctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
596         return err;
597     }
598     if (strlen(compact->item_sep_str) != 1) {
599         av_log(wctx, AV_LOG_ERROR, "Item separator '%s' specified, but must contain a single character\n",
600                compact->item_sep_str);
601         return AVERROR(EINVAL);
602     }
603     compact->item_sep = compact->item_sep_str[0];
604
605     if      (!strcmp(compact->escape_mode_str, "none")) compact->escape_str = none_escape_str;
606     else if (!strcmp(compact->escape_mode_str, "c"   )) compact->escape_str = c_escape_str;
607     else if (!strcmp(compact->escape_mode_str, "csv" )) compact->escape_str = csv_escape_str;
608     else {
609         av_log(wctx, AV_LOG_ERROR, "Unknown escape mode '%s'\n", compact->escape_mode_str);
610         return AVERROR(EINVAL);
611     }
612
613     return 0;
614 }
615
616 static av_cold void compact_uninit(WriterContext *wctx)
617 {
618     CompactContext *compact = wctx->priv;
619
620     av_freep(&compact->item_sep_str);
621     av_freep(&compact->escape_mode_str);
622 }
623
624 static void compact_print_section_header(WriterContext *wctx, const char *section)
625 {
626     CompactContext *compact = wctx->priv;
627
628     printf("%s%c", section, compact->item_sep);
629 }
630
631 static void compact_print_section_footer(WriterContext *wctx, const char *section)
632 {
633     printf("\n");
634 }
635
636 static void compact_print_str(WriterContext *wctx, const char *key, const char *value)
637 {
638     CompactContext *compact = wctx->priv;
639     AVBPrint buf;
640
641     if (wctx->nb_item) printf("%c", compact->item_sep);
642     if (!compact->nokey)
643         printf("%s=", key);
644     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
645     printf("%s", compact->escape_str(&buf, value, compact->item_sep, wctx));
646     av_bprint_finalize(&buf, NULL);
647 }
648
649 static void compact_print_int(WriterContext *wctx, const char *key, long long int value)
650 {
651     CompactContext *compact = wctx->priv;
652
653     if (wctx->nb_item) printf("%c", compact->item_sep);
654     if (!compact->nokey)
655         printf("%s=", key);
656     printf("%lld", value);
657 }
658
659 static void compact_show_tags(WriterContext *wctx, AVDictionary *dict)
660 {
661     CompactContext *compact = wctx->priv;
662     AVDictionaryEntry *tag = NULL;
663     AVBPrint buf;
664
665     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
666     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
667         if (wctx->nb_item) printf("%c", compact->item_sep);
668         if (!compact->nokey) {
669             av_bprint_clear(&buf);
670             printf("tag:%s=", compact->escape_str(&buf, tag->key, compact->item_sep, wctx));
671         }
672         av_bprint_clear(&buf);
673         printf("%s", compact->escape_str(&buf, tag->value, compact->item_sep, wctx));
674     }
675     av_bprint_finalize(&buf, NULL);
676 }
677
678 static const Writer compact_writer = {
679     .name                 = "compact",
680     .priv_size            = sizeof(CompactContext),
681     .init                 = compact_init,
682     .uninit               = compact_uninit,
683     .print_section_header = compact_print_section_header,
684     .print_section_footer = compact_print_section_footer,
685     .print_integer        = compact_print_int,
686     .print_string         = compact_print_str,
687     .show_tags            = compact_show_tags,
688     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
689 };
690
691 /* CSV output */
692
693 static av_cold int csv_init(WriterContext *wctx, const char *args, void *opaque)
694 {
695     return compact_init(wctx, "item_sep=,:nokey=1:escape=csv", opaque);
696 }
697
698 static const Writer csv_writer = {
699     .name                 = "csv",
700     .priv_size            = sizeof(CompactContext),
701     .init                 = csv_init,
702     .uninit               = compact_uninit,
703     .print_section_header = compact_print_section_header,
704     .print_section_footer = compact_print_section_footer,
705     .print_integer        = compact_print_int,
706     .print_string         = compact_print_str,
707     .show_tags            = compact_show_tags,
708     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
709 };
710
711 /* JSON output */
712
713 typedef struct {
714     const AVClass *class;
715     int multiple_entries; ///< tells if the given chapter requires multiple entries
716     int print_packets_and_frames;
717     int indent_level;
718     int compact;
719     const char *item_sep, *item_start_end;
720 } JSONContext;
721
722 #undef OFFSET
723 #define OFFSET(x) offsetof(JSONContext, x)
724
725 static const AVOption json_options[]= {
726     { "compact", "enable compact output", OFFSET(compact), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
727     { "c",       "enable compact output", OFFSET(compact), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
728     { NULL }
729 };
730
731 static const char *json_get_name(void *ctx)
732 {
733     return "json";
734 }
735
736 static const AVClass json_class = {
737     "JSONContext",
738     json_get_name,
739     json_options
740 };
741
742 static av_cold int json_init(WriterContext *wctx, const char *args, void *opaque)
743 {
744     JSONContext *json = wctx->priv;
745     int err;
746
747     json->class = &json_class;
748     av_opt_set_defaults(json);
749
750     if (args &&
751         (err = (av_set_options_string(json, args, "=", ":"))) < 0) {
752         av_log(wctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
753         return err;
754     }
755
756     json->item_sep       = json->compact ? ", " : ",\n";
757     json->item_start_end = json->compact ? " "  : "\n";
758
759     return 0;
760 }
761
762 static const char *json_escape_str(AVBPrint *dst, const char *src, void *log_ctx)
763 {
764     static const char json_escape[] = {'"', '\\', '\b', '\f', '\n', '\r', '\t', 0};
765     static const char json_subst[]  = {'"', '\\',  'b',  'f',  'n',  'r',  't', 0};
766     const char *p;
767
768     for (p = src; *p; p++) {
769         char *s = strchr(json_escape, *p);
770         if (s) {
771             av_bprint_chars(dst, '\\', 1);
772             av_bprint_chars(dst, json_subst[s - json_escape], 1);
773         } else if ((unsigned char)*p < 32) {
774             av_bprintf(dst, "\\u00%02x", *p & 0xff);
775         } else {
776             av_bprint_chars(dst, *p, 1);
777         }
778     }
779     return dst->str;
780 }
781
782 static void json_print_header(WriterContext *wctx)
783 {
784     JSONContext *json = wctx->priv;
785     printf("{");
786     json->indent_level++;
787 }
788
789 static void json_print_footer(WriterContext *wctx)
790 {
791     JSONContext *json = wctx->priv;
792     json->indent_level--;
793     printf("\n}\n");
794 }
795
796 #define JSON_INDENT() printf("%*c", json->indent_level * 4, ' ')
797
798 static void json_print_chapter_header(WriterContext *wctx, const char *chapter)
799 {
800     JSONContext *json = wctx->priv;
801     AVBPrint buf;
802
803     if (wctx->nb_chapter)
804         printf(",");
805     printf("\n");
806     json->multiple_entries = !strcmp(chapter, "packets") || !strcmp(chapter, "frames" ) ||
807                              !strcmp(chapter, "packets_and_frames") ||
808                              !strcmp(chapter, "streams") || !strcmp(chapter, "library_versions");
809     if (json->multiple_entries) {
810         JSON_INDENT();
811         av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
812         printf("\"%s\": [\n", json_escape_str(&buf, chapter, wctx));
813         av_bprint_finalize(&buf, NULL);
814         json->print_packets_and_frames = !strcmp(chapter, "packets_and_frames");
815         json->indent_level++;
816     }
817 }
818
819 static void json_print_chapter_footer(WriterContext *wctx, const char *chapter)
820 {
821     JSONContext *json = wctx->priv;
822
823     if (json->multiple_entries) {
824         printf("\n");
825         json->indent_level--;
826         JSON_INDENT();
827         printf("]");
828     }
829 }
830
831 static void json_print_section_header(WriterContext *wctx, const char *section)
832 {
833     JSONContext *json = wctx->priv;
834
835     if (wctx->nb_section)
836         printf(",\n");
837     JSON_INDENT();
838     if (!json->multiple_entries)
839         printf("\"%s\": ", section);
840     printf("{%s", json->item_start_end);
841     json->indent_level++;
842     /* this is required so the parser can distinguish between packets and frames */
843     if (json->print_packets_and_frames) {
844         if (!json->compact)
845             JSON_INDENT();
846         printf("\"type\": \"%s\"%s", section, json->item_sep);
847     }
848 }
849
850 static void json_print_section_footer(WriterContext *wctx, const char *section)
851 {
852     JSONContext *json = wctx->priv;
853
854     printf("%s", json->item_start_end);
855     json->indent_level--;
856     if (!json->compact)
857         JSON_INDENT();
858     printf("}");
859 }
860
861 static inline void json_print_item_str(WriterContext *wctx,
862                                        const char *key, const char *value)
863 {
864     AVBPrint buf;
865
866     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
867     printf("\"%s\":", json_escape_str(&buf, key,   wctx));
868     av_bprint_clear(&buf);
869     printf(" \"%s\"", json_escape_str(&buf, value, wctx));
870     av_bprint_finalize(&buf, NULL);
871 }
872
873 static void json_print_str(WriterContext *wctx, const char *key, const char *value)
874 {
875     JSONContext *json = wctx->priv;
876
877     if (wctx->nb_item) printf("%s", json->item_sep);
878     if (!json->compact)
879         JSON_INDENT();
880     json_print_item_str(wctx, key, value);
881 }
882
883 static void json_print_int(WriterContext *wctx, const char *key, long long int value)
884 {
885     JSONContext *json = wctx->priv;
886     AVBPrint buf;
887
888     if (wctx->nb_item) printf("%s", json->item_sep);
889     if (!json->compact)
890         JSON_INDENT();
891
892     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
893     printf("\"%s\": %lld", json_escape_str(&buf, key, wctx), value);
894     av_bprint_finalize(&buf, NULL);
895 }
896
897 static void json_show_tags(WriterContext *wctx, AVDictionary *dict)
898 {
899     JSONContext *json = wctx->priv;
900     AVDictionaryEntry *tag = NULL;
901     int is_first = 1;
902     if (!dict)
903         return;
904     printf("%s", json->item_sep);
905     if (!json->compact)
906         JSON_INDENT();
907     printf("\"tags\": {%s", json->item_start_end);
908     json->indent_level++;
909     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
910         if (is_first) is_first = 0;
911         else          printf("%s", json->item_sep);
912         if (!json->compact)
913             JSON_INDENT();
914         json_print_item_str(wctx, tag->key, tag->value);
915     }
916     json->indent_level--;
917     printf("%s", json->item_start_end);
918     if (!json->compact)
919         JSON_INDENT();
920     printf("}");
921 }
922
923 static const Writer json_writer = {
924     .name                 = "json",
925     .priv_size            = sizeof(JSONContext),
926     .init                 = json_init,
927     .print_header         = json_print_header,
928     .print_footer         = json_print_footer,
929     .print_chapter_header = json_print_chapter_header,
930     .print_chapter_footer = json_print_chapter_footer,
931     .print_section_header = json_print_section_header,
932     .print_section_footer = json_print_section_footer,
933     .print_integer        = json_print_int,
934     .print_string         = json_print_str,
935     .show_tags            = json_show_tags,
936     .flags = WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
937 };
938
939 /* XML output */
940
941 typedef struct {
942     const AVClass *class;
943     int within_tag;
944     int multiple_entries; ///< tells if the given chapter requires multiple entries
945     int indent_level;
946     int fully_qualified;
947     int xsd_strict;
948 } XMLContext;
949
950 #undef OFFSET
951 #define OFFSET(x) offsetof(XMLContext, x)
952
953 static const AVOption xml_options[] = {
954     {"fully_qualified", "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_INT, {.dbl=0},  0, 1 },
955     {"q",               "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_INT, {.dbl=0},  0, 1 },
956     {"xsd_strict",      "ensure that the output is XSD compliant",         OFFSET(xsd_strict),      AV_OPT_TYPE_INT, {.dbl=0},  0, 1 },
957     {"x",               "ensure that the output is XSD compliant",         OFFSET(xsd_strict),      AV_OPT_TYPE_INT, {.dbl=0},  0, 1 },
958     {NULL},
959 };
960
961 static const char *xml_get_name(void *ctx)
962 {
963     return "xml";
964 }
965
966 static const AVClass xml_class = {
967     "XMLContext",
968     xml_get_name,
969     xml_options
970 };
971
972 static av_cold int xml_init(WriterContext *wctx, const char *args, void *opaque)
973 {
974     XMLContext *xml = wctx->priv;
975     int err;
976
977     xml->class = &xml_class;
978     av_opt_set_defaults(xml);
979
980     if (args &&
981         (err = (av_set_options_string(xml, args, "=", ":"))) < 0) {
982         av_log(wctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
983         return err;
984     }
985
986     if (xml->xsd_strict) {
987         xml->fully_qualified = 1;
988 #define CHECK_COMPLIANCE(opt, opt_name)                                 \
989         if (opt) {                                                      \
990             av_log(wctx, AV_LOG_ERROR,                                  \
991                    "XSD-compliant output selected but option '%s' was selected, XML output may be non-compliant.\n" \
992                    "You need to disable such option with '-no%s'\n", opt_name, opt_name); \
993             return AVERROR(EINVAL);                                     \
994         }
995         CHECK_COMPLIANCE(show_private_data, "private");
996         CHECK_COMPLIANCE(show_value_unit,   "unit");
997         CHECK_COMPLIANCE(use_value_prefix,  "prefix");
998
999         if (do_show_frames && do_show_packets) {
1000             av_log(wctx, AV_LOG_ERROR,
1001                    "Interleaved frames and packets are not allowed in XSD. "
1002                    "Select only one between the -show_frames and the -show_packets options.\n");
1003             return AVERROR(EINVAL);
1004         }
1005     }
1006
1007     return 0;
1008 }
1009
1010 static const char *xml_escape_str(AVBPrint *dst, const char *src, void *log_ctx)
1011 {
1012     const char *p;
1013
1014     for (p = src; *p; p++) {
1015         switch (*p) {
1016         case '&' : av_bprintf(dst, "%s", "&amp;");  break;
1017         case '<' : av_bprintf(dst, "%s", "&lt;");   break;
1018         case '>' : av_bprintf(dst, "%s", "&gt;");   break;
1019         case '\"': av_bprintf(dst, "%s", "&quot;"); break;
1020         case '\'': av_bprintf(dst, "%s", "&apos;"); break;
1021         default: av_bprint_chars(dst, *p, 1);
1022         }
1023     }
1024
1025     return dst->str;
1026 }
1027
1028 static void xml_print_header(WriterContext *wctx)
1029 {
1030     XMLContext *xml = wctx->priv;
1031     const char *qual = " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' "
1032         "xmlns:ffprobe='http://www.ffmpeg.org/schema/ffprobe' "
1033         "xsi:schemaLocation='http://www.ffmpeg.org/schema/ffprobe ffprobe.xsd'";
1034
1035     printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1036     printf("<%sffprobe%s>\n",
1037            xml->fully_qualified ? "ffprobe:" : "",
1038            xml->fully_qualified ? qual : "");
1039
1040     xml->indent_level++;
1041 }
1042
1043 static void xml_print_footer(WriterContext *wctx)
1044 {
1045     XMLContext *xml = wctx->priv;
1046
1047     xml->indent_level--;
1048     printf("</%sffprobe>\n", xml->fully_qualified ? "ffprobe:" : "");
1049 }
1050
1051 #define XML_INDENT() printf("%*c", xml->indent_level * 4, ' ')
1052
1053 static void xml_print_chapter_header(WriterContext *wctx, const char *chapter)
1054 {
1055     XMLContext *xml = wctx->priv;
1056
1057     if (wctx->nb_chapter)
1058         printf("\n");
1059     xml->multiple_entries = !strcmp(chapter, "packets") || !strcmp(chapter, "frames") ||
1060                             !strcmp(chapter, "packets_and_frames") ||
1061                             !strcmp(chapter, "streams") || !strcmp(chapter, "library_versions");
1062
1063     if (xml->multiple_entries) {
1064         XML_INDENT(); printf("<%s>\n", chapter);
1065         xml->indent_level++;
1066     }
1067 }
1068
1069 static void xml_print_chapter_footer(WriterContext *wctx, const char *chapter)
1070 {
1071     XMLContext *xml = wctx->priv;
1072
1073     if (xml->multiple_entries) {
1074         xml->indent_level--;
1075         XML_INDENT(); printf("</%s>\n", chapter);
1076     }
1077 }
1078
1079 static void xml_print_section_header(WriterContext *wctx, const char *section)
1080 {
1081     XMLContext *xml = wctx->priv;
1082
1083     XML_INDENT(); printf("<%s ", section);
1084     xml->within_tag = 1;
1085 }
1086
1087 static void xml_print_section_footer(WriterContext *wctx, const char *section)
1088 {
1089     XMLContext *xml = wctx->priv;
1090
1091     if (xml->within_tag)
1092         printf("/>\n");
1093     else {
1094         XML_INDENT(); printf("</%s>\n", section);
1095     }
1096 }
1097
1098 static void xml_print_str(WriterContext *wctx, const char *key, const char *value)
1099 {
1100     AVBPrint buf;
1101
1102     if (wctx->nb_item)
1103         printf(" ");
1104     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
1105     printf("%s=\"%s\"", key, xml_escape_str(&buf, value, wctx));
1106     av_bprint_finalize(&buf, NULL);
1107 }
1108
1109 static void xml_print_int(WriterContext *wctx, const char *key, long long int value)
1110 {
1111     if (wctx->nb_item)
1112         printf(" ");
1113     printf("%s=\"%lld\"", key, value);
1114 }
1115
1116 static void xml_show_tags(WriterContext *wctx, AVDictionary *dict)
1117 {
1118     XMLContext *xml = wctx->priv;
1119     AVDictionaryEntry *tag = NULL;
1120     int is_first = 1;
1121     AVBPrint buf;
1122
1123     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
1124     xml->indent_level++;
1125     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
1126         if (is_first) {
1127             /* close section tag */
1128             printf(">\n");
1129             xml->within_tag = 0;
1130             is_first = 0;
1131         }
1132         XML_INDENT();
1133
1134         av_bprint_clear(&buf);
1135         printf("<tag key=\"%s\"", xml_escape_str(&buf, tag->key, wctx));
1136         av_bprint_clear(&buf);
1137         printf(" value=\"%s\"/>\n", xml_escape_str(&buf, tag->value, wctx));
1138     }
1139     av_bprint_finalize(&buf, NULL);
1140     xml->indent_level--;
1141 }
1142
1143 static Writer xml_writer = {
1144     .name                 = "xml",
1145     .priv_size            = sizeof(XMLContext),
1146     .init                 = xml_init,
1147     .print_header         = xml_print_header,
1148     .print_footer         = xml_print_footer,
1149     .print_chapter_header = xml_print_chapter_header,
1150     .print_chapter_footer = xml_print_chapter_footer,
1151     .print_section_header = xml_print_section_header,
1152     .print_section_footer = xml_print_section_footer,
1153     .print_integer        = xml_print_int,
1154     .print_string         = xml_print_str,
1155     .show_tags            = xml_show_tags,
1156     .flags = WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
1157 };
1158
1159 static void writer_register_all(void)
1160 {
1161     static int initialized;
1162
1163     if (initialized)
1164         return;
1165     initialized = 1;
1166
1167     writer_register(&default_writer);
1168     writer_register(&compact_writer);
1169     writer_register(&csv_writer);
1170     writer_register(&json_writer);
1171     writer_register(&xml_writer);
1172 }
1173
1174 #define print_fmt(k, f, ...) do {              \
1175     av_bprint_clear(&pbuf);                    \
1176     av_bprintf(&pbuf, f, __VA_ARGS__);         \
1177     writer_print_string(w, k, pbuf.str, 0);    \
1178 } while (0)
1179
1180 #define print_int(k, v)         writer_print_integer(w, k, v)
1181 #define print_str(k, v)         writer_print_string(w, k, v, 0)
1182 #define print_str_opt(k, v)     writer_print_string(w, k, v, 1)
1183 #define print_time(k, v, tb)    writer_print_time(w, k, v, tb)
1184 #define print_ts(k, v)          writer_print_ts(w, k, v)
1185 #define print_val(k, v, u)      writer_print_string(w, k, \
1186     value_string(val_str, sizeof(val_str), (struct unit_value){.val.i = v, .unit=u}), 0)
1187 #define print_section_header(s) writer_print_section_header(w, s)
1188 #define print_section_footer(s) writer_print_section_footer(w, s)
1189 #define show_tags(metadata)     writer_show_tags(w, metadata)
1190
1191 static void show_packet(WriterContext *w, AVFormatContext *fmt_ctx, AVPacket *pkt, int packet_idx)
1192 {
1193     char val_str[128];
1194     AVStream *st = fmt_ctx->streams[pkt->stream_index];
1195     AVBPrint pbuf;
1196     const char *s;
1197
1198     av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
1199
1200     print_section_header("packet");
1201     s = av_get_media_type_string(st->codec->codec_type);
1202     if (s) print_str    ("codec_type", s);
1203     else   print_str_opt("codec_type", "unknown");
1204     print_int("stream_index",     pkt->stream_index);
1205     print_ts  ("pts",             pkt->pts);
1206     print_time("pts_time",        pkt->pts, &st->time_base);
1207     print_ts  ("dts",             pkt->dts);
1208     print_time("dts_time",        pkt->dts, &st->time_base);
1209     print_ts  ("duration",        pkt->duration);
1210     print_time("duration_time",   pkt->duration, &st->time_base);
1211     print_val("size",             pkt->size, unit_byte_str);
1212     if (pkt->pos != -1) print_fmt    ("pos", "%"PRId64, pkt->pos);
1213     else                print_str_opt("pos", "N/A");
1214     print_fmt("flags", "%c",      pkt->flags & AV_PKT_FLAG_KEY ? 'K' : '_');
1215     print_section_footer("packet");
1216
1217     av_bprint_finalize(&pbuf, NULL);
1218     fflush(stdout);
1219 }
1220
1221 static void show_frame(WriterContext *w, AVFrame *frame, AVStream *stream)
1222 {
1223     AVBPrint pbuf;
1224     const char *s;
1225
1226     av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
1227
1228     print_section_header("frame");
1229
1230     s = av_get_media_type_string(stream->codec->codec_type);
1231     if (s) print_str    ("media_type", s);
1232     else   print_str_opt("media_type", "unknown");
1233     print_int("key_frame",              frame->key_frame);
1234     print_ts  ("pkt_pts",               frame->pkt_pts);
1235     print_time("pkt_pts_time",          frame->pkt_pts, &stream->time_base);
1236     print_ts  ("pkt_dts",               frame->pkt_dts);
1237     print_time("pkt_dts_time",          frame->pkt_dts, &stream->time_base);
1238     if (frame->pkt_pos != -1) print_fmt    ("pkt_pos", "%"PRId64, frame->pkt_pos);
1239     else                      print_str_opt("pkt_pos", "N/A");
1240
1241     switch (stream->codec->codec_type) {
1242     case AVMEDIA_TYPE_VIDEO:
1243         print_int("width",                  frame->width);
1244         print_int("height",                 frame->height);
1245         s = av_get_pix_fmt_name(frame->format);
1246         if (s) print_str    ("pix_fmt", s);
1247         else   print_str_opt("pix_fmt", "unknown");
1248         if (frame->sample_aspect_ratio.num) {
1249             print_fmt("sample_aspect_ratio", "%d:%d",
1250                       frame->sample_aspect_ratio.num,
1251                       frame->sample_aspect_ratio.den);
1252         } else {
1253             print_str_opt("sample_aspect_ratio", "N/A");
1254         }
1255         print_fmt("pict_type",              "%c", av_get_picture_type_char(frame->pict_type));
1256         print_int("coded_picture_number",   frame->coded_picture_number);
1257         print_int("display_picture_number", frame->display_picture_number);
1258         print_int("interlaced_frame",       frame->interlaced_frame);
1259         print_int("top_field_first",        frame->top_field_first);
1260         print_int("repeat_pict",            frame->repeat_pict);
1261         print_int("reference",              frame->reference);
1262         break;
1263
1264     case AVMEDIA_TYPE_AUDIO:
1265         s = av_get_sample_fmt_name(frame->format);
1266         if (s) print_str    ("sample_fmt", s);
1267         else   print_str_opt("sample_fmt", "unknown");
1268         print_int("nb_samples",         frame->nb_samples);
1269         break;
1270     }
1271
1272     print_section_footer("frame");
1273
1274     av_bprint_finalize(&pbuf, NULL);
1275     fflush(stdout);
1276 }
1277
1278 static av_always_inline int get_decoded_frame(AVFormatContext *fmt_ctx,
1279                                               AVFrame *frame, int *got_frame,
1280                                               AVPacket *pkt)
1281 {
1282     AVCodecContext *dec_ctx = fmt_ctx->streams[pkt->stream_index]->codec;
1283     int ret = 0;
1284
1285     *got_frame = 0;
1286     switch (dec_ctx->codec_type) {
1287     case AVMEDIA_TYPE_VIDEO:
1288         ret = avcodec_decode_video2(dec_ctx, frame, got_frame, pkt);
1289         break;
1290
1291     case AVMEDIA_TYPE_AUDIO:
1292         ret = avcodec_decode_audio4(dec_ctx, frame, got_frame, pkt);
1293         break;
1294     }
1295
1296     return ret;
1297 }
1298
1299 static void read_packets(WriterContext *w, AVFormatContext *fmt_ctx)
1300 {
1301     AVPacket pkt, pkt1;
1302     AVFrame frame;
1303     int i = 0, ret, got_frame;
1304
1305     av_init_packet(&pkt);
1306
1307     while (!av_read_frame(fmt_ctx, &pkt)) {
1308         if (do_read_packets) {
1309             if (do_show_packets)
1310                 show_packet(w, fmt_ctx, &pkt, i++);
1311             nb_streams_packets[pkt.stream_index]++;
1312         }
1313         if (do_read_frames) {
1314             pkt1 = pkt;
1315             while (pkt1.size) {
1316                 avcodec_get_frame_defaults(&frame);
1317                 ret = get_decoded_frame(fmt_ctx, &frame, &got_frame, &pkt1);
1318                 if (ret < 0 || !got_frame)
1319                     break;
1320                 if (do_show_frames)
1321                     show_frame(w, &frame, fmt_ctx->streams[pkt.stream_index]);
1322                 pkt1.data += ret;
1323                 pkt1.size -= ret;
1324                 nb_streams_frames[pkt.stream_index]++;
1325             }
1326         }
1327         av_free_packet(&pkt);
1328     }
1329     av_init_packet(&pkt);
1330     pkt.data = NULL;
1331     pkt.size = 0;
1332     //Flush remaining frames that are cached in the decoder
1333     for (i = 0; i < fmt_ctx->nb_streams; i++) {
1334         pkt.stream_index = i;
1335         while (get_decoded_frame(fmt_ctx, &frame, &got_frame, &pkt) >= 0 && got_frame) {
1336             if (do_read_frames) {
1337                 if (do_show_frames)
1338                     show_frame(w, &frame, fmt_ctx->streams[pkt.stream_index]);
1339                 nb_streams_frames[pkt.stream_index]++;
1340             }
1341         }
1342     }
1343 }
1344
1345 static void show_stream(WriterContext *w, AVFormatContext *fmt_ctx, int stream_idx)
1346 {
1347     AVStream *stream = fmt_ctx->streams[stream_idx];
1348     AVCodecContext *dec_ctx;
1349     AVCodec *dec;
1350     char val_str[128];
1351     const char *s;
1352     AVRational display_aspect_ratio;
1353     AVBPrint pbuf;
1354
1355     av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
1356
1357     print_section_header("stream");
1358
1359     print_int("index", stream->index);
1360
1361     if ((dec_ctx = stream->codec)) {
1362         const char *profile = NULL;
1363         if ((dec = dec_ctx->codec)) {
1364             print_str("codec_name",      dec->name);
1365             print_str("codec_long_name", dec->long_name);
1366         } else {
1367             print_str_opt("codec_name",      "unknown");
1368             print_str_opt("codec_long_name", "unknown");
1369         }
1370
1371         if (dec && (profile = av_get_profile_name(dec, dec_ctx->profile)))
1372             print_str("profile", profile);
1373         else
1374             print_str_opt("profile", "unknown");
1375
1376         s = av_get_media_type_string(dec_ctx->codec_type);
1377         if (s) print_str    ("codec_type", s);
1378         else   print_str_opt("codec_type", "unknown");
1379         print_fmt("codec_time_base", "%d/%d", dec_ctx->time_base.num, dec_ctx->time_base.den);
1380
1381         /* print AVI/FourCC tag */
1382         av_get_codec_tag_string(val_str, sizeof(val_str), dec_ctx->codec_tag);
1383         print_str("codec_tag_string",    val_str);
1384         print_fmt("codec_tag", "0x%04x", dec_ctx->codec_tag);
1385
1386         switch (dec_ctx->codec_type) {
1387         case AVMEDIA_TYPE_VIDEO:
1388             print_int("width",        dec_ctx->width);
1389             print_int("height",       dec_ctx->height);
1390             print_int("has_b_frames", dec_ctx->has_b_frames);
1391             if (dec_ctx->sample_aspect_ratio.num) {
1392                 print_fmt("sample_aspect_ratio", "%d:%d",
1393                           dec_ctx->sample_aspect_ratio.num,
1394                           dec_ctx->sample_aspect_ratio.den);
1395                 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
1396                           dec_ctx->width  * dec_ctx->sample_aspect_ratio.num,
1397                           dec_ctx->height * dec_ctx->sample_aspect_ratio.den,
1398                           1024*1024);
1399                 print_fmt("display_aspect_ratio", "%d:%d",
1400                           display_aspect_ratio.num,
1401                           display_aspect_ratio.den);
1402             } else {
1403                 print_str_opt("sample_aspect_ratio", "N/A");
1404                 print_str_opt("display_aspect_ratio", "N/A");
1405             }
1406             s = av_get_pix_fmt_name(dec_ctx->pix_fmt);
1407             if (s) print_str    ("pix_fmt", s);
1408             else   print_str_opt("pix_fmt", "unknown");
1409             print_int("level",   dec_ctx->level);
1410             if (dec_ctx->timecode_frame_start >= 0) {
1411                 char tcbuf[AV_TIMECODE_STR_SIZE];
1412                 av_timecode_make_mpeg_tc_string(tcbuf, dec_ctx->timecode_frame_start);
1413                 print_str("timecode", tcbuf);
1414             } else {
1415                 print_str_opt("timecode", "N/A");
1416             }
1417             break;
1418
1419         case AVMEDIA_TYPE_AUDIO:
1420             s = av_get_sample_fmt_name(dec_ctx->sample_fmt);
1421             if (s) print_str    ("sample_fmt", s);
1422             else   print_str_opt("sample_fmt", "unknown");
1423             print_val("sample_rate",     dec_ctx->sample_rate, unit_hertz_str);
1424             print_int("channels",        dec_ctx->channels);
1425             print_int("bits_per_sample", av_get_bits_per_sample(dec_ctx->codec_id));
1426             break;
1427         }
1428     } else {
1429         print_str_opt("codec_type", "unknown");
1430     }
1431     if (dec_ctx->codec && dec_ctx->codec->priv_class && show_private_data) {
1432         const AVOption *opt = NULL;
1433         while (opt = av_opt_next(dec_ctx->priv_data,opt)) {
1434             uint8_t *str;
1435             if (opt->flags) continue;
1436             if (av_opt_get(dec_ctx->priv_data, opt->name, 0, &str) >= 0) {
1437                 print_str(opt->name, str);
1438                 av_free(str);
1439             }
1440         }
1441     }
1442
1443     if (fmt_ctx->iformat->flags & AVFMT_SHOW_IDS) print_fmt    ("id", "0x%x", stream->id);
1444     else                                          print_str_opt("id", "N/A");
1445     print_fmt("r_frame_rate",   "%d/%d", stream->r_frame_rate.num,   stream->r_frame_rate.den);
1446     print_fmt("avg_frame_rate", "%d/%d", stream->avg_frame_rate.num, stream->avg_frame_rate.den);
1447     print_fmt("time_base",      "%d/%d", stream->time_base.num,      stream->time_base.den);
1448     print_time("start_time",    stream->start_time, &stream->time_base);
1449     print_time("duration",      stream->duration,   &stream->time_base);
1450     if (dec_ctx->bit_rate > 0) print_val    ("bit_rate", dec_ctx->bit_rate, unit_bit_per_second_str);
1451     else                       print_str_opt("bit_rate", "N/A");
1452     if (stream->nb_frames) print_fmt    ("nb_frames", "%"PRId64, stream->nb_frames);
1453     else                   print_str_opt("nb_frames", "N/A");
1454     if (nb_streams_frames[stream_idx])  print_fmt    ("nb_read_frames", "%"PRIu64, nb_streams_frames[stream_idx]);
1455     else                                print_str_opt("nb_read_frames", "N/A");
1456     if (nb_streams_packets[stream_idx]) print_fmt    ("nb_read_packets", "%"PRIu64, nb_streams_packets[stream_idx]);
1457     else                                print_str_opt("nb_read_packets", "N/A");
1458     show_tags(stream->metadata);
1459
1460     print_section_footer("stream");
1461     av_bprint_finalize(&pbuf, NULL);
1462     fflush(stdout);
1463 }
1464
1465 static void show_streams(WriterContext *w, AVFormatContext *fmt_ctx)
1466 {
1467     int i;
1468     for (i = 0; i < fmt_ctx->nb_streams; i++)
1469         show_stream(w, fmt_ctx, i);
1470 }
1471
1472 static void show_format(WriterContext *w, AVFormatContext *fmt_ctx)
1473 {
1474     char val_str[128];
1475     int64_t size = fmt_ctx->pb ? avio_size(fmt_ctx->pb) : -1;
1476
1477     print_section_header("format");
1478     print_str("filename",         fmt_ctx->filename);
1479     print_int("nb_streams",       fmt_ctx->nb_streams);
1480     print_str("format_name",      fmt_ctx->iformat->name);
1481     print_str("format_long_name", fmt_ctx->iformat->long_name);
1482     print_time("start_time",      fmt_ctx->start_time, &AV_TIME_BASE_Q);
1483     print_time("duration",        fmt_ctx->duration,   &AV_TIME_BASE_Q);
1484     if (size >= 0) print_val    ("size", size, unit_byte_str);
1485     else           print_str_opt("size", "N/A");
1486     if (fmt_ctx->bit_rate > 0) print_val    ("bit_rate", fmt_ctx->bit_rate, unit_bit_per_second_str);
1487     else                       print_str_opt("bit_rate", "N/A");
1488     show_tags(fmt_ctx->metadata);
1489     print_section_footer("format");
1490     fflush(stdout);
1491 }
1492
1493 static void show_error(WriterContext *w, int err)
1494 {
1495     char errbuf[128];
1496     const char *errbuf_ptr = errbuf;
1497
1498     if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
1499         errbuf_ptr = strerror(AVUNERROR(err));
1500
1501     writer_print_chapter_header(w, "error");
1502     print_section_header("error");
1503     print_int("code", err);
1504     print_str("string", errbuf_ptr);
1505     print_section_footer("error");
1506     writer_print_chapter_footer(w, "error");
1507 }
1508
1509 static int open_input_file(AVFormatContext **fmt_ctx_ptr, const char *filename)
1510 {
1511     int err, i;
1512     AVFormatContext *fmt_ctx = NULL;
1513     AVDictionaryEntry *t;
1514
1515     if ((err = avformat_open_input(&fmt_ctx, filename,
1516                                    iformat, &format_opts)) < 0) {
1517         print_error(filename, err);
1518         return err;
1519     }
1520     if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
1521         av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
1522         return AVERROR_OPTION_NOT_FOUND;
1523     }
1524
1525
1526     /* fill the streams in the format context */
1527     if ((err = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
1528         print_error(filename, err);
1529         return err;
1530     }
1531
1532     av_dump_format(fmt_ctx, 0, filename, 0);
1533
1534     /* bind a decoder to each input stream */
1535     for (i = 0; i < fmt_ctx->nb_streams; i++) {
1536         AVStream *stream = fmt_ctx->streams[i];
1537         AVCodec *codec;
1538
1539         if (!(codec = avcodec_find_decoder(stream->codec->codec_id))) {
1540             av_log(NULL, AV_LOG_ERROR,
1541                     "Unsupported codec with id %d for input stream %d\n",
1542                     stream->codec->codec_id, stream->index);
1543         } else if (avcodec_open2(stream->codec, codec, NULL) < 0) {
1544             av_log(NULL, AV_LOG_ERROR, "Error while opening codec for input stream %d\n",
1545                    stream->index);
1546         }
1547     }
1548
1549     *fmt_ctx_ptr = fmt_ctx;
1550     return 0;
1551 }
1552
1553 static void close_input_file(AVFormatContext **ctx_ptr)
1554 {
1555     int i;
1556     AVFormatContext *fmt_ctx = *ctx_ptr;
1557
1558     /* close decoder for each stream */
1559     for (i = 0; i < fmt_ctx->nb_streams; i++)
1560         if (fmt_ctx->streams[i]->codec->codec_id != CODEC_ID_NONE)
1561             avcodec_close(fmt_ctx->streams[i]->codec);
1562
1563     avformat_close_input(ctx_ptr);
1564 }
1565
1566 #define PRINT_CHAPTER(name) do {                                        \
1567     if (do_show_ ## name) {                                             \
1568         writer_print_chapter_header(wctx, #name);                       \
1569         show_ ## name (wctx, fmt_ctx);                                  \
1570         writer_print_chapter_footer(wctx, #name);                       \
1571     }                                                                   \
1572 } while (0)
1573
1574 static int probe_file(WriterContext *wctx, const char *filename)
1575 {
1576     AVFormatContext *fmt_ctx;
1577     int ret;
1578
1579     do_read_frames = do_show_frames || do_count_frames;
1580     do_read_packets = do_show_packets || do_count_packets;
1581
1582     ret = open_input_file(&fmt_ctx, filename);
1583     if (ret >= 0) {
1584         nb_streams_frames  = av_calloc(fmt_ctx->nb_streams, sizeof(*nb_streams_frames));
1585         nb_streams_packets = av_calloc(fmt_ctx->nb_streams, sizeof(*nb_streams_packets));
1586         if (do_read_frames || do_read_packets) {
1587             const char *chapter;
1588             if (do_show_frames && do_show_packets &&
1589                 wctx->writer->flags & WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER)
1590                 chapter = "packets_and_frames";
1591             else if (do_show_packets && !do_show_frames)
1592                 chapter = "packets";
1593             else // (!do_show_packets && do_show_frames)
1594                 chapter = "frames";
1595             if (do_show_frames || do_show_packets)
1596                 writer_print_chapter_header(wctx, chapter);
1597             read_packets(wctx, fmt_ctx);
1598             if (do_show_frames || do_show_packets)
1599                 writer_print_chapter_footer(wctx, chapter);
1600         }
1601         PRINT_CHAPTER(streams);
1602         PRINT_CHAPTER(format);
1603         close_input_file(&fmt_ctx);
1604         av_freep(&nb_streams_frames);
1605         av_freep(&nb_streams_packets);
1606     }
1607     return ret;
1608 }
1609
1610 static void show_usage(void)
1611 {
1612     av_log(NULL, AV_LOG_INFO, "Simple multimedia streams analyzer\n");
1613     av_log(NULL, AV_LOG_INFO, "usage: %s [OPTIONS] [INPUT_FILE]\n", program_name);
1614     av_log(NULL, AV_LOG_INFO, "\n");
1615 }
1616
1617 static void ffprobe_show_program_version(WriterContext *w)
1618 {
1619     AVBPrint pbuf;
1620     av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
1621
1622     writer_print_chapter_header(w, "program_version");
1623     print_section_header("program_version");
1624     print_str("version", FFMPEG_VERSION);
1625     print_fmt("copyright", "Copyright (c) %d-%d the FFmpeg developers",
1626               program_birth_year, this_year);
1627     print_str("build_date", __DATE__);
1628     print_str("build_time", __TIME__);
1629     print_str("compiler_type", CC_TYPE);
1630     print_str("compiler_version", CC_VERSION);
1631     print_str("configuration", FFMPEG_CONFIGURATION);
1632     print_section_footer("program_version");
1633     writer_print_chapter_footer(w, "program_version");
1634
1635     av_bprint_finalize(&pbuf, NULL);
1636 }
1637
1638 #define SHOW_LIB_VERSION(libname, LIBNAME)                              \
1639     do {                                                                \
1640         if (CONFIG_##LIBNAME) {                                         \
1641             unsigned int version = libname##_version();                 \
1642             print_section_header("library_version");                    \
1643             print_str("name",    "lib" #libname);                       \
1644             print_int("major",   LIB##LIBNAME##_VERSION_MAJOR);         \
1645             print_int("minor",   LIB##LIBNAME##_VERSION_MINOR);         \
1646             print_int("micro",   LIB##LIBNAME##_VERSION_MICRO);         \
1647             print_int("version", version);                              \
1648             print_section_footer("library_version");                    \
1649         }                                                               \
1650     } while (0)
1651
1652 static void ffprobe_show_library_versions(WriterContext *w)
1653 {
1654     writer_print_chapter_header(w, "library_versions");
1655     SHOW_LIB_VERSION(avutil,     AVUTIL);
1656     SHOW_LIB_VERSION(avcodec,    AVCODEC);
1657     SHOW_LIB_VERSION(avformat,   AVFORMAT);
1658     SHOW_LIB_VERSION(avdevice,   AVDEVICE);
1659     SHOW_LIB_VERSION(avfilter,   AVFILTER);
1660     SHOW_LIB_VERSION(swscale,    SWSCALE);
1661     SHOW_LIB_VERSION(swresample, SWRESAMPLE);
1662     SHOW_LIB_VERSION(postproc,   POSTPROC);
1663     writer_print_chapter_footer(w, "library_versions");
1664 }
1665
1666 static int opt_format(const char *opt, const char *arg)
1667 {
1668     iformat = av_find_input_format(arg);
1669     if (!iformat) {
1670         av_log(NULL, AV_LOG_ERROR, "Unknown input format: %s\n", arg);
1671         return AVERROR(EINVAL);
1672     }
1673     return 0;
1674 }
1675
1676 static int opt_show_format_entry(const char *opt, const char *arg)
1677 {
1678     do_show_format = 1;
1679     av_dict_set(&fmt_entries_to_show, arg, "", 0);
1680     return 0;
1681 }
1682
1683 static void opt_input_file(void *optctx, const char *arg)
1684 {
1685     if (input_filename) {
1686         av_log(NULL, AV_LOG_ERROR,
1687                 "Argument '%s' provided as input filename, but '%s' was already specified.\n",
1688                 arg, input_filename);
1689         exit(1);
1690     }
1691     if (!strcmp(arg, "-"))
1692         arg = "pipe:";
1693     input_filename = arg;
1694 }
1695
1696 static int opt_help(const char *opt, const char *arg)
1697 {
1698     av_log_set_callback(log_callback_help);
1699     show_usage();
1700     show_help_options(options, "Main options:\n", 0, 0);
1701     printf("\n");
1702
1703     show_help_children(avformat_get_class(), AV_OPT_FLAG_DECODING_PARAM);
1704
1705     return 0;
1706 }
1707
1708 static int opt_pretty(const char *opt, const char *arg)
1709 {
1710     show_value_unit              = 1;
1711     use_value_prefix             = 1;
1712     use_byte_value_binary_prefix = 1;
1713     use_value_sexagesimal_format = 1;
1714     return 0;
1715 }
1716
1717 static int opt_show_versions(const char *opt, const char *arg)
1718 {
1719     do_show_program_version  = 1;
1720     do_show_library_versions = 1;
1721     return 0;
1722 }
1723
1724 static const OptionDef options[] = {
1725 #include "cmdutils_common_opts.h"
1726     { "f", HAS_ARG, {(void*)opt_format}, "force format", "format" },
1727     { "unit", OPT_BOOL, {(void*)&show_value_unit}, "show unit of the displayed values" },
1728     { "prefix", OPT_BOOL, {(void*)&use_value_prefix}, "use SI prefixes for the displayed values" },
1729     { "byte_binary_prefix", OPT_BOOL, {(void*)&use_byte_value_binary_prefix},
1730       "use binary prefixes for byte units" },
1731     { "sexagesimal", OPT_BOOL,  {(void*)&use_value_sexagesimal_format},
1732       "use sexagesimal format HOURS:MM:SS.MICROSECONDS for time units" },
1733     { "pretty", 0, {(void*)&opt_pretty},
1734       "prettify the format of displayed values, make it more human readable" },
1735     { "print_format", OPT_STRING | HAS_ARG, {(void*)&print_format},
1736       "set the output printing format (available formats are: default, compact, csv, json, xml)", "format" },
1737     { "show_error",   OPT_BOOL, {(void*)&do_show_error} ,  "show probing error" },
1738     { "show_format",  OPT_BOOL, {(void*)&do_show_format} , "show format/container info" },
1739     { "show_frames",  OPT_BOOL, {(void*)&do_show_frames} , "show frames info" },
1740     { "show_format_entry", HAS_ARG, {(void*)opt_show_format_entry},
1741       "show a particular entry from the format/container info", "entry" },
1742     { "show_packets", OPT_BOOL, {(void*)&do_show_packets}, "show packets info" },
1743     { "show_streams", OPT_BOOL, {(void*)&do_show_streams}, "show streams info" },
1744     { "count_frames", OPT_BOOL, {(void*)&do_count_frames}, "count the number of frames per stream" },
1745     { "count_packets", OPT_BOOL, {(void*)&do_count_packets}, "count the number of packets per stream" },
1746     { "show_program_version",  OPT_BOOL, {(void*)&do_show_program_version},  "show ffprobe version" },
1747     { "show_library_versions", OPT_BOOL, {(void*)&do_show_library_versions}, "show library versions" },
1748     { "show_versions",         0, {(void*)&opt_show_versions}, "show program and library versions" },
1749     { "show_private_data", OPT_BOOL, {(void*)&show_private_data}, "show private data" },
1750     { "private",           OPT_BOOL, {(void*)&show_private_data}, "same as show_private_data" },
1751     { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
1752     { "i", HAS_ARG, {(void *)opt_input_file}, "read specified file", "input_file"},
1753     { NULL, },
1754 };
1755
1756 int main(int argc, char **argv)
1757 {
1758     const Writer *w;
1759     WriterContext *wctx;
1760     char *buf;
1761     char *w_name = NULL, *w_args = NULL;
1762     int ret;
1763
1764     av_log_set_flags(AV_LOG_SKIP_REPEATED);
1765     parse_loglevel(argc, argv, options);
1766     av_register_all();
1767     avformat_network_init();
1768     init_opts();
1769 #if CONFIG_AVDEVICE
1770     avdevice_register_all();
1771 #endif
1772
1773     show_banner(argc, argv, options);
1774     parse_options(NULL, argc, argv, options, opt_input_file);
1775
1776     writer_register_all();
1777
1778     if (!print_format)
1779         print_format = av_strdup("default");
1780     w_name = av_strtok(print_format, "=", &buf);
1781     w_args = buf;
1782
1783     w = writer_get_by_name(w_name);
1784     if (!w) {
1785         av_log(NULL, AV_LOG_ERROR, "Unknown output format with name '%s'\n", w_name);
1786         ret = AVERROR(EINVAL);
1787         goto end;
1788     }
1789
1790     if ((ret = writer_open(&wctx, w, w_args, NULL)) >= 0) {
1791         writer_print_header(wctx);
1792
1793         if (do_show_program_version)
1794             ffprobe_show_program_version(wctx);
1795         if (do_show_library_versions)
1796             ffprobe_show_library_versions(wctx);
1797
1798         if (!input_filename &&
1799             ((do_show_format || do_show_streams || do_show_packets || do_show_error) ||
1800              (!do_show_program_version && !do_show_library_versions))) {
1801             show_usage();
1802             av_log(NULL, AV_LOG_ERROR, "You have to specify one input file.\n");
1803             av_log(NULL, AV_LOG_ERROR, "Use -h to get full help or, even better, run 'man %s'.\n", program_name);
1804             ret = AVERROR(EINVAL);
1805         } else if (input_filename) {
1806             ret = probe_file(wctx, input_filename);
1807             if (ret < 0 && do_show_error)
1808                 show_error(wctx, ret);
1809         }
1810
1811         writer_print_footer(wctx);
1812         writer_close(&wctx);
1813     }
1814
1815 end:
1816     av_freep(&print_format);
1817
1818     uninit_opts();
1819     av_dict_free(&fmt_entries_to_show);
1820
1821     avformat_network_deinit();
1822
1823     return ret;
1824 }