]> git.sesse.net Git - ffmpeg/blob - ffprobe.c
ffprobe: small align cosmetic in json writer struct init.
[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 *, 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, 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     char buf[128];
289
290     if (ts == AV_NOPTS_VALUE) {
291         writer_print_string(wctx, key, "N/A", 1);
292     } else {
293         snprintf(buf, sizeof(buf), "%"PRId64, ts);
294         writer_print_string(wctx, key, buf, 0);
295     }
296 }
297
298 static inline void writer_show_tags(WriterContext *wctx, AVDictionary *dict)
299 {
300     wctx->writer->show_tags(wctx, dict);
301 }
302
303 #define MAX_REGISTERED_WRITERS_NB 64
304
305 static const Writer *registered_writers[MAX_REGISTERED_WRITERS_NB + 1];
306
307 static int writer_register(const Writer *writer)
308 {
309     static int next_registered_writer_idx = 0;
310
311     if (next_registered_writer_idx == MAX_REGISTERED_WRITERS_NB)
312         return AVERROR(ENOMEM);
313
314     registered_writers[next_registered_writer_idx++] = writer;
315     return 0;
316 }
317
318 static const Writer *writer_get_by_name(const char *name)
319 {
320     int i;
321
322     for (i = 0; registered_writers[i]; i++)
323         if (!strcmp(registered_writers[i]->name, name))
324             return registered_writers[i];
325
326     return NULL;
327 }
328
329 /* Print helpers */
330
331 struct print_buf {
332     char *s;
333     int len;
334 };
335
336 static char *fast_asprintf(struct print_buf *pbuf, const char *fmt, ...)
337 {
338     va_list va;
339     int len;
340
341     va_start(va, fmt);
342     len = vsnprintf(NULL, 0, fmt, va);
343     va_end(va);
344     if (len < 0)
345         goto fail;
346
347     if (pbuf->len < len) {
348         char *p = av_realloc(pbuf->s, len + 1);
349         if (!p)
350             goto fail;
351         pbuf->s   = p;
352         pbuf->len = len;
353     }
354
355     va_start(va, fmt);
356     len = vsnprintf(pbuf->s, len + 1, fmt, va);
357     va_end(va);
358     if (len < 0)
359         goto fail;
360     return pbuf->s;
361
362 fail:
363     av_freep(&pbuf->s);
364     pbuf->len = 0;
365     return NULL;
366 }
367
368 #define ESCAPE_INIT_BUF_SIZE 256
369
370 #define ESCAPE_CHECK_SIZE(src, size, max_size)                          \
371     if (size > max_size) {                                              \
372         char buf[64];                                                   \
373         snprintf(buf, sizeof(buf), "%s", src);                          \
374         av_log(log_ctx, AV_LOG_WARNING,                                 \
375                "String '%s...' with is too big\n", buf);                \
376         return "FFPROBE_TOO_BIG_STRING";                                \
377     }
378
379 #define ESCAPE_REALLOC_BUF(dst_size_p, dst_p, src, size)                \
380     if (*dst_size_p < size) {                                           \
381         char *q = av_realloc(*dst_p, size);                             \
382         if (!q) {                                                       \
383             char buf[64];                                               \
384             snprintf(buf, sizeof(buf), "%s", src);                      \
385             av_log(log_ctx, AV_LOG_WARNING,                             \
386                    "String '%s...' could not be escaped\n", buf);       \
387             return "FFPROBE_THIS_STRING_COULD_NOT_BE_ESCAPED";          \
388         }                                                               \
389         *dst_size_p = size;                                             \
390         *dst = q;                                                       \
391     }
392
393 /* WRITERS */
394
395 /* Default output */
396
397 static void default_print_footer(WriterContext *wctx)
398 {
399     printf("\n");
400 }
401
402 static void default_print_chapter_header(WriterContext *wctx, const char *chapter)
403 {
404     if (wctx->nb_chapter)
405         printf("\n");
406 }
407
408 /* lame uppercasing routine, assumes the string is lower case ASCII */
409 static inline char *upcase_string(char *dst, size_t dst_size, const char *src)
410 {
411     int i;
412     for (i = 0; src[i] && i < dst_size-1; i++)
413         dst[i] = src[i]-32;
414     dst[i] = 0;
415     return dst;
416 }
417
418 static void default_print_section_header(WriterContext *wctx, const char *section)
419 {
420     char buf[32];
421
422     if (wctx->nb_section)
423         printf("\n");
424     printf("[%s]\n", upcase_string(buf, sizeof(buf), section));
425 }
426
427 static void default_print_section_footer(WriterContext *wctx, const char *section)
428 {
429     char buf[32];
430
431     printf("[/%s]", upcase_string(buf, sizeof(buf), section));
432 }
433
434 static void default_print_str(WriterContext *wctx, const char *key, const char *value)
435 {
436     printf("%s=%s\n", key, value);
437 }
438
439 static void default_print_int(WriterContext *wctx, const char *key, int value)
440 {
441     printf("%s=%d\n", key, value);
442 }
443
444 static void default_show_tags(WriterContext *wctx, AVDictionary *dict)
445 {
446     AVDictionaryEntry *tag = NULL;
447     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
448         printf("TAG:");
449         writer_print_string(wctx, tag->key, tag->value, 0);
450     }
451 }
452
453 static const Writer default_writer = {
454     .name                  = "default",
455     .print_footer          = default_print_footer,
456     .print_chapter_header  = default_print_chapter_header,
457     .print_section_header  = default_print_section_header,
458     .print_section_footer  = default_print_section_footer,
459     .print_integer         = default_print_int,
460     .print_string          = default_print_str,
461     .show_tags             = default_show_tags,
462     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
463 };
464
465 /* Compact output */
466
467 /**
468  * Escape \n, \r, \\ and sep characters contained in s, and print the
469  * resulting string.
470  */
471 static const char *c_escape_str(char **dst, size_t *dst_size,
472                                 const char *src, const char sep, void *log_ctx)
473 {
474     const char *p;
475     char *q;
476     size_t size = 1;
477
478     /* precompute size */
479     for (p = src; *p; p++, size++) {
480         ESCAPE_CHECK_SIZE(src, size, SIZE_MAX-2);
481         if (*p == '\n' || *p == '\r' || *p == '\\')
482             size++;
483     }
484
485     ESCAPE_REALLOC_BUF(dst_size, dst, src, size);
486
487     q = *dst;
488     for (p = src; *p; p++) {
489         switch (*src) {
490         case '\n': *q++ = '\\'; *q++ = 'n';  break;
491         case '\r': *q++ = '\\'; *q++ = 'r';  break;
492         case '\\': *q++ = '\\'; *q++ = '\\'; break;
493         default:
494             if (*p == sep)
495                 *q++ = '\\';
496             *q++ = *p;
497         }
498     }
499     *q = 0;
500     return *dst;
501 }
502
503 /**
504  * Quote fields containing special characters, check RFC4180.
505  */
506 static const char *csv_escape_str(char **dst, size_t *dst_size,
507                                   const char *src, const char sep, void *log_ctx)
508 {
509     const char *p;
510     char *q;
511     size_t size = 1;
512     int quote = 0;
513
514     /* precompute size */
515     for (p = src; *p; p++, size++) {
516         ESCAPE_CHECK_SIZE(src, size, SIZE_MAX-4);
517         if (*p == '"' || *p == sep || *p == '\n' || *p == '\r')
518             if (!quote) {
519                 quote = 1;
520                 size += 2;
521             }
522         if (*p == '"')
523             size++;
524     }
525
526     ESCAPE_REALLOC_BUF(dst_size, dst, src, size);
527
528     q = *dst;
529     p = src;
530     if (quote)
531         *q++ = '\"';
532     while (*p) {
533         if (*p == '"')
534             *q++ = '\"';
535         *q++ = *p++;
536     }
537     if (quote)
538         *q++ = '\"';
539     *q = 0;
540
541     return *dst;
542 }
543
544 static const char *none_escape_str(char **dst, size_t *dst_size,
545                                    const char *src, const char sep, void *log_ctx)
546 {
547     return src;
548 }
549
550 typedef struct CompactContext {
551     const AVClass *class;
552     char *item_sep_str;
553     char item_sep;
554     int nokey;
555     char  *buf;
556     size_t buf_size;
557     char *escape_mode_str;
558     const char * (*escape_str)(char **dst, size_t *dst_size,
559                                const char *src, const char sep, void *log_ctx);
560 } CompactContext;
561
562 #define OFFSET(x) offsetof(CompactContext, x)
563
564 static const AVOption compact_options[]= {
565     {"item_sep", "set item separator",    OFFSET(item_sep_str),    AV_OPT_TYPE_STRING, {.str="|"},  CHAR_MIN, CHAR_MAX },
566     {"s",        "set item separator",    OFFSET(item_sep_str),    AV_OPT_TYPE_STRING, {.str="|"},  CHAR_MIN, CHAR_MAX },
567     {"nokey",    "force no key printing", OFFSET(nokey),           AV_OPT_TYPE_INT,    {.dbl=0},    0,        1        },
568     {"nk",       "force no key printing", OFFSET(nokey),           AV_OPT_TYPE_INT,    {.dbl=0},    0,        1        },
569     {"escape",   "set escape mode",       OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"},  CHAR_MIN, CHAR_MAX },
570     {"e",        "set escape mode",       OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"},  CHAR_MIN, CHAR_MAX },
571     {NULL},
572 };
573
574 static const char *compact_get_name(void *ctx)
575 {
576     return "compact";
577 }
578
579 static const AVClass compact_class = {
580     "CompactContext",
581     compact_get_name,
582     compact_options
583 };
584
585 static av_cold int compact_init(WriterContext *wctx, const char *args, void *opaque)
586 {
587     CompactContext *compact = wctx->priv;
588     int err;
589
590     compact->class = &compact_class;
591     av_opt_set_defaults(compact);
592
593     if (args &&
594         (err = (av_set_options_string(compact, args, "=", ":"))) < 0) {
595         av_log(wctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
596         return err;
597     }
598     if (strlen(compact->item_sep_str) != 1) {
599         av_log(wctx, AV_LOG_ERROR, "Item separator '%s' specified, but must contain a single character\n",
600                compact->item_sep_str);
601         return AVERROR(EINVAL);
602     }
603     compact->item_sep = compact->item_sep_str[0];
604
605     compact->buf_size = ESCAPE_INIT_BUF_SIZE;
606     if (!(compact->buf = av_malloc(compact->buf_size)))
607         return AVERROR(ENOMEM);
608
609     if      (!strcmp(compact->escape_mode_str, "none")) compact->escape_str = none_escape_str;
610     else if (!strcmp(compact->escape_mode_str, "c"   )) compact->escape_str = c_escape_str;
611     else if (!strcmp(compact->escape_mode_str, "csv" )) compact->escape_str = csv_escape_str;
612     else {
613         av_log(wctx, AV_LOG_ERROR, "Unknown escape mode '%s'\n", compact->escape_mode_str);
614         return AVERROR(EINVAL);
615     }
616
617     return 0;
618 }
619
620 static av_cold void compact_uninit(WriterContext *wctx)
621 {
622     CompactContext *compact = wctx->priv;
623
624     av_freep(&compact->item_sep_str);
625     av_freep(&compact->buf);
626     av_freep(&compact->escape_mode_str);
627 }
628
629 static void compact_print_section_header(WriterContext *wctx, const char *section)
630 {
631     CompactContext *compact = wctx->priv;
632
633     printf("%s%c", section, compact->item_sep);
634 }
635
636 static void compact_print_section_footer(WriterContext *wctx, const char *section)
637 {
638     printf("\n");
639 }
640
641 static void compact_print_str(WriterContext *wctx, const char *key, const char *value)
642 {
643     CompactContext *compact = wctx->priv;
644
645     if (wctx->nb_item) printf("%c", compact->item_sep);
646     if (!compact->nokey)
647         printf("%s=", key);
648     printf("%s", compact->escape_str(&compact->buf, &compact->buf_size,
649                                      value, compact->item_sep, wctx));
650 }
651
652 static void compact_print_int(WriterContext *wctx, const char *key, int value)
653 {
654     CompactContext *compact = wctx->priv;
655
656     if (wctx->nb_item) printf("%c", compact->item_sep);
657     if (!compact->nokey)
658         printf("%s=", key);
659     printf("%d", value);
660 }
661
662 static void compact_show_tags(WriterContext *wctx, AVDictionary *dict)
663 {
664     CompactContext *compact = wctx->priv;
665     AVDictionaryEntry *tag = NULL;
666
667     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
668         if (wctx->nb_item) printf("%c", compact->item_sep);
669         if (!compact->nokey)
670             printf("tag:%s=", compact->escape_str(&compact->buf, &compact->buf_size,
671                                                   tag->key, compact->item_sep, wctx));
672         printf("%s", compact->escape_str(&compact->buf, &compact->buf_size,
673                                          tag->value, compact->item_sep, wctx));
674     }
675 }
676
677 static const Writer compact_writer = {
678     .name                 = "compact",
679     .priv_size            = sizeof(CompactContext),
680     .init                 = compact_init,
681     .uninit               = compact_uninit,
682     .print_section_header = compact_print_section_header,
683     .print_section_footer = compact_print_section_footer,
684     .print_integer        = compact_print_int,
685     .print_string         = compact_print_str,
686     .show_tags            = compact_show_tags,
687     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
688 };
689
690 /* CSV output */
691
692 static av_cold int csv_init(WriterContext *wctx, const char *args, void *opaque)
693 {
694     return compact_init(wctx, "item_sep=,:nokey=1:escape=csv", opaque);
695 }
696
697 static const Writer csv_writer = {
698     .name                 = "csv",
699     .priv_size            = sizeof(CompactContext),
700     .init                 = csv_init,
701     .uninit               = compact_uninit,
702     .print_section_header = compact_print_section_header,
703     .print_section_footer = compact_print_section_footer,
704     .print_integer        = compact_print_int,
705     .print_string         = compact_print_str,
706     .show_tags            = compact_show_tags,
707     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
708 };
709
710 /* JSON output */
711
712 typedef struct {
713     int multiple_entries; ///< tells if the given chapter requires multiple entries
714     char *buf;
715     size_t buf_size;
716 } JSONContext;
717
718 static av_cold int json_init(WriterContext *wctx, const char *args, void *opaque)
719 {
720     JSONContext *json = wctx->priv;
721
722     json->buf_size = ESCAPE_INIT_BUF_SIZE;
723     if (!(json->buf = av_malloc(json->buf_size)))
724         return AVERROR(ENOMEM);
725
726     return 0;
727 }
728
729 static av_cold void json_uninit(WriterContext *wctx)
730 {
731     JSONContext *json = wctx->priv;
732     av_freep(&json->buf);
733 }
734
735 static const char *json_escape_str(char **dst, size_t *dst_size, const char *src,
736                                    void *log_ctx)
737 {
738     static const char json_escape[] = {'"', '\\', '\b', '\f', '\n', '\r', '\t', 0};
739     static const char json_subst[]  = {'"', '\\',  'b',  'f',  'n',  'r',  't', 0};
740     const char *p;
741     char *q;
742     size_t size = 1;
743
744     // compute the length of the escaped string
745     for (p = src; *p; p++) {
746         ESCAPE_CHECK_SIZE(src, size, SIZE_MAX-6);
747         if (strchr(json_escape, *p))     size += 2; // simple escape
748         else if ((unsigned char)*p < 32) size += 6; // handle non-printable chars
749         else                             size += 1; // char copy
750     }
751     ESCAPE_REALLOC_BUF(dst_size, dst, src, size);
752
753     q = *dst;
754     for (p = src; *p; p++) {
755         char *s = strchr(json_escape, *p);
756         if (s) {
757             *q++ = '\\';
758             *q++ = json_subst[s - json_escape];
759         } else if ((unsigned char)*p < 32) {
760             snprintf(q, 7, "\\u00%02x", *p & 0xff);
761             q += 6;
762         } else {
763             *q++ = *p;
764         }
765     }
766     *q = 0;
767     return *dst;
768 }
769
770 static void json_print_header(WriterContext *wctx)
771 {
772     printf("{");
773 }
774
775 static void json_print_footer(WriterContext *wctx)
776 {
777     printf("\n}\n");
778 }
779
780 static void json_print_chapter_header(WriterContext *wctx, const char *chapter)
781 {
782     JSONContext *json = wctx->priv;
783
784     if (wctx->nb_chapter)
785         printf(",");
786     json->multiple_entries = !strcmp(chapter, "packets") || !strcmp(chapter, "streams");
787     printf("\n  \"%s\":%s", json_escape_str(&json->buf, &json->buf_size, chapter, wctx),
788            json->multiple_entries ? " [" : " ");
789 }
790
791 static void json_print_chapter_footer(WriterContext *wctx, const char *chapter)
792 {
793     JSONContext *json = wctx->priv;
794
795     if (json->multiple_entries)
796         printf("]");
797 }
798
799 static void json_print_section_header(WriterContext *wctx, const char *section)
800 {
801     if (wctx->nb_section) printf(",");
802     printf("{\n");
803 }
804
805 static void json_print_section_footer(WriterContext *wctx, const char *section)
806 {
807     printf("\n  }");
808 }
809
810 static inline void json_print_item_str(WriterContext *wctx,
811                                        const char *key, const char *value,
812                                        const char *indent)
813 {
814     JSONContext *json = wctx->priv;
815
816     printf("%s\"%s\":", indent, json_escape_str(&json->buf, &json->buf_size, key,   wctx));
817     printf(" \"%s\"",           json_escape_str(&json->buf, &json->buf_size, value, wctx));
818 }
819
820 #define INDENT "    "
821
822 static void json_print_str(WriterContext *wctx, const char *key, const char *value)
823 {
824     if (wctx->nb_item) printf(",\n");
825     json_print_item_str(wctx, key, value, INDENT);
826 }
827
828 static void json_print_int(WriterContext *wctx, const char *key, int value)
829 {
830     JSONContext *json = wctx->priv;
831
832     if (wctx->nb_item) printf(",\n");
833     printf(INDENT "\"%s\": %d",
834            json_escape_str(&json->buf, &json->buf_size, key, wctx), value);
835 }
836
837 static void json_show_tags(WriterContext *wctx, AVDictionary *dict)
838 {
839     AVDictionaryEntry *tag = NULL;
840     int is_first = 1;
841     if (!dict)
842         return;
843     printf(",\n" INDENT "\"tags\": {\n");
844     while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
845         if (is_first) is_first = 0;
846         else          printf(",\n");
847         json_print_item_str(wctx, tag->key, tag->value, INDENT INDENT);
848     }
849     printf("\n    }");
850 }
851
852 static const Writer json_writer = {
853     .name                 = "json",
854     .priv_size            = sizeof(JSONContext),
855     .init                 = json_init,
856     .uninit               = json_uninit,
857     .print_header         = json_print_header,
858     .print_footer         = json_print_footer,
859     .print_chapter_header = json_print_chapter_header,
860     .print_chapter_footer = json_print_chapter_footer,
861     .print_section_header = json_print_section_header,
862     .print_section_footer = json_print_section_footer,
863     .print_integer        = json_print_int,
864     .print_string         = json_print_str,
865     .show_tags            = json_show_tags,
866 };
867
868 static void writer_register_all(void)
869 {
870     static int initialized;
871
872     if (initialized)
873         return;
874     initialized = 1;
875
876     writer_register(&default_writer);
877     writer_register(&compact_writer);
878     writer_register(&csv_writer);
879     writer_register(&json_writer);
880 }
881
882 #define print_fmt(k, f, ...) do {              \
883     if (fast_asprintf(&pbuf, f, __VA_ARGS__))  \
884         writer_print_string(w, k, pbuf.s, 0);  \
885 } while (0)
886
887 #define print_fmt_opt(k, f, ...) do {          \
888     if (fast_asprintf(&pbuf, f, __VA_ARGS__))  \
889         writer_print_string(w, k, pbuf.s, 1);  \
890 } while (0)
891
892 #define print_int(k, v)         writer_print_integer(w, k, v)
893 #define print_str(k, v)         writer_print_string(w, k, v, 0)
894 #define print_str_opt(k, v)     writer_print_string(w, k, v, 1)
895 #define print_time(k, v, tb)    writer_print_time(w, k, v, tb)
896 #define print_ts(k, v)          writer_print_ts(w, k, v)
897 #define print_val(k, v, u)      writer_print_string(w, k, \
898     value_string(val_str, sizeof(val_str), (struct unit_value){.val.i = v, .unit=u}), 1)
899 #define print_section_header(s) writer_print_section_header(w, s)
900 #define print_section_footer(s) writer_print_section_footer(w, s)
901 #define show_tags(metadata)     writer_show_tags(w, metadata)
902
903 static void show_packet(WriterContext *w, AVFormatContext *fmt_ctx, AVPacket *pkt, int packet_idx)
904 {
905     char val_str[128];
906     AVStream *st = fmt_ctx->streams[pkt->stream_index];
907     struct print_buf pbuf = {.s = NULL};
908     const char *s;
909
910     print_section_header("packet");
911     s = av_get_media_type_string(st->codec->codec_type);
912     if (s) print_str    ("codec_type", s);
913     else   print_str_opt("codec_type", "unknown");
914     print_int("stream_index",     pkt->stream_index);
915     print_ts  ("pts",             pkt->pts);
916     print_time("pts_time",        pkt->pts, &st->time_base);
917     print_ts  ("dts",             pkt->dts);
918     print_time("dts_time",        pkt->dts, &st->time_base);
919     print_ts  ("duration",        pkt->duration);
920     print_time("duration_time",   pkt->duration, &st->time_base);
921     print_val("size",             pkt->size, unit_byte_str);
922     if (pkt->pos != -1) print_fmt    ("pos", "%"PRId64, pkt->pos);
923     else                print_str_opt("pos", "N/A");
924     print_fmt("flags", "%c",      pkt->flags & AV_PKT_FLAG_KEY ? 'K' : '_');
925     print_section_footer("packet");
926
927     av_free(pbuf.s);
928     fflush(stdout);
929 }
930
931 static void show_packets(WriterContext *w, AVFormatContext *fmt_ctx)
932 {
933     AVPacket pkt;
934     int i = 0;
935
936     av_init_packet(&pkt);
937
938     while (!av_read_frame(fmt_ctx, &pkt))
939         show_packet(w, fmt_ctx, &pkt, i++);
940 }
941
942 static void show_stream(WriterContext *w, AVFormatContext *fmt_ctx, int stream_idx)
943 {
944     AVStream *stream = fmt_ctx->streams[stream_idx];
945     AVCodecContext *dec_ctx;
946     AVCodec *dec;
947     char val_str[128];
948     const char *s;
949     AVRational display_aspect_ratio;
950     struct print_buf pbuf = {.s = NULL};
951
952     print_section_header("stream");
953
954     print_int("index", stream->index);
955
956     if ((dec_ctx = stream->codec)) {
957         if ((dec = dec_ctx->codec)) {
958             print_str("codec_name",      dec->name);
959             print_str("codec_long_name", dec->long_name);
960         } else {
961             print_str_opt("codec_name",      "unknown");
962             print_str_opt("codec_long_name", "unknown");
963         }
964
965         s = av_get_media_type_string(dec_ctx->codec_type);
966         if (s) print_str    ("codec_type", s);
967         else   print_str_opt("codec_type", "unknown");
968         print_fmt("codec_time_base", "%d/%d", dec_ctx->time_base.num, dec_ctx->time_base.den);
969
970         /* print AVI/FourCC tag */
971         av_get_codec_tag_string(val_str, sizeof(val_str), dec_ctx->codec_tag);
972         print_str("codec_tag_string",    val_str);
973         print_fmt("codec_tag", "0x%04x", dec_ctx->codec_tag);
974
975         switch (dec_ctx->codec_type) {
976         case AVMEDIA_TYPE_VIDEO:
977             print_int("width",        dec_ctx->width);
978             print_int("height",       dec_ctx->height);
979             print_int("has_b_frames", dec_ctx->has_b_frames);
980             if (dec_ctx->sample_aspect_ratio.num) {
981                 print_fmt("sample_aspect_ratio", "%d:%d",
982                           dec_ctx->sample_aspect_ratio.num,
983                           dec_ctx->sample_aspect_ratio.den);
984                 av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
985                           dec_ctx->width  * dec_ctx->sample_aspect_ratio.num,
986                           dec_ctx->height * dec_ctx->sample_aspect_ratio.den,
987                           1024*1024);
988                 print_fmt("display_aspect_ratio", "%d:%d",
989                           display_aspect_ratio.num,
990                           display_aspect_ratio.den);
991             } else {
992                 print_str_opt("sample_aspect_ratio", "N/A");
993                 print_str_opt("display_aspect_ratio", "N/A");
994             }
995             s = av_get_pix_fmt_name(dec_ctx->pix_fmt);
996             if (s) print_str    ("pix_fmt", s);
997             else   print_str_opt("pix_fmt", "unknown");
998             print_int("level",   dec_ctx->level);
999             break;
1000
1001         case AVMEDIA_TYPE_AUDIO:
1002             s = av_get_sample_fmt_name(dec_ctx->sample_fmt);
1003             if (s) print_str    ("sample_fmt", s);
1004             else   print_str_opt("sample_fmt", "unknown");
1005             print_val("sample_rate",     dec_ctx->sample_rate, unit_hertz_str);
1006             print_int("channels",        dec_ctx->channels);
1007             print_int("bits_per_sample", av_get_bits_per_sample(dec_ctx->codec_id));
1008             break;
1009         }
1010     } else {
1011         print_str_opt("codec_type", "unknown");
1012     }
1013     if (dec_ctx->codec && dec_ctx->codec->priv_class) {
1014         const AVOption *opt = NULL;
1015         while (opt = av_opt_next(dec_ctx->priv_data,opt)) {
1016             uint8_t *str;
1017             if (opt->flags) continue;
1018             if (av_opt_get(dec_ctx->priv_data, opt->name, 0, &str) >= 0) {
1019                 print_str(opt->name, str);
1020                 av_free(str);
1021             }
1022         }
1023     }
1024
1025     if (fmt_ctx->iformat->flags & AVFMT_SHOW_IDS) print_fmt    ("id", "0x%x", stream->id);
1026     else                                          print_str_opt("id", "N/A");
1027     print_fmt("r_frame_rate",   "%d/%d", stream->r_frame_rate.num,   stream->r_frame_rate.den);
1028     print_fmt("avg_frame_rate", "%d/%d", stream->avg_frame_rate.num, stream->avg_frame_rate.den);
1029     print_fmt("time_base",      "%d/%d", stream->time_base.num,      stream->time_base.den);
1030     print_time("start_time",    stream->start_time, &stream->time_base);
1031     print_time("duration",      stream->duration,   &stream->time_base);
1032     if (stream->nb_frames) print_fmt    ("nb_frames", "%"PRId64, stream->nb_frames);
1033     else                   print_str_opt("nb_frames", "N/A");
1034     show_tags(stream->metadata);
1035
1036     print_section_footer("stream");
1037     av_free(pbuf.s);
1038     fflush(stdout);
1039 }
1040
1041 static void show_streams(WriterContext *w, AVFormatContext *fmt_ctx)
1042 {
1043     int i;
1044     for (i = 0; i < fmt_ctx->nb_streams; i++)
1045         show_stream(w, fmt_ctx, i);
1046 }
1047
1048 static void show_format(WriterContext *w, AVFormatContext *fmt_ctx)
1049 {
1050     char val_str[128];
1051     int64_t size = avio_size(fmt_ctx->pb);
1052     struct print_buf pbuf = {.s = NULL};
1053
1054     print_section_header("format");
1055     print_str("filename",         fmt_ctx->filename);
1056     print_int("nb_streams",       fmt_ctx->nb_streams);
1057     print_str("format_name",      fmt_ctx->iformat->name);
1058     print_str("format_long_name", fmt_ctx->iformat->long_name);
1059     print_time("start_time",      fmt_ctx->start_time, &AV_TIME_BASE_Q);
1060     print_time("duration",        fmt_ctx->duration,   &AV_TIME_BASE_Q);
1061     if (size >= 0) print_val    ("size", size, unit_byte_str);
1062     else           print_str_opt("size", "N/A");
1063     if (fmt_ctx->bit_rate > 0) print_val    ("bit_rate", fmt_ctx->bit_rate, unit_bit_per_second_str);
1064     else                       print_str_opt("bit_rate", "N/A");
1065     show_tags(fmt_ctx->metadata);
1066     print_section_footer("format");
1067     av_free(pbuf.s);
1068     fflush(stdout);
1069 }
1070
1071 static int open_input_file(AVFormatContext **fmt_ctx_ptr, const char *filename)
1072 {
1073     int err, i;
1074     AVFormatContext *fmt_ctx = NULL;
1075     AVDictionaryEntry *t;
1076
1077     if ((err = avformat_open_input(&fmt_ctx, filename, iformat, &format_opts)) < 0) {
1078         print_error(filename, err);
1079         return err;
1080     }
1081     if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
1082         av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
1083         return AVERROR_OPTION_NOT_FOUND;
1084     }
1085
1086
1087     /* fill the streams in the format context */
1088     if ((err = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
1089         print_error(filename, err);
1090         return err;
1091     }
1092
1093     av_dump_format(fmt_ctx, 0, filename, 0);
1094
1095     /* bind a decoder to each input stream */
1096     for (i = 0; i < fmt_ctx->nb_streams; i++) {
1097         AVStream *stream = fmt_ctx->streams[i];
1098         AVCodec *codec;
1099
1100         if (!(codec = avcodec_find_decoder(stream->codec->codec_id))) {
1101             fprintf(stderr, "Unsupported codec with id %d for input stream %d\n",
1102                     stream->codec->codec_id, stream->index);
1103         } else if (avcodec_open2(stream->codec, codec, NULL) < 0) {
1104             fprintf(stderr, "Error while opening codec for input stream %d\n",
1105                     stream->index);
1106         }
1107     }
1108
1109     *fmt_ctx_ptr = fmt_ctx;
1110     return 0;
1111 }
1112
1113 #define PRINT_CHAPTER(name) do {                                        \
1114     if (do_show_ ## name) {                                             \
1115         writer_print_chapter_header(wctx, #name);                       \
1116         show_ ## name (wctx, fmt_ctx);                                  \
1117         writer_print_chapter_footer(wctx, #name);                       \
1118     }                                                                   \
1119 } while (0)
1120
1121 static int probe_file(const char *filename)
1122 {
1123     AVFormatContext *fmt_ctx;
1124     int ret;
1125     const Writer *w;
1126     char *buf;
1127     char *w_name = NULL, *w_args = NULL;
1128     WriterContext *wctx;
1129
1130     writer_register_all();
1131
1132     if (!print_format)
1133         print_format = av_strdup("default");
1134     w_name = av_strtok(print_format, "=", &buf);
1135     w_args = buf;
1136
1137     w = writer_get_by_name(w_name);
1138     if (!w) {
1139         av_log(NULL, AV_LOG_ERROR, "Unknown output format with name '%s'\n", w_name);
1140         ret = AVERROR(EINVAL);
1141         goto end;
1142     }
1143
1144     if ((ret = writer_open(&wctx, w, w_args, NULL)) < 0)
1145         goto end;
1146     if ((ret = open_input_file(&fmt_ctx, filename)))
1147         goto end;
1148
1149     writer_print_header(wctx);
1150     PRINT_CHAPTER(packets);
1151     PRINT_CHAPTER(streams);
1152     PRINT_CHAPTER(format);
1153     writer_print_footer(wctx);
1154
1155     av_close_input_file(fmt_ctx);
1156     writer_close(&wctx);
1157
1158 end:
1159     av_freep(&print_format);
1160
1161     return ret;
1162 }
1163
1164 static void show_usage(void)
1165 {
1166     printf("Simple multimedia streams analyzer\n");
1167     printf("usage: %s [OPTIONS] [INPUT_FILE]\n", program_name);
1168     printf("\n");
1169 }
1170
1171 static int opt_format(const char *opt, const char *arg)
1172 {
1173     iformat = av_find_input_format(arg);
1174     if (!iformat) {
1175         fprintf(stderr, "Unknown input format: %s\n", arg);
1176         return AVERROR(EINVAL);
1177     }
1178     return 0;
1179 }
1180
1181 static void opt_input_file(void *optctx, const char *arg)
1182 {
1183     if (input_filename) {
1184         fprintf(stderr, "Argument '%s' provided as input filename, but '%s' was already specified.\n",
1185                 arg, input_filename);
1186         exit(1);
1187     }
1188     if (!strcmp(arg, "-"))
1189         arg = "pipe:";
1190     input_filename = arg;
1191 }
1192
1193 static int opt_help(const char *opt, const char *arg)
1194 {
1195     av_log_set_callback(log_callback_help);
1196     show_usage();
1197     show_help_options(options, "Main options:\n", 0, 0);
1198     printf("\n");
1199
1200     show_help_children(avformat_get_class(), AV_OPT_FLAG_DECODING_PARAM);
1201
1202     return 0;
1203 }
1204
1205 static int opt_pretty(const char *opt, const char *arg)
1206 {
1207     show_value_unit              = 1;
1208     use_value_prefix             = 1;
1209     use_byte_value_binary_prefix = 1;
1210     use_value_sexagesimal_format = 1;
1211     return 0;
1212 }
1213
1214 static const OptionDef options[] = {
1215 #include "cmdutils_common_opts.h"
1216     { "f", HAS_ARG, {(void*)opt_format}, "force format", "format" },
1217     { "unit", OPT_BOOL, {(void*)&show_value_unit}, "show unit of the displayed values" },
1218     { "prefix", OPT_BOOL, {(void*)&use_value_prefix}, "use SI prefixes for the displayed values" },
1219     { "byte_binary_prefix", OPT_BOOL, {(void*)&use_byte_value_binary_prefix},
1220       "use binary prefixes for byte units" },
1221     { "sexagesimal", OPT_BOOL,  {(void*)&use_value_sexagesimal_format},
1222       "use sexagesimal format HOURS:MM:SS.MICROSECONDS for time units" },
1223     { "pretty", 0, {(void*)&opt_pretty},
1224       "prettify the format of displayed values, make it more human readable" },
1225     { "print_format", OPT_STRING | HAS_ARG, {(void*)&print_format},
1226       "set the output printing format (available formats are: default, compact, csv, json)", "format" },
1227     { "show_format",  OPT_BOOL, {(void*)&do_show_format} , "show format/container info" },
1228     { "show_packets", OPT_BOOL, {(void*)&do_show_packets}, "show packets info" },
1229     { "show_streams", OPT_BOOL, {(void*)&do_show_streams}, "show streams info" },
1230     { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
1231     { "i", HAS_ARG, {(void *)opt_input_file}, "read specified file", "input_file"},
1232     { NULL, },
1233 };
1234
1235 int main(int argc, char **argv)
1236 {
1237     int ret;
1238
1239     parse_loglevel(argc, argv, options);
1240     av_register_all();
1241     avformat_network_init();
1242     init_opts();
1243 #if CONFIG_AVDEVICE
1244     avdevice_register_all();
1245 #endif
1246
1247     show_banner();
1248     parse_options(NULL, argc, argv, options, opt_input_file);
1249
1250     if (!input_filename) {
1251         show_usage();
1252         fprintf(stderr, "You have to specify one input file.\n");
1253         fprintf(stderr, "Use -h to get full help or, even better, run 'man %s'.\n", program_name);
1254         exit(1);
1255     }
1256
1257     ret = probe_file(input_filename);
1258
1259     avformat_network_deinit();
1260
1261     return ret;
1262 }