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