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