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