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