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