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