]> git.sesse.net Git - ffmpeg/blob - ffprobe.c
ffprobe: simplify/fix logic for the -show_format_entry option
[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     int is_fmt_chapter;             ///< tells if the current chapter is "format", required by the print_format_entry option
183 };
184
185 static const char *writer_get_name(void *p)
186 {
187     WriterContext *wctx = p;
188     return wctx->writer->name;
189 }
190
191 static const AVClass writer_class = {
192     "Writer",
193     writer_get_name,
194     NULL,
195     LIBAVUTIL_VERSION_INT,
196 };
197
198 static void writer_close(WriterContext **wctx)
199 {
200     if (!*wctx)
201         return;
202
203     if ((*wctx)->writer->uninit)
204         (*wctx)->writer->uninit(*wctx);
205     av_freep(&((*wctx)->priv));
206     av_freep(wctx);
207 }
208
209 static int writer_open(WriterContext **wctx, const Writer *writer,
210                        const char *args, void *opaque)
211 {
212     int ret = 0;
213
214     if (!(*wctx = av_malloc(sizeof(WriterContext)))) {
215         ret = AVERROR(ENOMEM);
216         goto fail;
217     }
218
219     if (!((*wctx)->priv = av_mallocz(writer->priv_size))) {
220         ret = AVERROR(ENOMEM);
221         goto fail;
222     }
223
224     (*wctx)->class = &writer_class;
225     (*wctx)->writer = writer;
226     if ((*wctx)->writer->init)
227         ret = (*wctx)->writer->init(*wctx, args, opaque);
228     if (ret < 0)
229         goto fail;
230
231     return 0;
232
233 fail:
234     writer_close(wctx);
235     return ret;
236 }
237
238 static inline void writer_print_header(WriterContext *wctx)
239 {
240     if (wctx->writer->print_header)
241         wctx->writer->print_header(wctx);
242     wctx->nb_chapter = 0;
243 }
244
245 static inline void writer_print_footer(WriterContext *wctx)
246 {
247     if (wctx->writer->print_footer)
248         wctx->writer->print_footer(wctx);
249 }
250
251 static inline void writer_print_chapter_header(WriterContext *wctx,
252                                                const char *chapter)
253 {
254     if (wctx->writer->print_chapter_header)
255         wctx->writer->print_chapter_header(wctx, chapter);
256     wctx->nb_section = 0;
257
258     wctx->is_fmt_chapter = !strcmp(chapter, "format");
259 }
260
261 static inline void writer_print_chapter_footer(WriterContext *wctx,
262                                                const char *chapter)
263 {
264     if (wctx->writer->print_chapter_footer)
265         wctx->writer->print_chapter_footer(wctx, chapter);
266     wctx->nb_chapter++;
267 }
268
269 static inline void writer_print_section_header(WriterContext *wctx,
270                                                const char *section)
271 {
272     if (wctx->writer->print_section_header)
273         wctx->writer->print_section_header(wctx, section);
274     wctx->nb_item = 0;
275 }
276
277 static inline void writer_print_section_footer(WriterContext *wctx,
278                                                const char *section)
279 {
280     if (wctx->writer->print_section_footer)
281         wctx->writer->print_section_footer(wctx, section);
282     wctx->nb_section++;
283 }
284
285 static inline void writer_print_integer(WriterContext *wctx,
286                                         const char *key, long long int val)
287 {
288     if (!wctx->is_fmt_chapter || !fmt_entries_to_show || 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 (!wctx->is_fmt_chapter || !fmt_entries_to_show || 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 (!wctx->is_fmt_chapter || !fmt_entries_to_show || 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 show_format(WriterContext *w, AVFormatContext *fmt_ctx)
1445 {
1446     char val_str[128];
1447     int64_t size = fmt_ctx->pb ? avio_size(fmt_ctx->pb) : -1;
1448
1449     print_section_header("format");
1450     print_str("filename",         fmt_ctx->filename);
1451     print_int("nb_streams",       fmt_ctx->nb_streams);
1452     print_str("format_name",      fmt_ctx->iformat->name);
1453     print_str("format_long_name", fmt_ctx->iformat->long_name);
1454     print_time("start_time",      fmt_ctx->start_time, &AV_TIME_BASE_Q);
1455     print_time("duration",        fmt_ctx->duration,   &AV_TIME_BASE_Q);
1456     if (size >= 0) print_val    ("size", size, unit_byte_str);
1457     else           print_str_opt("size", "N/A");
1458     if (fmt_ctx->bit_rate > 0) print_val    ("bit_rate", fmt_ctx->bit_rate, unit_bit_per_second_str);
1459     else                       print_str_opt("bit_rate", "N/A");
1460     show_tags(fmt_ctx->metadata);
1461     print_section_footer("format");
1462     fflush(stdout);
1463 }
1464
1465 static void show_error(WriterContext *w, int err)
1466 {
1467     char errbuf[128];
1468     const char *errbuf_ptr = errbuf;
1469
1470     if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
1471         errbuf_ptr = strerror(AVUNERROR(err));
1472
1473     writer_print_chapter_header(w, "error");
1474     print_section_header("error");
1475     print_int("code", err);
1476     print_str("string", errbuf_ptr);
1477     print_section_footer("error");
1478     writer_print_chapter_footer(w, "error");
1479 }
1480
1481 static int open_input_file(AVFormatContext **fmt_ctx_ptr, const char *filename)
1482 {
1483     int err, i;
1484     AVFormatContext *fmt_ctx = NULL;
1485     AVDictionaryEntry *t;
1486
1487     if ((err = avformat_open_input(&fmt_ctx, filename,
1488                                    iformat, &format_opts)) < 0) {
1489         print_error(filename, err);
1490         return err;
1491     }
1492     if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
1493         av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
1494         return AVERROR_OPTION_NOT_FOUND;
1495     }
1496
1497
1498     /* fill the streams in the format context */
1499     if ((err = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
1500         print_error(filename, err);
1501         return err;
1502     }
1503
1504     av_dump_format(fmt_ctx, 0, filename, 0);
1505
1506     /* bind a decoder to each input stream */
1507     for (i = 0; i < fmt_ctx->nb_streams; i++) {
1508         AVStream *stream = fmt_ctx->streams[i];
1509         AVCodec *codec;
1510
1511         if (!(codec = avcodec_find_decoder(stream->codec->codec_id))) {
1512             av_log(NULL, AV_LOG_ERROR,
1513                     "Unsupported codec with id %d for input stream %d\n",
1514                     stream->codec->codec_id, stream->index);
1515         } else if (avcodec_open2(stream->codec, codec, NULL) < 0) {
1516             av_log(NULL, AV_LOG_ERROR, "Error while opening codec for input stream %d\n",
1517                    stream->index);
1518         }
1519     }
1520
1521     *fmt_ctx_ptr = fmt_ctx;
1522     return 0;
1523 }
1524
1525 #define PRINT_CHAPTER(name) do {                                        \
1526     if (do_show_ ## name) {                                             \
1527         writer_print_chapter_header(wctx, #name);                       \
1528         show_ ## name (wctx, fmt_ctx);                                  \
1529         writer_print_chapter_footer(wctx, #name);                       \
1530     }                                                                   \
1531 } while (0)
1532
1533 static int probe_file(WriterContext *wctx, const char *filename)
1534 {
1535     AVFormatContext *fmt_ctx;
1536     int ret, i;
1537
1538     do_read_frames = do_show_frames || do_count_frames;
1539     do_read_packets = do_show_packets || do_count_packets;
1540
1541     ret = open_input_file(&fmt_ctx, filename);
1542     if (ret >= 0) {
1543         nb_streams_frames  = av_calloc(fmt_ctx->nb_streams, sizeof(*nb_streams_frames));
1544         nb_streams_packets = av_calloc(fmt_ctx->nb_streams, sizeof(*nb_streams_packets));
1545         if (do_read_frames || do_read_packets) {
1546             const char *chapter;
1547             if (do_show_frames && do_show_packets &&
1548                 wctx->writer->flags & WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER)
1549                 chapter = "packets_and_frames";
1550             else if (do_show_packets && !do_show_frames)
1551                 chapter = "packets";
1552             else // (!do_show_packets && do_show_frames)
1553                 chapter = "frames";
1554             if (do_show_frames || do_show_packets)
1555                 writer_print_chapter_header(wctx, chapter);
1556             read_packets(wctx, fmt_ctx);
1557             if (do_show_frames || do_show_packets)
1558                 writer_print_chapter_footer(wctx, chapter);
1559         }
1560         PRINT_CHAPTER(streams);
1561         PRINT_CHAPTER(format);
1562         for (i = 0; i < fmt_ctx->nb_streams; i++)
1563             if (fmt_ctx->streams[i]->codec->codec_id != CODEC_ID_NONE)
1564                 avcodec_close(fmt_ctx->streams[i]->codec);
1565         avformat_close_input(&fmt_ctx);
1566         av_freep(&nb_streams_frames);
1567         av_freep(&nb_streams_packets);
1568     }
1569     return ret;
1570 }
1571
1572 static void show_usage(void)
1573 {
1574     av_log(NULL, AV_LOG_INFO, "Simple multimedia streams analyzer\n");
1575     av_log(NULL, AV_LOG_INFO, "usage: %s [OPTIONS] [INPUT_FILE]\n", program_name);
1576     av_log(NULL, AV_LOG_INFO, "\n");
1577 }
1578
1579 static void ffprobe_show_program_version(WriterContext *w)
1580 {
1581     struct print_buf pbuf = {.s = NULL};
1582
1583     writer_print_chapter_header(w, "program_version");
1584     print_section_header("program_version");
1585     print_str("version", FFMPEG_VERSION);
1586     print_fmt("copyright", "Copyright (c) %d-%d the FFmpeg developers",
1587               program_birth_year, this_year);
1588     print_str("build_date", __DATE__);
1589     print_str("build_time", __TIME__);
1590     print_str("compiler_type", CC_TYPE);
1591     print_str("compiler_version", CC_VERSION);
1592     print_str("configuration", FFMPEG_CONFIGURATION);
1593     print_section_footer("program_version");
1594     writer_print_chapter_footer(w, "program_version");
1595
1596     av_free(pbuf.s);
1597 }
1598
1599 #define SHOW_LIB_VERSION(libname, LIBNAME)                              \
1600     do {                                                                \
1601         if (CONFIG_##LIBNAME) {                                         \
1602             unsigned int version = libname##_version();                 \
1603             print_section_header("library_version");                    \
1604             print_str("name",    "lib" #libname);                       \
1605             print_int("major",   LIB##LIBNAME##_VERSION_MAJOR);         \
1606             print_int("minor",   LIB##LIBNAME##_VERSION_MINOR);         \
1607             print_int("micro",   LIB##LIBNAME##_VERSION_MICRO);         \
1608             print_int("version", version);                              \
1609             print_section_footer("library_version");                    \
1610         }                                                               \
1611     } while (0)
1612
1613 static void ffprobe_show_library_versions(WriterContext *w)
1614 {
1615     writer_print_chapter_header(w, "library_versions");
1616     SHOW_LIB_VERSION(avutil,     AVUTIL);
1617     SHOW_LIB_VERSION(avcodec,    AVCODEC);
1618     SHOW_LIB_VERSION(avformat,   AVFORMAT);
1619     SHOW_LIB_VERSION(avdevice,   AVDEVICE);
1620     SHOW_LIB_VERSION(avfilter,   AVFILTER);
1621     SHOW_LIB_VERSION(swscale,    SWSCALE);
1622     SHOW_LIB_VERSION(swresample, SWRESAMPLE);
1623     SHOW_LIB_VERSION(postproc,   POSTPROC);
1624     writer_print_chapter_footer(w, "library_versions");
1625 }
1626
1627 static int opt_format(const char *opt, const char *arg)
1628 {
1629     iformat = av_find_input_format(arg);
1630     if (!iformat) {
1631         av_log(NULL, AV_LOG_ERROR, "Unknown input format: %s\n", arg);
1632         return AVERROR(EINVAL);
1633     }
1634     return 0;
1635 }
1636
1637 static int opt_show_format_entry(const char *opt, const char *arg)
1638 {
1639     do_show_format = 1;
1640     av_dict_set(&fmt_entries_to_show, arg, "", 0);
1641     return 0;
1642 }
1643
1644 static void opt_input_file(void *optctx, const char *arg)
1645 {
1646     if (input_filename) {
1647         av_log(NULL, AV_LOG_ERROR,
1648                 "Argument '%s' provided as input filename, but '%s' was already specified.\n",
1649                 arg, input_filename);
1650         exit(1);
1651     }
1652     if (!strcmp(arg, "-"))
1653         arg = "pipe:";
1654     input_filename = arg;
1655 }
1656
1657 static int opt_help(const char *opt, const char *arg)
1658 {
1659     av_log_set_callback(log_callback_help);
1660     show_usage();
1661     show_help_options(options, "Main options:\n", 0, 0);
1662     printf("\n");
1663
1664     show_help_children(avformat_get_class(), AV_OPT_FLAG_DECODING_PARAM);
1665
1666     return 0;
1667 }
1668
1669 static int opt_pretty(const char *opt, const char *arg)
1670 {
1671     show_value_unit              = 1;
1672     use_value_prefix             = 1;
1673     use_byte_value_binary_prefix = 1;
1674     use_value_sexagesimal_format = 1;
1675     return 0;
1676 }
1677
1678 static int opt_show_versions(const char *opt, const char *arg)
1679 {
1680     do_show_program_version  = 1;
1681     do_show_library_versions = 1;
1682     return 0;
1683 }
1684
1685 static const OptionDef options[] = {
1686 #include "cmdutils_common_opts.h"
1687     { "f", HAS_ARG, {(void*)opt_format}, "force format", "format" },
1688     { "unit", OPT_BOOL, {(void*)&show_value_unit}, "show unit of the displayed values" },
1689     { "prefix", OPT_BOOL, {(void*)&use_value_prefix}, "use SI prefixes for the displayed values" },
1690     { "byte_binary_prefix", OPT_BOOL, {(void*)&use_byte_value_binary_prefix},
1691       "use binary prefixes for byte units" },
1692     { "sexagesimal", OPT_BOOL,  {(void*)&use_value_sexagesimal_format},
1693       "use sexagesimal format HOURS:MM:SS.MICROSECONDS for time units" },
1694     { "pretty", 0, {(void*)&opt_pretty},
1695       "prettify the format of displayed values, make it more human readable" },
1696     { "print_format", OPT_STRING | HAS_ARG, {(void*)&print_format},
1697       "set the output printing format (available formats are: default, compact, csv, json, xml)", "format" },
1698     { "show_error",   OPT_BOOL, {(void*)&do_show_error} ,  "show probing error" },
1699     { "show_format",  OPT_BOOL, {(void*)&do_show_format} , "show format/container info" },
1700     { "show_frames",  OPT_BOOL, {(void*)&do_show_frames} , "show frames info" },
1701     { "show_format_entry", HAS_ARG, {(void*)opt_show_format_entry},
1702       "show a particular entry from the format/container info", "entry" },
1703     { "show_packets", OPT_BOOL, {(void*)&do_show_packets}, "show packets info" },
1704     { "show_streams", OPT_BOOL, {(void*)&do_show_streams}, "show streams info" },
1705     { "count_frames", OPT_BOOL, {(void*)&do_count_frames}, "count the number of frames per stream" },
1706     { "count_packets", OPT_BOOL, {(void*)&do_count_packets}, "count the number of packets per stream" },
1707     { "show_program_version",  OPT_BOOL, {(void*)&do_show_program_version},  "show ffprobe version" },
1708     { "show_library_versions", OPT_BOOL, {(void*)&do_show_library_versions}, "show library versions" },
1709     { "show_versions",         0, {(void*)&opt_show_versions}, "show program and library versions" },
1710     { "show_private_data", OPT_BOOL, {(void*)&show_private_data}, "show private data" },
1711     { "private",           OPT_BOOL, {(void*)&show_private_data}, "same as show_private_data" },
1712     { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
1713     { "i", HAS_ARG, {(void *)opt_input_file}, "read specified file", "input_file"},
1714     { NULL, },
1715 };
1716
1717 int main(int argc, char **argv)
1718 {
1719     const Writer *w;
1720     WriterContext *wctx;
1721     char *buf;
1722     char *w_name = NULL, *w_args = NULL;
1723     int ret;
1724
1725     av_log_set_flags(AV_LOG_SKIP_REPEATED);
1726     parse_loglevel(argc, argv, options);
1727     av_register_all();
1728     avformat_network_init();
1729     init_opts();
1730 #if CONFIG_AVDEVICE
1731     avdevice_register_all();
1732 #endif
1733
1734     show_banner(argc, argv, options);
1735     parse_options(NULL, argc, argv, options, opt_input_file);
1736
1737     writer_register_all();
1738
1739     if (!print_format)
1740         print_format = av_strdup("default");
1741     w_name = av_strtok(print_format, "=", &buf);
1742     w_args = buf;
1743
1744     w = writer_get_by_name(w_name);
1745     if (!w) {
1746         av_log(NULL, AV_LOG_ERROR, "Unknown output format with name '%s'\n", w_name);
1747         ret = AVERROR(EINVAL);
1748         goto end;
1749     }
1750
1751     if ((ret = writer_open(&wctx, w, w_args, NULL)) >= 0) {
1752         writer_print_header(wctx);
1753
1754         if (do_show_program_version)
1755             ffprobe_show_program_version(wctx);
1756         if (do_show_library_versions)
1757             ffprobe_show_library_versions(wctx);
1758
1759         if (!input_filename &&
1760             ((do_show_format || do_show_streams || do_show_packets || do_show_error) ||
1761              (!do_show_program_version && !do_show_library_versions))) {
1762             show_usage();
1763             av_log(NULL, AV_LOG_ERROR, "You have to specify one input file.\n");
1764             av_log(NULL, AV_LOG_ERROR, "Use -h to get full help or, even better, run 'man %s'.\n", program_name);
1765             ret = AVERROR(EINVAL);
1766         } else if (input_filename) {
1767             ret = probe_file(wctx, input_filename);
1768             if (ret < 0 && do_show_error)
1769                 show_error(wctx, ret);
1770         }
1771
1772         writer_print_footer(wctx);
1773         writer_close(&wctx);
1774     }
1775
1776 end:
1777     av_freep(&print_format);
1778     avformat_network_deinit();
1779
1780     return ret;
1781 }