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