]> git.sesse.net Git - ffmpeg/blob - ffprobe.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / ffprobe.c
1 /*
2  * ffprobe : Simple Media Prober based on the FFmpeg libraries
3  * Copyright (c) 2007-2010 Stefano Sabatini
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "config.h"
23
24 #include "libavformat/avformat.h"
25 #include "libavcodec/avcodec.h"
26 #include "libavutil/avstring.h"
27 #include "libavutil/opt.h"
28 #include "libavutil/pixdesc.h"
29 #include "libavutil/dict.h"
30 #include "libavdevice/avdevice.h"
31 #include "cmdutils.h"
32
33 const char program_name[] = "ffprobe";
34 const int program_birth_year = 2007;
35
36 static int do_show_format  = 0;
37 static int do_show_packets = 0;
38 static int do_show_streams = 0;
39
40 static int show_value_unit              = 0;
41 static int use_value_prefix             = 0;
42 static int use_byte_value_binary_prefix = 0;
43 static int use_value_sexagesimal_format = 0;
44
45 static char *print_format;
46
47 static const OptionDef options[];
48
49 /* FFprobe context */
50 static const char *input_filename;
51 static AVInputFormat *iformat = NULL;
52
53 static const char *binary_unit_prefixes [] = { "", "Ki", "Mi", "Gi", "Ti", "Pi" };
54 static const char *decimal_unit_prefixes[] = { "", "K" , "M" , "G" , "T" , "P"  };
55
56 static const char *unit_second_str          = "s"    ;
57 static const char *unit_hertz_str           = "Hz"   ;
58 static const char *unit_byte_str            = "byte" ;
59 static const char *unit_bit_per_second_str  = "bit/s";
60
61 void av_noreturn exit_program(int ret)
62 {
63     exit(ret);
64 }
65
66 struct unit_value {
67     union { double d; int i; } val;
68     const char *unit;
69 };
70
71 static char *value_string(char *buf, int buf_size, struct unit_value uv)
72 {
73     double vald;
74     int show_float = 0;
75
76     if (uv.unit == unit_second_str) {
77         vald = uv.val.d;
78         show_float = 1;
79     } else {
80         vald = uv.val.i;
81     }
82
83     if (uv.unit == unit_second_str && use_value_sexagesimal_format) {
84         double secs;
85         int hours, mins;
86         secs  = vald;
87         mins  = (int)secs / 60;
88         secs  = secs - mins * 60;
89         hours = mins / 60;
90         mins %= 60;
91         snprintf(buf, buf_size, "%d:%02d:%09.6f", hours, mins, secs);
92     } else if (use_value_prefix) {
93         const char *prefix_string;
94         int index, l;
95
96         if (uv.unit == unit_byte_str && use_byte_value_binary_prefix) {
97             index = (int) (log(vald)/log(2)) / 10;
98             index = av_clip(index, 0, FF_ARRAY_ELEMS(binary_unit_prefixes) -1);
99             vald /= pow(2, index*10);
100             prefix_string = binary_unit_prefixes[index];
101         } else {
102             index = (int) (log10(vald)) / 3;
103             index = av_clip(index, 0, FF_ARRAY_ELEMS(decimal_unit_prefixes) -1);
104             vald /= pow(10, index*3);
105             prefix_string = decimal_unit_prefixes[index];
106         }
107
108         if (show_float || vald != (int)vald) l = snprintf(buf, buf_size, "%.3f", vald);
109         else                                 l = snprintf(buf, buf_size, "%d",   (int)vald);
110         snprintf(buf+l, buf_size-l, "%s%s%s", prefix_string || show_value_unit ? " " : "",
111                  prefix_string, show_value_unit ? uv.unit : "");
112     } else {
113         int l;
114
115         if (show_float) l = snprintf(buf, buf_size, "%.3f", vald);
116         else            l = snprintf(buf, buf_size, "%d",   (int)vald);
117         snprintf(buf+l, buf_size-l, "%s%s", show_value_unit ? " " : "",
118                  show_value_unit ? uv.unit : "");
119     }
120
121     return buf;
122 }
123
124 /* WRITERS API */
125
126 typedef struct WriterContext WriterContext;
127
128 #define WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS 1
129
130 typedef struct Writer {
131     int priv_size;                  ///< private size for the writer context
132     const char *name;
133
134     int  (*init)  (WriterContext *wctx, const char *args, void *opaque);
135     void (*uninit)(WriterContext *wctx);
136
137     void (*print_header)(WriterContext *ctx);
138     void (*print_footer)(WriterContext *ctx);
139
140     void (*print_chapter_header)(WriterContext *wctx, const char *);
141     void (*print_chapter_footer)(WriterContext *wctx, const char *);
142     void (*print_section_header)(WriterContext *wctx, const char *);
143     void (*print_section_footer)(WriterContext *wctx, const char *);
144     void (*print_integer)       (WriterContext *wctx, const char *, long long int);
145     void (*print_string)        (WriterContext *wctx, const char *, const char *);
146     void (*show_tags)           (WriterContext *wctx, AVDictionary *dict);
147     int flags;                  ///< a combination or WRITER_FLAG_*
148 } Writer;
149
150 struct WriterContext {
151     const AVClass *class;           ///< class of the writer
152     const Writer *writer;           ///< the Writer of which this is an instance
153     char *name;                     ///< name of this writer instance
154     void *priv;                     ///< private data for use by the filter
155     unsigned int nb_item;           ///< number of the item printed in the given section, starting at 0
156     unsigned int nb_section;        ///< number of the section printed in the given section sequence, starting at 0
157     unsigned int nb_chapter;        ///< number of the chapter, starting at 0
158 };
159
160 static const char *writer_get_name(void *p)
161 {
162     WriterContext *wctx = p;
163     return wctx->writer->name;
164 }
165
166 static const AVClass writer_class = {
167     "Writer",
168     writer_get_name,
169     NULL,
170     LIBAVUTIL_VERSION_INT,
171 };
172
173 static void writer_close(WriterContext **wctx)
174 {
175     if (*wctx && (*wctx)->writer->uninit)
176         (*wctx)->writer->uninit(*wctx);
177
178     av_freep(&((*wctx)->priv));
179     av_freep(wctx);
180 }
181
182 static int writer_open(WriterContext **wctx, const Writer *writer,
183                        const char *args, void *opaque)
184 {
185     int ret = 0;
186
187     if (!(*wctx = av_malloc(sizeof(WriterContext)))) {
188         ret = AVERROR(ENOMEM);
189         goto fail;
190     }
191
192     if (!((*wctx)->priv = av_mallocz(writer->priv_size))) {
193         ret = AVERROR(ENOMEM);
194         goto fail;
195     }
196
197     (*wctx)->class = &writer_class;
198     (*wctx)->writer = writer;
199     if ((*wctx)->writer->init)
200         ret = (*wctx)->writer->init(*wctx, args, opaque);
201     if (ret < 0)
202         goto fail;
203
204     return 0;
205
206 fail:
207     writer_close(wctx);
208     return ret;
209 }
210
211 static inline void writer_print_header(WriterContext *wctx)
212 {
213     if (wctx->writer->print_header)
214         wctx->writer->print_header(wctx);
215     wctx->nb_chapter = 0;
216 }
217
218 static inline void writer_print_footer(WriterContext *wctx)
219 {
220     if (wctx->writer->print_footer)
221         wctx->writer->print_footer(wctx);
222 }
223
224 static inline void writer_print_chapter_header(WriterContext *wctx,
225                                                const char *header)
226 {
227     if (wctx->writer->print_chapter_header)
228         wctx->writer->print_chapter_header(wctx, header);
229     wctx->nb_section = 0;
230 }
231
232 static inline void writer_print_chapter_footer(WriterContext *wctx,
233                                                const char *footer)
234 {
235     if (wctx->writer->print_chapter_footer)
236         wctx->writer->print_chapter_footer(wctx, footer);
237     wctx->nb_chapter++;
238 }
239
240 static inline void writer_print_section_header(WriterContext *wctx,
241                                                const char *header)
242 {
243     if (wctx->writer->print_section_header)
244         wctx->writer->print_section_header(wctx, header);
245     wctx->nb_item = 0;
246 }
247
248 static inline void writer_print_section_footer(WriterContext *wctx,
249                                                const char *footer)
250 {
251     if (wctx->writer->print_section_footer)
252         wctx->writer->print_section_footer(wctx, footer);
253     wctx->nb_section++;
254 }
255
256 static inline void writer_print_integer(WriterContext *wctx,
257                                         const char *key, long long int val)
258 {
259     wctx->writer->print_integer(wctx, key, val);
260     wctx->nb_item++;
261 }
262
263 static inline void writer_print_string(WriterContext *wctx,
264                                        const char *key, const char *val, int opt)
265 {
266     if (opt && !(wctx->writer->flags & WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS))
267         return;
268     wctx->writer->print_string(wctx, key, val);
269     wctx->nb_item++;
270 }
271
272 static void writer_print_time(WriterContext *wctx, const char *key,
273                               int64_t ts, const AVRational *time_base)
274 {
275     char buf[128];
276
277     if (ts == AV_NOPTS_VALUE) {
278         writer_print_string(wctx, key, "N/A", 1);
279     } else {
280         double d = ts * av_q2d(*time_base);
281         value_string(buf, sizeof(buf), (struct unit_value){.val.d=d, .unit=unit_second_str});
282         writer_print_string(wctx, key, buf, 0);
283     }
284 }
285
286 static void writer_print_ts(WriterContext *wctx, const char *key, int64_t ts)
287 {
288     if (ts == AV_NOPTS_VALUE) {
289         writer_print_string(wctx, key, "N/A", 1);
290     } else {
291         writer_print_integer(wctx, key, ts);
292     }
293 }
294
295 static inline void writer_show_tags(WriterContext *wctx, AVDictionary *dict)
296 {
297     wctx->writer->show_tags(wctx, dict);
298 }
299
300 #define MAX_REGISTERED_WRITERS_NB 64
301
302 static const Writer *registered_writers[MAX_REGISTERED_WRITERS_NB + 1];
303
304 static int writer_register(const Writer *writer)
305 {
306     static int next_registered_writer_idx = 0;
307
308     if (next_registered_writer_idx == MAX_REGISTERED_WRITERS_NB)
309         return AVERROR(ENOMEM);
310
311     registered_writers[next_registered_writer_idx++] = writer;
312     return 0;
313 }
314
315 static const Writer *writer_get_by_name(const char *name)
316 {
317     int i;
318
319     for (i = 0; registered_writers[i]; i++)
320         if (!strcmp(registered_writers[i]->name, name))
321             return registered_writers[i];
322
323     return NULL;
324 }
325
326 /* Print helpers */
327
328 struct print_buf {
329     char *s;
330     int len;
331 };
332
333 static char *fast_asprintf(struct print_buf *pbuf, const char *fmt, ...)
334 {
335     va_list va;
336     int len;
337
338     va_start(va, fmt);
339     len = vsnprintf(NULL, 0, fmt, va);
340     va_end(va);
341     if (len < 0)
342         goto fail;
343
344     if (pbuf->len < len) {
345         char *p = av_realloc(pbuf->s, len + 1);
346         if (!p)
347             goto fail;
348         pbuf->s   = p;
349         pbuf->len = len;
350     }
351
352     va_start(va, fmt);
353     len = vsnprintf(pbuf->s, len + 1, fmt, va);
354     va_end(va);
355     if (len < 0)
356         goto fail;
357     return pbuf->s;
358
359 fail:
360     av_freep(&pbuf->s);
361     pbuf->len = 0;
362     return NULL;
363 }
364
365 #define ESCAPE_INIT_BUF_SIZE 256
366
367 #define ESCAPE_CHECK_SIZE(src, size, max_size)                          \
368     if (size > max_size) {                                              \
369         char buf[64];                                                   \
370         snprintf(buf, sizeof(buf), "%s", src);                          \
371         av_log(log_ctx, AV_LOG_WARNING,                                 \
372                "String '%s...' with is too big\n", buf);                \
373         return "FFPROBE_TOO_BIG_STRING";                                \
374     }
375
376 #define ESCAPE_REALLOC_BUF(dst_size_p, dst_p, src, size)                \
377     if (*dst_size_p < size) {                                           \
378         char *q = av_realloc(*dst_p, size);                             \
379         if (!q) {                                                       \
380             char buf[64];                                               \
381             snprintf(buf, sizeof(buf), "%s", src);                      \
382             av_log(log_ctx, AV_LOG_WARNING,                             \
383                    "String '%s...' could not be escaped\n", buf);       \
384             return "FFPROBE_THIS_STRING_COULD_NOT_BE_ESCAPED";          \
385         }                                                               \
386         *dst_size_p = size;                                             \
387         *dst = q;                                                       \
388     }
389
390 /* WRITERS */
391
392 /* Default output */
393
394 static void default_print_footer(WriterContext *wctx)
395 {
396     printf("\n");
397 }
398
399 static void default_print_chapter_header(WriterContext *wctx, const char *chapter)
400 {
401     if (wctx->nb_chapter)
402         printf("\n");
403 }
404
405 /* lame uppercasing routine, assumes the string is lower case ASCII */
406 static inline char *upcase_string(char *dst, size_t dst_size, const char *src)
407 {
408     int i;
409     for (i = 0; src[i] && i < dst_size-1; i++)
410         dst[i] = src[i]-32;
411     dst[i] = 0;
412     return dst;
413 }
414
415 static void default_print_section_header(WriterContext *wctx, const char *section)
416 {
417     char buf[32];
418
419     if (wctx->nb_section)
420         printf("\n");
421     printf("[%s]\n", upcase_string(buf, sizeof(buf), section));
422 }
423
424 static void default_print_section_footer(WriterContext *wctx, const char *section)
425 {
426     char buf[32];
427
428     printf("[/%s]", upcase_string(buf, sizeof(buf), section));
429 }
430
431 static void default_print_str(WriterContext *wctx, const char *key, const char *value)
432 {
433     printf("%s=%s\n", key, value);
434 }
435
436 static void default_print_int(WriterContext *wctx, const char *key, long long int value)
437 {
438     printf("%s=%lld\n", key, value);
439 }
440
441 static void default_show_tags(WriterContext *wctx, AVDictionary *dict)
442 {
443     AVDictionaryEntry *tag = NULL;
444     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
445         printf("TAG:");
446         writer_print_string(wctx, tag->key, tag->value, 0);
447     }
448 }
449
450 static const Writer default_writer = {
451     .name                  = "default",
452     .print_footer          = default_print_footer,
453     .print_chapter_header  = default_print_chapter_header,
454     .print_section_header  = default_print_section_header,
455     .print_section_footer  = default_print_section_footer,
456     .print_integer         = default_print_int,
457     .print_string          = default_print_str,
458     .show_tags             = default_show_tags,
459     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
460 };
461
462 /* Compact output */
463
464 /**
465  * Escape \n, \r, \\ and sep characters contained in s, and print the
466  * resulting string.
467  */
468 static const char *c_escape_str(char **dst, size_t *dst_size,
469                                 const char *src, const char sep, void *log_ctx)
470 {
471     const char *p;
472     char *q;
473     size_t size = 1;
474
475     /* precompute size */
476     for (p = src; *p; p++, size++) {
477         ESCAPE_CHECK_SIZE(src, size, SIZE_MAX-2);
478         if (*p == '\n' || *p == '\r' || *p == '\\')
479             size++;
480     }
481
482     ESCAPE_REALLOC_BUF(dst_size, dst, src, size);
483
484     q = *dst;
485     for (p = src; *p; p++) {
486         switch (*src) {
487         case '\n': *q++ = '\\'; *q++ = 'n';  break;
488         case '\r': *q++ = '\\'; *q++ = 'r';  break;
489         case '\\': *q++ = '\\'; *q++ = '\\'; break;
490         default:
491             if (*p == sep)
492                 *q++ = '\\';
493             *q++ = *p;
494         }
495     }
496     *q = 0;
497     return *dst;
498 }
499
500 /**
501  * Quote fields containing special characters, check RFC4180.
502  */
503 static const char *csv_escape_str(char **dst, size_t *dst_size,
504                                   const char *src, const char sep, void *log_ctx)
505 {
506     const char *p;
507     char *q;
508     size_t size = 1;
509     int quote = 0;
510
511     /* precompute size */
512     for (p = src; *p; p++, size++) {
513         ESCAPE_CHECK_SIZE(src, size, SIZE_MAX-4);
514         if (*p == '"' || *p == sep || *p == '\n' || *p == '\r')
515             if (!quote) {
516                 quote = 1;
517                 size += 2;
518             }
519         if (*p == '"')
520             size++;
521     }
522
523     ESCAPE_REALLOC_BUF(dst_size, dst, src, size);
524
525     q = *dst;
526     p = src;
527     if (quote)
528         *q++ = '\"';
529     while (*p) {
530         if (*p == '"')
531             *q++ = '\"';
532         *q++ = *p++;
533     }
534     if (quote)
535         *q++ = '\"';
536     *q = 0;
537
538     return *dst;
539 }
540
541 static const char *none_escape_str(char **dst, size_t *dst_size,
542                                    const char *src, const char sep, void *log_ctx)
543 {
544     return src;
545 }
546
547 typedef struct CompactContext {
548     const AVClass *class;
549     char *item_sep_str;
550     char item_sep;
551     int nokey;
552     char  *buf;
553     size_t buf_size;
554     char *escape_mode_str;
555     const char * (*escape_str)(char **dst, size_t *dst_size,
556                                const char *src, const char sep, void *log_ctx);
557 } CompactContext;
558
559 #define OFFSET(x) offsetof(CompactContext, x)
560
561 static const AVOption compact_options[]= {
562     {"item_sep", "set item separator",    OFFSET(item_sep_str),    AV_OPT_TYPE_STRING, {.str="|"},  CHAR_MIN, CHAR_MAX },
563     {"s",        "set item separator",    OFFSET(item_sep_str),    AV_OPT_TYPE_STRING, {.str="|"},  CHAR_MIN, CHAR_MAX },
564     {"nokey",    "force no key printing", OFFSET(nokey),           AV_OPT_TYPE_INT,    {.dbl=0},    0,        1        },
565     {"nk",       "force no key printing", OFFSET(nokey),           AV_OPT_TYPE_INT,    {.dbl=0},    0,        1        },
566     {"escape",   "set escape mode",       OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"},  CHAR_MIN, CHAR_MAX },
567     {"e",        "set escape mode",       OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"},  CHAR_MIN, CHAR_MAX },
568     {NULL},
569 };
570
571 static const char *compact_get_name(void *ctx)
572 {
573     return "compact";
574 }
575
576 static const AVClass compact_class = {
577     "CompactContext",
578     compact_get_name,
579     compact_options
580 };
581
582 static av_cold int compact_init(WriterContext *wctx, const char *args, void *opaque)
583 {
584     CompactContext *compact = wctx->priv;
585     int err;
586
587     compact->class = &compact_class;
588     av_opt_set_defaults(compact);
589
590     if (args &&
591         (err = (av_set_options_string(compact, args, "=", ":"))) < 0) {
592         av_log(wctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
593         return err;
594     }
595     if (strlen(compact->item_sep_str) != 1) {
596         av_log(wctx, AV_LOG_ERROR, "Item separator '%s' specified, but must contain a single character\n",
597                compact->item_sep_str);
598         return AVERROR(EINVAL);
599     }
600     compact->item_sep = compact->item_sep_str[0];
601
602     compact->buf_size = ESCAPE_INIT_BUF_SIZE;
603     if (!(compact->buf = av_malloc(compact->buf_size)))
604         return AVERROR(ENOMEM);
605
606     if      (!strcmp(compact->escape_mode_str, "none")) compact->escape_str = none_escape_str;
607     else if (!strcmp(compact->escape_mode_str, "c"   )) compact->escape_str = c_escape_str;
608     else if (!strcmp(compact->escape_mode_str, "csv" )) compact->escape_str = csv_escape_str;
609     else {
610         av_log(wctx, AV_LOG_ERROR, "Unknown escape mode '%s'\n", compact->escape_mode_str);
611         return AVERROR(EINVAL);
612     }
613
614     return 0;
615 }
616
617 static av_cold void compact_uninit(WriterContext *wctx)
618 {
619     CompactContext *compact = wctx->priv;
620
621     av_freep(&compact->item_sep_str);
622     av_freep(&compact->buf);
623     av_freep(&compact->escape_mode_str);
624 }
625
626 static void compact_print_section_header(WriterContext *wctx, const char *section)
627 {
628     CompactContext *compact = wctx->priv;
629
630     printf("%s%c", section, compact->item_sep);
631 }
632
633 static void compact_print_section_footer(WriterContext *wctx, const char *section)
634 {
635     printf("\n");
636 }
637
638 static void compact_print_str(WriterContext *wctx, const char *key, const char *value)
639 {
640     CompactContext *compact = wctx->priv;
641
642     if (wctx->nb_item) printf("%c", compact->item_sep);
643     if (!compact->nokey)
644         printf("%s=", key);
645     printf("%s", compact->escape_str(&compact->buf, &compact->buf_size,
646                                      value, compact->item_sep, wctx));
647 }
648
649 static void compact_print_int(WriterContext *wctx, const char *key, long long int value)
650 {
651     CompactContext *compact = wctx->priv;
652
653     if (wctx->nb_item) printf("%c", compact->item_sep);
654     if (!compact->nokey)
655         printf("%s=", key);
656     printf("%lld", value);
657 }
658
659 static void compact_show_tags(WriterContext *wctx, AVDictionary *dict)
660 {
661     CompactContext *compact = wctx->priv;
662     AVDictionaryEntry *tag = NULL;
663
664     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
665         if (wctx->nb_item) printf("%c", compact->item_sep);
666         if (!compact->nokey)
667             printf("tag:%s=", compact->escape_str(&compact->buf, &compact->buf_size,
668                                                   tag->key, compact->item_sep, wctx));
669         printf("%s", compact->escape_str(&compact->buf, &compact->buf_size,
670                                          tag->value, compact->item_sep, wctx));
671     }
672 }
673
674 static const Writer compact_writer = {
675     .name                 = "compact",
676     .priv_size            = sizeof(CompactContext),
677     .init                 = compact_init,
678     .uninit               = compact_uninit,
679     .print_section_header = compact_print_section_header,
680     .print_section_footer = compact_print_section_footer,
681     .print_integer        = compact_print_int,
682     .print_string         = compact_print_str,
683     .show_tags            = compact_show_tags,
684     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
685 };
686
687 /* CSV output */
688
689 static av_cold int csv_init(WriterContext *wctx, const char *args, void *opaque)
690 {
691     return compact_init(wctx, "item_sep=,:nokey=1:escape=csv", opaque);
692 }
693
694 static const Writer csv_writer = {
695     .name                 = "csv",
696     .priv_size            = sizeof(CompactContext),
697     .init                 = csv_init,
698     .uninit               = compact_uninit,
699     .print_section_header = compact_print_section_header,
700     .print_section_footer = compact_print_section_footer,
701     .print_integer        = compact_print_int,
702     .print_string         = compact_print_str,
703     .show_tags            = compact_show_tags,
704     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
705 };
706
707 /* JSON output */
708
709 typedef struct {
710     int multiple_entries; ///< tells if the given chapter requires multiple entries
711     char *buf;
712     size_t buf_size;
713 } JSONContext;
714
715 static av_cold int json_init(WriterContext *wctx, const char *args, void *opaque)
716 {
717     JSONContext *json = wctx->priv;
718
719     json->buf_size = ESCAPE_INIT_BUF_SIZE;
720     if (!(json->buf = av_malloc(json->buf_size)))
721         return AVERROR(ENOMEM);
722
723     return 0;
724 }
725
726 static av_cold void json_uninit(WriterContext *wctx)
727 {
728     JSONContext *json = wctx->priv;
729     av_freep(&json->buf);
730 }
731
732 static const char *json_escape_str(char **dst, size_t *dst_size, const char *src,
733                                    void *log_ctx)
734 {
735     static const char json_escape[] = {'"', '\\', '\b', '\f', '\n', '\r', '\t', 0};
736     static const char json_subst[]  = {'"', '\\',  'b',  'f',  'n',  'r',  't', 0};
737     const char *p;
738     char *q;
739     size_t size = 1;
740
741     // compute the length of the escaped string
742     for (p = src; *p; p++) {
743         ESCAPE_CHECK_SIZE(src, size, SIZE_MAX-6);
744         if (strchr(json_escape, *p))     size += 2; // simple escape
745         else if ((unsigned char)*p < 32) size += 6; // handle non-printable chars
746         else                             size += 1; // char copy
747     }
748     ESCAPE_REALLOC_BUF(dst_size, dst, src, size);
749
750     q = *dst;
751     for (p = src; *p; p++) {
752         char *s = strchr(json_escape, *p);
753         if (s) {
754             *q++ = '\\';
755             *q++ = json_subst[s - json_escape];
756         } else if ((unsigned char)*p < 32) {
757             snprintf(q, 7, "\\u00%02x", *p & 0xff);
758             q += 6;
759         } else {
760             *q++ = *p;
761         }
762     }
763     *q = 0;
764     return *dst;
765 }
766
767 static void json_print_header(WriterContext *wctx)
768 {
769     printf("{");
770 }
771
772 static void json_print_footer(WriterContext *wctx)
773 {
774     printf("\n}\n");
775 }
776
777 static void json_print_chapter_header(WriterContext *wctx, const char *chapter)
778 {
779     JSONContext *json = wctx->priv;
780
781     if (wctx->nb_chapter)
782         printf(",");
783     json->multiple_entries = !strcmp(chapter, "packets") || !strcmp(chapter, "streams");
784     printf("\n  \"%s\":%s", json_escape_str(&json->buf, &json->buf_size, chapter, wctx),
785            json->multiple_entries ? " [" : " ");
786 }
787
788 static void json_print_chapter_footer(WriterContext *wctx, const char *chapter)
789 {
790     JSONContext *json = wctx->priv;
791
792     if (json->multiple_entries)
793         printf("]");
794 }
795
796 static void json_print_section_header(WriterContext *wctx, const char *section)
797 {
798     if (wctx->nb_section) printf(",");
799     printf("{\n");
800 }
801
802 static void json_print_section_footer(WriterContext *wctx, const char *section)
803 {
804     printf("\n  }");
805 }
806
807 static inline void json_print_item_str(WriterContext *wctx,
808                                        const char *key, const char *value,
809                                        const char *indent)
810 {
811     JSONContext *json = wctx->priv;
812
813     printf("%s\"%s\":", indent, json_escape_str(&json->buf, &json->buf_size, key,   wctx));
814     printf(" \"%s\"",           json_escape_str(&json->buf, &json->buf_size, value, wctx));
815 }
816
817 #define INDENT "    "
818
819 static void json_print_str(WriterContext *wctx, const char *key, const char *value)
820 {
821     if (wctx->nb_item) printf(",\n");
822     json_print_item_str(wctx, key, value, INDENT);
823 }
824
825 static void json_print_int(WriterContext *wctx, const char *key, long long int value)
826 {
827     JSONContext *json = wctx->priv;
828
829     if (wctx->nb_item) printf(",\n");
830     printf(INDENT "\"%s\": %lld",
831            json_escape_str(&json->buf, &json->buf_size, key, wctx), value);
832 }
833
834 static void json_show_tags(WriterContext *wctx, AVDictionary *dict)
835 {
836     AVDictionaryEntry *tag = NULL;
837     int is_first = 1;
838     if (!dict)
839         return;
840     printf(",\n" INDENT "\"tags\": {\n");
841     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
842         if (is_first) is_first = 0;
843         else          printf(",\n");
844         json_print_item_str(wctx, tag->key, tag->value, INDENT INDENT);
845     }
846     printf("\n    }");
847 }
848
849 static const Writer json_writer = {
850     .name                 = "json",
851     .priv_size            = sizeof(JSONContext),
852     .init                 = json_init,
853     .uninit               = json_uninit,
854     .print_header         = json_print_header,
855     .print_footer         = json_print_footer,
856     .print_chapter_header = json_print_chapter_header,
857     .print_chapter_footer = json_print_chapter_footer,
858     .print_section_header = json_print_section_header,
859     .print_section_footer = json_print_section_footer,
860     .print_integer        = json_print_int,
861     .print_string         = json_print_str,
862     .show_tags            = json_show_tags,
863 };
864
865 static void writer_register_all(void)
866 {
867     static int initialized;
868
869     if (initialized)
870         return;
871     initialized = 1;
872
873     writer_register(&default_writer);
874     writer_register(&compact_writer);
875     writer_register(&csv_writer);
876     writer_register(&json_writer);
877 }
878
879 #define print_fmt(k, f, ...) do {              \
880     if (fast_asprintf(&pbuf, f, __VA_ARGS__))  \
881         writer_print_string(w, k, pbuf.s, 0);  \
882 } while (0)
883
884 #define print_fmt_opt(k, f, ...) do {          \
885     if (fast_asprintf(&pbuf, f, __VA_ARGS__))  \
886         writer_print_string(w, k, pbuf.s, 1);  \
887 } while (0)
888
889 #define print_int(k, v)         writer_print_integer(w, k, v)
890 #define print_str(k, v)         writer_print_string(w, k, v, 0)
891 #define print_str_opt(k, v)     writer_print_string(w, k, v, 1)
892 #define print_time(k, v, tb)    writer_print_time(w, k, v, tb)
893 #define print_ts(k, v)          writer_print_ts(w, k, v)
894 #define print_val(k, v, u)      writer_print_string(w, k, \
895     value_string(val_str, sizeof(val_str), (struct unit_value){.val.i = v, .unit=u}), 0)
896 #define print_section_header(s) writer_print_section_header(w, s)
897 #define print_section_footer(s) writer_print_section_footer(w, s)
898 #define show_tags(metadata)     writer_show_tags(w, metadata)
899
900 static void show_packet(WriterContext *w, AVFormatContext *fmt_ctx, AVPacket *pkt, int packet_idx)
901 {
902     char val_str[128];
903     AVStream *st = fmt_ctx->streams[pkt->stream_index];
904     struct print_buf pbuf = {.s = NULL};
905     const char *s;
906
907     print_section_header("packet");
908     s = av_get_media_type_string(st->codec->codec_type);
909     if (s) print_str    ("codec_type", s);
910     else   print_str_opt("codec_type", "unknown");
911     print_int("stream_index",     pkt->stream_index);
912     print_ts  ("pts",             pkt->pts);
913     print_time("pts_time",        pkt->pts, &st->time_base);
914     print_ts  ("dts",             pkt->dts);
915     print_time("dts_time",        pkt->dts, &st->time_base);
916     print_ts  ("duration",        pkt->duration);
917     print_time("duration_time",   pkt->duration, &st->time_base);
918     print_val("size",             pkt->size, unit_byte_str);
919     if (pkt->pos != -1) print_fmt    ("pos", "%"PRId64, pkt->pos);
920     else                print_str_opt("pos", "N/A");
921     print_fmt("flags", "%c",      pkt->flags & AV_PKT_FLAG_KEY ? 'K' : '_');
922     print_section_footer("packet");
923
924     av_free(pbuf.s);
925     fflush(stdout);
926 }
927
928 static void show_packets(WriterContext *w, AVFormatContext *fmt_ctx)
929 {
930     AVPacket pkt;
931     int i = 0;
932
933     av_init_packet(&pkt);
934
935     while (!av_read_frame(fmt_ctx, &pkt))
936         show_packet(w, fmt_ctx, &pkt, i++);
937 }
938
939 static void show_stream(WriterContext *w, AVFormatContext *fmt_ctx, int stream_idx)
940 {
941     AVStream *stream = fmt_ctx->streams[stream_idx];
942     AVCodecContext *dec_ctx;
943     AVCodec *dec;
944     char val_str[128];
945     const char *s;
946     AVRational display_aspect_ratio;
947     struct print_buf pbuf = {.s = NULL};
948
949     print_section_header("stream");
950
951     print_int("index", stream->index);
952
953     if ((dec_ctx = stream->codec)) {
954         if ((dec = dec_ctx->codec)) {
955             print_str("codec_name",      dec->name);
956             print_str("codec_long_name", dec->long_name);
957         } else {
958             print_str_opt("codec_name",      "unknown");
959             print_str_opt("codec_long_name", "unknown");
960         }
961
962         s = av_get_media_type_string(dec_ctx->codec_type);
963         if (s) print_str    ("codec_type", s);
964         else   print_str_opt("codec_type", "unknown");
965         print_fmt("codec_time_base", "%d/%d", dec_ctx->time_base.num, dec_ctx->time_base.den);
966
967         /* print AVI/FourCC tag */
968         av_get_codec_tag_string(val_str, sizeof(val_str), dec_ctx->codec_tag);
969         print_str("codec_tag_string",    val_str);
970         print_fmt("codec_tag", "0x%04x", dec_ctx->codec_tag);
971
972         switch (dec_ctx->codec_type) {
973         case AVMEDIA_TYPE_VIDEO:
974             print_int("width",        dec_ctx->width);
975             print_int("height",       dec_ctx->height);
976             print_int("has_b_frames", dec_ctx->has_b_frames);
977             if (dec_ctx->sample_aspect_ratio.num) {
978                 print_fmt("sample_aspect_ratio", "%d:%d",
979                           dec_ctx->sample_aspect_ratio.num,
980                           dec_ctx->sample_aspect_ratio.den);
981                 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
982                           dec_ctx->width  * dec_ctx->sample_aspect_ratio.num,
983                           dec_ctx->height * dec_ctx->sample_aspect_ratio.den,
984                           1024*1024);
985                 print_fmt("display_aspect_ratio", "%d:%d",
986                           display_aspect_ratio.num,
987                           display_aspect_ratio.den);
988             } else {
989                 print_str_opt("sample_aspect_ratio", "N/A");
990                 print_str_opt("display_aspect_ratio", "N/A");
991             }
992             s = av_get_pix_fmt_name(dec_ctx->pix_fmt);
993             if (s) print_str    ("pix_fmt", s);
994             else   print_str_opt("pix_fmt", "unknown");
995             print_int("level",   dec_ctx->level);
996             if (dec_ctx->timecode_frame_start >= 0) {
997                 uint32_t tc = dec_ctx->timecode_frame_start;
998                 print_fmt("timecode", "%02d:%02d:%02d%c%02d",
999                           tc>>19 & 0x1f,              // hours
1000                           tc>>13 & 0x3f,              // minutes
1001                           tc>>6  & 0x3f,              // seconds
1002                           tc     & 1<<24 ? ';' : ':', // drop
1003                           tc     & 0x3f);             // frames
1004             } else {
1005                 print_str_opt("timecode", "N/A");
1006             }
1007             break;
1008
1009         case AVMEDIA_TYPE_AUDIO:
1010             s = av_get_sample_fmt_name(dec_ctx->sample_fmt);
1011             if (s) print_str    ("sample_fmt", s);
1012             else   print_str_opt("sample_fmt", "unknown");
1013             print_val("sample_rate",     dec_ctx->sample_rate, unit_hertz_str);
1014             print_int("channels",        dec_ctx->channels);
1015             print_int("bits_per_sample", av_get_bits_per_sample(dec_ctx->codec_id));
1016             break;
1017         }
1018     } else {
1019         print_str_opt("codec_type", "unknown");
1020     }
1021     if (dec_ctx->codec && dec_ctx->codec->priv_class) {
1022         const AVOption *opt = NULL;
1023         while (opt = av_opt_next(dec_ctx->priv_data,opt)) {
1024             uint8_t *str;
1025             if (opt->flags) continue;
1026             if (av_opt_get(dec_ctx->priv_data, opt->name, 0, &str) >= 0) {
1027                 print_str(opt->name, str);
1028                 av_free(str);
1029             }
1030         }
1031     }
1032
1033     if (fmt_ctx->iformat->flags & AVFMT_SHOW_IDS) print_fmt    ("id", "0x%x", stream->id);
1034     else                                          print_str_opt("id", "N/A");
1035     print_fmt("r_frame_rate",   "%d/%d", stream->r_frame_rate.num,   stream->r_frame_rate.den);
1036     print_fmt("avg_frame_rate", "%d/%d", stream->avg_frame_rate.num, stream->avg_frame_rate.den);
1037     print_fmt("time_base",      "%d/%d", stream->time_base.num,      stream->time_base.den);
1038     print_time("start_time",    stream->start_time, &stream->time_base);
1039     print_time("duration",      stream->duration,   &stream->time_base);
1040     if (stream->nb_frames) print_fmt    ("nb_frames", "%"PRId64, stream->nb_frames);
1041     else                   print_str_opt("nb_frames", "N/A");
1042     show_tags(stream->metadata);
1043
1044     print_section_footer("stream");
1045     av_free(pbuf.s);
1046     fflush(stdout);
1047 }
1048
1049 static void show_streams(WriterContext *w, AVFormatContext *fmt_ctx)
1050 {
1051     int i;
1052     for (i = 0; i < fmt_ctx->nb_streams; i++)
1053         show_stream(w, fmt_ctx, i);
1054 }
1055
1056 static void show_format(WriterContext *w, AVFormatContext *fmt_ctx)
1057 {
1058     char val_str[128];
1059     int64_t size = avio_size(fmt_ctx->pb);
1060     struct print_buf pbuf = {.s = NULL};
1061
1062     print_section_header("format");
1063     print_str("filename",         fmt_ctx->filename);
1064     print_int("nb_streams",       fmt_ctx->nb_streams);
1065     print_str("format_name",      fmt_ctx->iformat->name);
1066     print_str("format_long_name", fmt_ctx->iformat->long_name);
1067     print_time("start_time",      fmt_ctx->start_time, &AV_TIME_BASE_Q);
1068     print_time("duration",        fmt_ctx->duration,   &AV_TIME_BASE_Q);
1069     if (size >= 0) print_val    ("size", size, unit_byte_str);
1070     else           print_str_opt("size", "N/A");
1071     if (fmt_ctx->bit_rate > 0) print_val    ("bit_rate", fmt_ctx->bit_rate, unit_bit_per_second_str);
1072     else                       print_str_opt("bit_rate", "N/A");
1073     show_tags(fmt_ctx->metadata);
1074     print_section_footer("format");
1075     av_free(pbuf.s);
1076     fflush(stdout);
1077 }
1078
1079 static int open_input_file(AVFormatContext **fmt_ctx_ptr, const char *filename)
1080 {
1081     int err, i;
1082     AVFormatContext *fmt_ctx = NULL;
1083     AVDictionaryEntry *t;
1084
1085     if ((err = avformat_open_input(&fmt_ctx, filename, iformat, &format_opts)) < 0) {
1086         print_error(filename, err);
1087         return err;
1088     }
1089     if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
1090         av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
1091         return AVERROR_OPTION_NOT_FOUND;
1092     }
1093
1094
1095     /* fill the streams in the format context */
1096     if ((err = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
1097         print_error(filename, err);
1098         return err;
1099     }
1100
1101     av_dump_format(fmt_ctx, 0, filename, 0);
1102
1103     /* bind a decoder to each input stream */
1104     for (i = 0; i < fmt_ctx->nb_streams; i++) {
1105         AVStream *stream = fmt_ctx->streams[i];
1106         AVCodec *codec;
1107
1108         if (!(codec = avcodec_find_decoder(stream->codec->codec_id))) {
1109             fprintf(stderr, "Unsupported codec with id %d for input stream %d\n",
1110                     stream->codec->codec_id, stream->index);
1111         } else if (avcodec_open2(stream->codec, codec, NULL) < 0) {
1112             fprintf(stderr, "Error while opening codec for input stream %d\n",
1113                     stream->index);
1114         }
1115     }
1116
1117     *fmt_ctx_ptr = fmt_ctx;
1118     return 0;
1119 }
1120
1121 #define PRINT_CHAPTER(name) do {                                        \
1122     if (do_show_ ## name) {                                             \
1123         writer_print_chapter_header(wctx, #name);                       \
1124         show_ ## name (wctx, fmt_ctx);                                  \
1125         writer_print_chapter_footer(wctx, #name);                       \
1126     }                                                                   \
1127 } while (0)
1128
1129 static int probe_file(const char *filename)
1130 {
1131     AVFormatContext *fmt_ctx;
1132     int ret;
1133     const Writer *w;
1134     char *buf;
1135     char *w_name = NULL, *w_args = NULL;
1136     WriterContext *wctx;
1137
1138     writer_register_all();
1139
1140     if (!print_format)
1141         print_format = av_strdup("default");
1142     w_name = av_strtok(print_format, "=", &buf);
1143     w_args = buf;
1144
1145     w = writer_get_by_name(w_name);
1146     if (!w) {
1147         av_log(NULL, AV_LOG_ERROR, "Unknown output format with name '%s'\n", w_name);
1148         ret = AVERROR(EINVAL);
1149         goto end;
1150     }
1151
1152     if ((ret = writer_open(&wctx, w, w_args, NULL)) < 0)
1153         goto end;
1154     if ((ret = open_input_file(&fmt_ctx, filename)))
1155         goto end;
1156
1157     writer_print_header(wctx);
1158     PRINT_CHAPTER(packets);
1159     PRINT_CHAPTER(streams);
1160     PRINT_CHAPTER(format);
1161     writer_print_footer(wctx);
1162
1163     av_close_input_file(fmt_ctx);
1164     writer_close(&wctx);
1165
1166 end:
1167     av_freep(&print_format);
1168
1169     return ret;
1170 }
1171
1172 static void show_usage(void)
1173 {
1174     printf("Simple multimedia streams analyzer\n");
1175     printf("usage: %s [OPTIONS] [INPUT_FILE]\n", program_name);
1176     printf("\n");
1177 }
1178
1179 static int opt_format(const char *opt, const char *arg)
1180 {
1181     iformat = av_find_input_format(arg);
1182     if (!iformat) {
1183         fprintf(stderr, "Unknown input format: %s\n", arg);
1184         return AVERROR(EINVAL);
1185     }
1186     return 0;
1187 }
1188
1189 static void opt_input_file(void *optctx, const char *arg)
1190 {
1191     if (input_filename) {
1192         fprintf(stderr, "Argument '%s' provided as input filename, but '%s' was already specified.\n",
1193                 arg, input_filename);
1194         exit(1);
1195     }
1196     if (!strcmp(arg, "-"))
1197         arg = "pipe:";
1198     input_filename = arg;
1199 }
1200
1201 static int opt_help(const char *opt, const char *arg)
1202 {
1203     av_log_set_callback(log_callback_help);
1204     show_usage();
1205     show_help_options(options, "Main options:\n", 0, 0);
1206     printf("\n");
1207
1208     show_help_children(avformat_get_class(), AV_OPT_FLAG_DECODING_PARAM);
1209
1210     return 0;
1211 }
1212
1213 static int opt_pretty(const char *opt, const char *arg)
1214 {
1215     show_value_unit              = 1;
1216     use_value_prefix             = 1;
1217     use_byte_value_binary_prefix = 1;
1218     use_value_sexagesimal_format = 1;
1219     return 0;
1220 }
1221
1222 static const OptionDef options[] = {
1223 #include "cmdutils_common_opts.h"
1224     { "f", HAS_ARG, {(void*)opt_format}, "force format", "format" },
1225     { "unit", OPT_BOOL, {(void*)&show_value_unit}, "show unit of the displayed values" },
1226     { "prefix", OPT_BOOL, {(void*)&use_value_prefix}, "use SI prefixes for the displayed values" },
1227     { "byte_binary_prefix", OPT_BOOL, {(void*)&use_byte_value_binary_prefix},
1228       "use binary prefixes for byte units" },
1229     { "sexagesimal", OPT_BOOL,  {(void*)&use_value_sexagesimal_format},
1230       "use sexagesimal format HOURS:MM:SS.MICROSECONDS for time units" },
1231     { "pretty", 0, {(void*)&opt_pretty},
1232       "prettify the format of displayed values, make it more human readable" },
1233     { "print_format", OPT_STRING | HAS_ARG, {(void*)&print_format},
1234       "set the output printing format (available formats are: default, compact, csv, json)", "format" },
1235     { "show_format",  OPT_BOOL, {(void*)&do_show_format} , "show format/container info" },
1236     { "show_packets", OPT_BOOL, {(void*)&do_show_packets}, "show packets info" },
1237     { "show_streams", OPT_BOOL, {(void*)&do_show_streams}, "show streams info" },
1238     { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
1239     { "i", HAS_ARG, {(void *)opt_input_file}, "read specified file", "input_file"},
1240     { NULL, },
1241 };
1242
1243 int main(int argc, char **argv)
1244 {
1245     int ret;
1246
1247     parse_loglevel(argc, argv, options);
1248     av_register_all();
1249     avformat_network_init();
1250     init_opts();
1251 #if CONFIG_AVDEVICE
1252     avdevice_register_all();
1253 #endif
1254
1255     show_banner();
1256     parse_options(NULL, argc, argv, options, opt_input_file);
1257
1258     if (!input_filename) {
1259         show_usage();
1260         fprintf(stderr, "You have to specify one input file.\n");
1261         fprintf(stderr, "Use -h to get full help or, even better, run 'man %s'.\n", program_name);
1262         exit(1);
1263     }
1264
1265     ret = probe_file(input_filename);
1266
1267     avformat_network_deinit();
1268
1269     return ret;
1270 }