]> git.sesse.net Git - ffmpeg/blob - ffprobe.c
Merge commit '1b891d17c531e8a63c2974aab4bf997ce70746f3'
[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 <string.h>
30
31 #include "libavformat/avformat.h"
32 #include "libavcodec/avcodec.h"
33 #include "libavutil/avassert.h"
34 #include "libavutil/avstring.h"
35 #include "libavutil/bprint.h"
36 #include "libavutil/opt.h"
37 #include "libavutil/pixdesc.h"
38 #include "libavutil/dict.h"
39 #include "libavutil/libm.h"
40 #include "libavutil/timecode.h"
41 #include "libavdevice/avdevice.h"
42 #include "libswscale/swscale.h"
43 #include "libswresample/swresample.h"
44 #include "libpostproc/postprocess.h"
45 #include "cmdutils.h"
46
47 const char program_name[] = "ffprobe";
48 const int program_birth_year = 2007;
49
50 static int do_bitexact = 0;
51 static int do_count_frames = 0;
52 static int do_count_packets = 0;
53 static int do_read_frames  = 0;
54 static int do_read_packets = 0;
55 static int do_show_error   = 0;
56 static int do_show_format  = 0;
57 static int do_show_frames  = 0;
58 static AVDictionary *fmt_entries_to_show = NULL;
59 static int do_show_packets = 0;
60 static int do_show_streams = 0;
61 static int do_show_data    = 0;
62 static int do_show_program_version  = 0;
63 static int do_show_library_versions = 0;
64
65 static int show_value_unit              = 0;
66 static int use_value_prefix             = 0;
67 static int use_byte_value_binary_prefix = 0;
68 static int use_value_sexagesimal_format = 0;
69 static int show_private_data            = 1;
70
71 static char *print_format;
72 static char *stream_specifier;
73
74 /* section structure definition */
75
76 struct section {
77     int id;             ///< unique id indentifying a section
78     const char *name;
79
80 #define SECTION_FLAG_IS_WRAPPER      1 ///< the section only contains other sections, but has no data at its own level
81 #define SECTION_FLAG_IS_ARRAY        2 ///< the section contains an array of elements of the same type
82 #define SECTION_FLAG_HAS_VARIABLE_FIELDS 4 ///< the section may contain a variable number of fields with variable keys.
83                                            ///  For these sections the element_name field is mandatory.
84     int flags;
85     const char *element_name; ///< name of the contained element, if provided
86 };
87
88 typedef enum {
89     SECTION_ID_NONE = -1,
90     SECTION_ID_ERROR,
91     SECTION_ID_FORMAT,
92     SECTION_ID_FORMAT_TAGS,
93     SECTION_ID_FRAME,
94     SECTION_ID_FRAMES,
95     SECTION_ID_FRAME_TAGS,
96     SECTION_ID_LIBRARY_VERSION,
97     SECTION_ID_LIBRARY_VERSIONS,
98     SECTION_ID_PACKET,
99     SECTION_ID_PACKETS,
100     SECTION_ID_PACKETS_AND_FRAMES,
101     SECTION_ID_PROGRAM_VERSION,
102     SECTION_ID_ROOT,
103     SECTION_ID_STREAM,
104     SECTION_ID_STREAM_DISPOSITION,
105     SECTION_ID_STREAMS,
106     SECTION_ID_STREAM_TAGS
107 } SectionID;
108
109 static const struct section sections[] = {
110     [SECTION_ID_ERROR] =              { SECTION_ID_ERROR,              "error" },
111     [SECTION_ID_FORMAT] =             { SECTION_ID_FORMAT,             "format" },
112     [SECTION_ID_FORMAT_TAGS] =        { SECTION_ID_FORMAT_TAGS,        "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, .element_name = "tag" },
113     [SECTION_ID_FRAME] =              { SECTION_ID_FRAME,              "frame" },
114     [SECTION_ID_FRAMES] =             { SECTION_ID_FRAMES,             "frames", SECTION_FLAG_IS_ARRAY },
115     [SECTION_ID_FRAME_TAGS] =         { SECTION_ID_FRAME_TAGS,         "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, .element_name = "tag" },
116     [SECTION_ID_LIBRARY_VERSION] =    { SECTION_ID_LIBRARY_VERSION,    "library_version" },
117     [SECTION_ID_LIBRARY_VERSIONS] =   { SECTION_ID_LIBRARY_VERSIONS,   "library_versions", SECTION_FLAG_IS_ARRAY },
118     [SECTION_ID_PACKET] =             { SECTION_ID_PACKET,             "packet" },
119     [SECTION_ID_PACKETS] =            { SECTION_ID_PACKETS,            "packets", SECTION_FLAG_IS_ARRAY },
120     [SECTION_ID_PACKETS_AND_FRAMES] = { SECTION_ID_PACKETS_AND_FRAMES, "packets_and_frames", SECTION_FLAG_IS_ARRAY },
121     [SECTION_ID_PROGRAM_VERSION] =    { SECTION_ID_PROGRAM_VERSION,    "program_version" },
122     [SECTION_ID_ROOT] =               { SECTION_ID_ROOT,               "root", SECTION_FLAG_IS_WRAPPER },
123     [SECTION_ID_STREAM] =             { SECTION_ID_STREAM,             "stream" },
124     [SECTION_ID_STREAM_DISPOSITION] = { SECTION_ID_STREAM_DISPOSITION, "disposition" },
125     [SECTION_ID_STREAMS] =            { SECTION_ID_STREAMS,            "streams", SECTION_FLAG_IS_ARRAY },
126     [SECTION_ID_STREAM_TAGS] =        { SECTION_ID_STREAM_TAGS,        "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, .element_name = "tag" },
127 };
128
129 static const OptionDef *options;
130
131 /* FFprobe context */
132 static const char *input_filename;
133 static AVInputFormat *iformat = NULL;
134
135 static const char *const binary_unit_prefixes [] = { "", "Ki", "Mi", "Gi", "Ti", "Pi" };
136 static const char *const decimal_unit_prefixes[] = { "", "K" , "M" , "G" , "T" , "P"  };
137
138 static const char unit_second_str[]         = "s"    ;
139 static const char unit_hertz_str[]          = "Hz"   ;
140 static const char unit_byte_str[]           = "byte" ;
141 static const char unit_bit_per_second_str[] = "bit/s";
142
143 static uint64_t *nb_streams_packets;
144 static uint64_t *nb_streams_frames;
145 static int *selected_streams;
146
147 static void exit_program(void)
148 {
149     av_dict_free(&fmt_entries_to_show);
150 }
151
152 struct unit_value {
153     union { double d; long long int i; } val;
154     const char *unit;
155 };
156
157 static char *value_string(char *buf, int buf_size, struct unit_value uv)
158 {
159     double vald;
160     long long int vali;
161     int show_float = 0;
162
163     if (uv.unit == unit_second_str) {
164         vald = uv.val.d;
165         show_float = 1;
166     } else {
167         vald = vali = uv.val.i;
168     }
169
170     if (uv.unit == unit_second_str && use_value_sexagesimal_format) {
171         double secs;
172         int hours, mins;
173         secs  = vald;
174         mins  = (int)secs / 60;
175         secs  = secs - mins * 60;
176         hours = mins / 60;
177         mins %= 60;
178         snprintf(buf, buf_size, "%d:%02d:%09.6f", hours, mins, secs);
179     } else {
180         const char *prefix_string = "";
181
182         if (use_value_prefix && vald > 1) {
183             long long int index;
184
185             if (uv.unit == unit_byte_str && use_byte_value_binary_prefix) {
186                 index = (long long int) (log2(vald)) / 10;
187                 index = av_clip(index, 0, FF_ARRAY_ELEMS(binary_unit_prefixes) - 1);
188                 vald /= exp2(index * 10);
189                 prefix_string = binary_unit_prefixes[index];
190             } else {
191                 index = (long long int) (log10(vald)) / 3;
192                 index = av_clip(index, 0, FF_ARRAY_ELEMS(decimal_unit_prefixes) - 1);
193                 vald /= pow(10, index * 3);
194                 prefix_string = decimal_unit_prefixes[index];
195             }
196         }
197
198         if (show_float || (use_value_prefix && vald != (long long int)vald))
199             snprintf(buf, buf_size, "%f", vald);
200         else
201             snprintf(buf, buf_size, "%lld", vali);
202         av_strlcatf(buf, buf_size, "%s%s%s", *prefix_string || show_value_unit ? " " : "",
203                  prefix_string, show_value_unit ? uv.unit : "");
204     }
205
206     return buf;
207 }
208
209 /* WRITERS API */
210
211 typedef struct WriterContext WriterContext;
212
213 #define WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS 1
214 #define WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER 2
215
216 typedef struct Writer {
217     const AVClass *priv_class;      ///< private class of the writer, if any
218     int priv_size;                  ///< private size for the writer context
219     const char *name;
220
221     int  (*init)  (WriterContext *wctx);
222     void (*uninit)(WriterContext *wctx);
223
224     void (*print_section_header)(WriterContext *wctx);
225     void (*print_section_footer)(WriterContext *wctx);
226     void (*print_integer)       (WriterContext *wctx, const char *, long long int);
227     void (*print_rational)      (WriterContext *wctx, AVRational *q, char *sep);
228     void (*print_string)        (WriterContext *wctx, const char *, const char *);
229     int flags;                  ///< a combination or WRITER_FLAG_*
230 } Writer;
231
232 #define SECTION_MAX_NB_LEVELS 10
233
234 struct WriterContext {
235     const AVClass *class;           ///< class of the writer
236     const Writer *writer;           ///< the Writer of which this is an instance
237     char *name;                     ///< name of this writer instance
238     void *priv;                     ///< private data for use by the filter
239
240     const struct section *sections; ///< array containing all sections
241     int nb_sections;                ///< number of sections
242
243     int level;                      ///< current level, starting from 0
244
245     /** number of the item printed in the given section, starting from 0 */
246     unsigned int nb_item[SECTION_MAX_NB_LEVELS];
247
248     /** section per each level */
249     const struct section *section[SECTION_MAX_NB_LEVELS];
250     AVBPrint section_pbuf[SECTION_MAX_NB_LEVELS]; ///< generic print buffer dedicated to each section,
251                                                   ///  used by various writers
252
253     unsigned int nb_section_packet; ///< number of the packet section in case we are in "packets_and_frames" section
254     unsigned int nb_section_frame;  ///< number of the frame  section in case we are in "packets_and_frames" section
255     unsigned int nb_section_packet_frame; ///< nb_section_packet or nb_section_frame according if is_packets_and_frames
256 };
257
258 static const char *writer_get_name(void *p)
259 {
260     WriterContext *wctx = p;
261     return wctx->writer->name;
262 }
263
264 static const AVClass writer_class = {
265     "Writer",
266     writer_get_name,
267     NULL,
268     LIBAVUTIL_VERSION_INT,
269 };
270
271 static void writer_close(WriterContext **wctx)
272 {
273     int i;
274
275     if (!*wctx)
276         return;
277
278     if ((*wctx)->writer->uninit)
279         (*wctx)->writer->uninit(*wctx);
280     for (i = 0; i < SECTION_MAX_NB_LEVELS; i++)
281         av_bprint_finalize(&(*wctx)->section_pbuf[i], NULL);
282     if ((*wctx)->writer->priv_class)
283         av_opt_free((*wctx)->priv);
284     av_freep(&((*wctx)->priv));
285     av_freep(wctx);
286 }
287
288 static int writer_open(WriterContext **wctx, const Writer *writer, const char *args,
289                        const struct section *sections, int nb_sections)
290 {
291     int i, ret = 0;
292
293     if (!(*wctx = av_malloc(sizeof(WriterContext)))) {
294         ret = AVERROR(ENOMEM);
295         goto fail;
296     }
297
298     if (!((*wctx)->priv = av_mallocz(writer->priv_size))) {
299         ret = AVERROR(ENOMEM);
300         goto fail;
301     }
302
303     (*wctx)->class = &writer_class;
304     (*wctx)->writer = writer;
305     (*wctx)->level = -1;
306     (*wctx)->sections = sections;
307     (*wctx)->nb_sections = nb_sections;
308
309     if (writer->priv_class) {
310         void *priv_ctx = (*wctx)->priv;
311         *((const AVClass **)priv_ctx) = writer->priv_class;
312         av_opt_set_defaults(priv_ctx);
313
314         if (args &&
315             (ret = av_set_options_string(priv_ctx, args, "=", ":")) < 0)
316             goto fail;
317     }
318
319     for (i = 0; i < SECTION_MAX_NB_LEVELS; i++)
320         av_bprint_init(&(*wctx)->section_pbuf[i], 1, AV_BPRINT_SIZE_UNLIMITED);
321
322     if ((*wctx)->writer->init)
323         ret = (*wctx)->writer->init(*wctx);
324     if (ret < 0)
325         goto fail;
326
327     return 0;
328
329 fail:
330     writer_close(wctx);
331     return ret;
332 }
333
334 static inline void writer_print_section_header(WriterContext *wctx,
335                                                int section_id)
336 {
337     int parent_section_id;
338     wctx->level++;
339     av_assert0(wctx->level < SECTION_MAX_NB_LEVELS);
340     parent_section_id = wctx->level ?
341         (wctx->section[wctx->level-1])->id : SECTION_ID_NONE;
342
343     wctx->nb_item[wctx->level] = 0;
344     wctx->section[wctx->level] = &wctx->sections[section_id];
345
346     if (section_id == SECTION_ID_PACKETS_AND_FRAMES) {
347         wctx->nb_section_packet = wctx->nb_section_frame =
348         wctx->nb_section_packet_frame = 0;
349     } else if (parent_section_id == SECTION_ID_PACKETS_AND_FRAMES) {
350         wctx->nb_section_packet_frame = section_id == SECTION_ID_PACKET ?
351             wctx->nb_section_packet : wctx->nb_section_frame;
352     }
353
354     if (wctx->writer->print_section_header)
355         wctx->writer->print_section_header(wctx);
356 }
357
358 static inline void writer_print_section_footer(WriterContext *wctx)
359 {
360     int section_id = wctx->section[wctx->level]->id;
361     int parent_section_id = wctx->level ?
362         wctx->section[wctx->level-1]->id : SECTION_ID_NONE;
363
364     if (parent_section_id != SECTION_ID_NONE)
365         wctx->nb_item[wctx->level-1]++;
366     if (parent_section_id == SECTION_ID_PACKETS_AND_FRAMES) {
367         if (section_id == SECTION_ID_PACKET) wctx->nb_section_packet++;
368         else                                     wctx->nb_section_frame++;
369     }
370     if (wctx->writer->print_section_footer)
371         wctx->writer->print_section_footer(wctx);
372     wctx->level--;
373 }
374
375 static inline void writer_print_integer(WriterContext *wctx,
376                                         const char *key, long long int val)
377 {
378     if ((wctx->section[wctx->level]->id != SECTION_ID_FORMAT
379          && wctx->section[wctx->level]->id != SECTION_ID_FORMAT_TAGS) ||
380         !fmt_entries_to_show || av_dict_get(fmt_entries_to_show, key, NULL, 0)) {
381         wctx->writer->print_integer(wctx, key, val);
382         wctx->nb_item[wctx->level]++;
383     }
384 }
385
386 static inline void writer_print_string(WriterContext *wctx,
387                                        const char *key, const char *val, int opt)
388 {
389     if (opt && !(wctx->writer->flags & WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS))
390         return;
391     if ((wctx->section[wctx->level]->id != SECTION_ID_FORMAT
392          && wctx->section[wctx->level]->id != SECTION_ID_FORMAT_TAGS) ||
393         !fmt_entries_to_show || av_dict_get(fmt_entries_to_show, key, NULL, 0)) {
394         wctx->writer->print_string(wctx, key, val);
395         wctx->nb_item[wctx->level]++;
396     }
397 }
398
399 static inline void writer_print_rational(WriterContext *wctx,
400                                          const char *key, AVRational q, char sep)
401 {
402     AVBPrint buf;
403     av_bprint_init(&buf, 0, AV_BPRINT_SIZE_AUTOMATIC);
404     av_bprintf(&buf, "%d%c%d", q.num, sep, q.den);
405     writer_print_string(wctx, key, buf.str, 0);
406 }
407
408 static void writer_print_time(WriterContext *wctx, const char *key,
409                               int64_t ts, const AVRational *time_base, int is_duration)
410 {
411     char buf[128];
412
413     if ((!is_duration && ts == AV_NOPTS_VALUE) || (is_duration && ts == 0)) {
414         writer_print_string(wctx, key, "N/A", 1);
415     } else {
416         double d = ts * av_q2d(*time_base);
417         struct unit_value uv;
418         uv.val.d = d;
419         uv.unit = unit_second_str;
420         value_string(buf, sizeof(buf), uv);
421         writer_print_string(wctx, key, buf, 0);
422     }
423 }
424
425 static void writer_print_ts(WriterContext *wctx, const char *key, int64_t ts, int is_duration)
426 {
427     if ((!is_duration && ts == AV_NOPTS_VALUE) || (is_duration && ts == 0)) {
428         writer_print_string(wctx, key, "N/A", 1);
429     } else {
430         writer_print_integer(wctx, key, ts);
431     }
432 }
433
434 static void writer_print_data(WriterContext *wctx, const char *name,
435                               uint8_t *data, int size)
436 {
437     AVBPrint bp;
438     int offset = 0, l, i;
439
440     av_bprint_init(&bp, 0, AV_BPRINT_SIZE_UNLIMITED);
441     av_bprintf(&bp, "\n");
442     while (size) {
443         av_bprintf(&bp, "%08x: ", offset);
444         l = FFMIN(size, 16);
445         for (i = 0; i < l; i++) {
446             av_bprintf(&bp, "%02x", data[i]);
447             if (i & 1)
448                 av_bprintf(&bp, " ");
449         }
450         av_bprint_chars(&bp, ' ', 41 - 2 * i - i / 2);
451         for (i = 0; i < l; i++)
452             av_bprint_chars(&bp, data[i] - 32U < 95 ? data[i] : '.', 1);
453         av_bprintf(&bp, "\n");
454         offset += l;
455         data   += l;
456         size   -= l;
457     }
458     writer_print_string(wctx, name, bp.str, 0);
459     av_bprint_finalize(&bp, NULL);
460 }
461
462 #define MAX_REGISTERED_WRITERS_NB 64
463
464 static const Writer *registered_writers[MAX_REGISTERED_WRITERS_NB + 1];
465
466 static int writer_register(const Writer *writer)
467 {
468     static int next_registered_writer_idx = 0;
469
470     if (next_registered_writer_idx == MAX_REGISTERED_WRITERS_NB)
471         return AVERROR(ENOMEM);
472
473     registered_writers[next_registered_writer_idx++] = writer;
474     return 0;
475 }
476
477 static const Writer *writer_get_by_name(const char *name)
478 {
479     int i;
480
481     for (i = 0; registered_writers[i]; i++)
482         if (!strcmp(registered_writers[i]->name, name))
483             return registered_writers[i];
484
485     return NULL;
486 }
487
488
489 /* WRITERS */
490
491 #define DEFINE_WRITER_CLASS(name)                   \
492 static const char *name##_get_name(void *ctx)       \
493 {                                                   \
494     return #name ;                                  \
495 }                                                   \
496 static const AVClass name##_class = {               \
497     #name,                                          \
498     name##_get_name,                                \
499     name##_options                                  \
500 }
501
502 /* Default output */
503
504 typedef struct DefaultContext {
505     const AVClass *class;
506     int nokey;
507     int noprint_wrappers;
508     int nested_section[SECTION_MAX_NB_LEVELS];
509 } DefaultContext;
510
511 #define OFFSET(x) offsetof(DefaultContext, x)
512
513 static const AVOption default_options[] = {
514     { "noprint_wrappers", "do not print headers and footers", OFFSET(noprint_wrappers), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
515     { "nw",               "do not print headers and footers", OFFSET(noprint_wrappers), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
516     { "nokey",          "force no key printing",     OFFSET(nokey),          AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
517     { "nk",             "force no key printing",     OFFSET(nokey),          AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
518     {NULL},
519 };
520
521 DEFINE_WRITER_CLASS(default);
522
523 /* lame uppercasing routine, assumes the string is lower case ASCII */
524 static inline char *upcase_string(char *dst, size_t dst_size, const char *src)
525 {
526     int i;
527     for (i = 0; src[i] && i < dst_size-1; i++)
528         dst[i] = av_toupper(src[i]);
529     dst[i] = 0;
530     return dst;
531 }
532
533 static void default_print_section_header(WriterContext *wctx)
534 {
535     DefaultContext *def = wctx->priv;
536     char buf[32];
537     const struct section *section = wctx->section[wctx->level];
538     const struct section *parent_section = wctx->level ?
539         wctx->section[wctx->level-1] : NULL;
540
541     av_bprint_clear(&wctx->section_pbuf[wctx->level]);
542     if (parent_section &&
543         !(parent_section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY))) {
544         def->nested_section[wctx->level] = 1;
545         av_bprintf(&wctx->section_pbuf[wctx->level], "%s%s:",
546                    wctx->section_pbuf[wctx->level-1].str,
547                    upcase_string(buf, sizeof(buf),
548                                  av_x_if_null(section->element_name, section->name)));
549     }
550
551     if (def->noprint_wrappers || def->nested_section[wctx->level])
552         return;
553
554     if (!(section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY)))
555         printf("[%s]\n", upcase_string(buf, sizeof(buf), section->name));
556 }
557
558 static void default_print_section_footer(WriterContext *wctx)
559 {
560     DefaultContext *def = wctx->priv;
561     const struct section *section = wctx->section[wctx->level];
562     char buf[32];
563
564     if (def->noprint_wrappers || def->nested_section[wctx->level])
565         return;
566
567     if (!(section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY)))
568         printf("[/%s]\n", upcase_string(buf, sizeof(buf), section->name));
569 }
570
571 static void default_print_str(WriterContext *wctx, const char *key, const char *value)
572 {
573     DefaultContext *def = wctx->priv;
574
575     if (!def->nokey)
576         printf("%s%s=", wctx->section_pbuf[wctx->level].str, key);
577     printf("%s\n", value);
578 }
579
580 static void default_print_int(WriterContext *wctx, const char *key, long long int value)
581 {
582     DefaultContext *def = wctx->priv;
583
584     if (!def->nokey)
585         printf("%s%s=", wctx->section_pbuf[wctx->level].str, key);
586     printf("%lld\n", value);
587 }
588
589 static const Writer default_writer = {
590     .name                  = "default",
591     .priv_size             = sizeof(DefaultContext),
592     .print_section_header  = default_print_section_header,
593     .print_section_footer  = default_print_section_footer,
594     .print_integer         = default_print_int,
595     .print_string          = default_print_str,
596     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
597     .priv_class            = &default_class,
598 };
599
600 /* Compact output */
601
602 /**
603  * Apply C-language-like string escaping.
604  */
605 static const char *c_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
606 {
607     const char *p;
608
609     for (p = src; *p; p++) {
610         switch (*p) {
611         case '\b': av_bprintf(dst, "%s", "\\b");  break;
612         case '\f': av_bprintf(dst, "%s", "\\f");  break;
613         case '\n': av_bprintf(dst, "%s", "\\n");  break;
614         case '\r': av_bprintf(dst, "%s", "\\r");  break;
615         case '\\': av_bprintf(dst, "%s", "\\\\"); break;
616         default:
617             if (*p == sep)
618                 av_bprint_chars(dst, '\\', 1);
619             av_bprint_chars(dst, *p, 1);
620         }
621     }
622     return dst->str;
623 }
624
625 /**
626  * Quote fields containing special characters, check RFC4180.
627  */
628 static const char *csv_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
629 {
630     char meta_chars[] = { sep, '"', '\n', '\r', '\0' };
631     int needs_quoting = !!src[strcspn(src, meta_chars)];
632
633     if (needs_quoting)
634         av_bprint_chars(dst, '\"', 1);
635
636     for (; *src; src++) {
637         if (*src == '"')
638             av_bprint_chars(dst, '\"', 1);
639         av_bprint_chars(dst, *src, 1);
640     }
641     if (needs_quoting)
642         av_bprint_chars(dst, '\"', 1);
643     return dst->str;
644 }
645
646 static const char *none_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
647 {
648     return src;
649 }
650
651 typedef struct CompactContext {
652     const AVClass *class;
653     char *item_sep_str;
654     char item_sep;
655     int nokey;
656     int print_section;
657     char *escape_mode_str;
658     const char * (*escape_str)(AVBPrint *dst, const char *src, const char sep, void *log_ctx);
659     int nested_section[SECTION_MAX_NB_LEVELS];
660 } CompactContext;
661
662 #undef OFFSET
663 #define OFFSET(x) offsetof(CompactContext, x)
664
665 static const AVOption compact_options[]= {
666     {"item_sep", "set item separator",    OFFSET(item_sep_str),    AV_OPT_TYPE_STRING, {.str="|"},  CHAR_MIN, CHAR_MAX },
667     {"s",        "set item separator",    OFFSET(item_sep_str),    AV_OPT_TYPE_STRING, {.str="|"},  CHAR_MIN, CHAR_MAX },
668     {"nokey",    "force no key printing", OFFSET(nokey),           AV_OPT_TYPE_INT,    {.i64=0},    0,        1        },
669     {"nk",       "force no key printing", OFFSET(nokey),           AV_OPT_TYPE_INT,    {.i64=0},    0,        1        },
670     {"escape",   "set escape mode",       OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"},  CHAR_MIN, CHAR_MAX },
671     {"e",        "set escape mode",       OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"},  CHAR_MIN, CHAR_MAX },
672     {"print_section", "print section name", OFFSET(print_section), AV_OPT_TYPE_INT,    {.i64=1},    0,        1        },
673     {"p",             "print section name", OFFSET(print_section), AV_OPT_TYPE_INT,    {.i64=1},    0,        1        },
674     {NULL},
675 };
676
677 DEFINE_WRITER_CLASS(compact);
678
679 static av_cold int compact_init(WriterContext *wctx)
680 {
681     CompactContext *compact = wctx->priv;
682
683     if (strlen(compact->item_sep_str) != 1) {
684         av_log(wctx, AV_LOG_ERROR, "Item separator '%s' specified, but must contain a single character\n",
685                compact->item_sep_str);
686         return AVERROR(EINVAL);
687     }
688     compact->item_sep = compact->item_sep_str[0];
689
690     if      (!strcmp(compact->escape_mode_str, "none")) compact->escape_str = none_escape_str;
691     else if (!strcmp(compact->escape_mode_str, "c"   )) compact->escape_str = c_escape_str;
692     else if (!strcmp(compact->escape_mode_str, "csv" )) compact->escape_str = csv_escape_str;
693     else {
694         av_log(wctx, AV_LOG_ERROR, "Unknown escape mode '%s'\n", compact->escape_mode_str);
695         return AVERROR(EINVAL);
696     }
697
698     return 0;
699 }
700
701 static void compact_print_section_header(WriterContext *wctx)
702 {
703     CompactContext *compact = wctx->priv;
704     const struct section *section = wctx->section[wctx->level];
705     const struct section *parent_section = wctx->level ?
706         wctx->section[wctx->level-1] : NULL;
707
708     av_bprint_clear(&wctx->section_pbuf[wctx->level]);
709     if (parent_section &&
710         !(parent_section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY))) {
711         compact->nested_section[wctx->level] = 1;
712         av_bprintf(&wctx->section_pbuf[wctx->level], "%s%s:",
713                    wctx->section_pbuf[wctx->level-1].str,
714                    (char *)av_x_if_null(section->element_name, section->name));
715         wctx->nb_item[wctx->level] = wctx->nb_item[wctx->level-1];
716     } else if (compact->print_section &&
717         !(section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY)))
718        printf("%s%c", section->name, compact->item_sep);
719 }
720
721 static void compact_print_section_footer(WriterContext *wctx)
722 {
723     CompactContext *compact = wctx->priv;
724
725     if (!compact->nested_section[wctx->level] &&
726         !(wctx->section[wctx->level]->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY)))
727         printf("\n");
728 }
729
730 static void compact_print_str(WriterContext *wctx, const char *key, const char *value)
731 {
732     CompactContext *compact = wctx->priv;
733     AVBPrint buf;
734
735     if (wctx->nb_item[wctx->level]) printf("%c", compact->item_sep);
736     if (!compact->nokey)
737         printf("%s%s=", wctx->section_pbuf[wctx->level].str, key);
738     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
739     printf("%s", compact->escape_str(&buf, value, compact->item_sep, wctx));
740     av_bprint_finalize(&buf, NULL);
741 }
742
743 static void compact_print_int(WriterContext *wctx, const char *key, long long int value)
744 {
745     CompactContext *compact = wctx->priv;
746
747     if (wctx->nb_item[wctx->level]) printf("%c", compact->item_sep);
748     if (!compact->nokey)
749         printf("%s%s=", wctx->section_pbuf[wctx->level].str, key);
750     printf("%lld", value);
751 }
752
753 static const Writer compact_writer = {
754     .name                 = "compact",
755     .priv_size            = sizeof(CompactContext),
756     .init                 = compact_init,
757     .print_section_header = compact_print_section_header,
758     .print_section_footer = compact_print_section_footer,
759     .print_integer        = compact_print_int,
760     .print_string         = compact_print_str,
761     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
762     .priv_class           = &compact_class,
763 };
764
765 /* CSV output */
766
767 #undef OFFSET
768 #define OFFSET(x) offsetof(CompactContext, x)
769
770 static const AVOption csv_options[] = {
771     {"item_sep", "set item separator",    OFFSET(item_sep_str),    AV_OPT_TYPE_STRING, {.str=","},  CHAR_MIN, CHAR_MAX },
772     {"s",        "set item separator",    OFFSET(item_sep_str),    AV_OPT_TYPE_STRING, {.str=","},  CHAR_MIN, CHAR_MAX },
773     {"nokey",    "force no key printing", OFFSET(nokey),           AV_OPT_TYPE_INT,    {.i64=1},    0,        1        },
774     {"nk",       "force no key printing", OFFSET(nokey),           AV_OPT_TYPE_INT,    {.i64=1},    0,        1        },
775     {"escape",   "set escape mode",       OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="csv"}, CHAR_MIN, CHAR_MAX },
776     {"e",        "set escape mode",       OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="csv"}, CHAR_MIN, CHAR_MAX },
777     {"print_section", "print section name", OFFSET(print_section), AV_OPT_TYPE_INT,    {.i64=1},    0,        1        },
778     {"p",             "print section name", OFFSET(print_section), AV_OPT_TYPE_INT,    {.i64=1},    0,        1        },
779     {NULL},
780 };
781
782 DEFINE_WRITER_CLASS(csv);
783
784 static const Writer csv_writer = {
785     .name                 = "csv",
786     .priv_size            = sizeof(CompactContext),
787     .init                 = compact_init,
788     .print_section_header = compact_print_section_header,
789     .print_section_footer = compact_print_section_footer,
790     .print_integer        = compact_print_int,
791     .print_string         = compact_print_str,
792     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
793     .priv_class           = &csv_class,
794 };
795
796 /* Flat output */
797
798 typedef struct FlatContext {
799     const AVClass *class;
800     const char *sep_str;
801     char sep;
802     int hierarchical;
803 } FlatContext;
804
805 #undef OFFSET
806 #define OFFSET(x) offsetof(FlatContext, x)
807
808 static const AVOption flat_options[]= {
809     {"sep_char", "set separator",    OFFSET(sep_str),    AV_OPT_TYPE_STRING, {.str="."},  CHAR_MIN, CHAR_MAX },
810     {"s",        "set separator",    OFFSET(sep_str),    AV_OPT_TYPE_STRING, {.str="."},  CHAR_MIN, CHAR_MAX },
811     {"hierarchical", "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
812     {"h",           "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
813     {NULL},
814 };
815
816 DEFINE_WRITER_CLASS(flat);
817
818 static av_cold int flat_init(WriterContext *wctx)
819 {
820     FlatContext *flat = wctx->priv;
821
822     if (strlen(flat->sep_str) != 1) {
823         av_log(wctx, AV_LOG_ERROR, "Item separator '%s' specified, but must contain a single character\n",
824                flat->sep_str);
825         return AVERROR(EINVAL);
826     }
827     flat->sep = flat->sep_str[0];
828
829     return 0;
830 }
831
832 static const char *flat_escape_key_str(AVBPrint *dst, const char *src, const char sep)
833 {
834     const char *p;
835
836     for (p = src; *p; p++) {
837         if (!((*p >= '0' && *p <= '9') ||
838               (*p >= 'a' && *p <= 'z') ||
839               (*p >= 'A' && *p <= 'Z')))
840             av_bprint_chars(dst, '_', 1);
841         else
842             av_bprint_chars(dst, *p, 1);
843     }
844     return dst->str;
845 }
846
847 static const char *flat_escape_value_str(AVBPrint *dst, const char *src)
848 {
849     const char *p;
850
851     for (p = src; *p; p++) {
852         switch (*p) {
853         case '\n': av_bprintf(dst, "%s", "\\n");  break;
854         case '\r': av_bprintf(dst, "%s", "\\r");  break;
855         case '\\': av_bprintf(dst, "%s", "\\\\"); break;
856         case '"':  av_bprintf(dst, "%s", "\\\""); break;
857         case '`':  av_bprintf(dst, "%s", "\\`");  break;
858         case '$':  av_bprintf(dst, "%s", "\\$");  break;
859         default:   av_bprint_chars(dst, *p, 1);   break;
860         }
861     }
862     return dst->str;
863 }
864
865 static void flat_print_section_header(WriterContext *wctx)
866 {
867     FlatContext *flat = wctx->priv;
868     AVBPrint *buf = &wctx->section_pbuf[wctx->level];
869     const struct section *section = wctx->section[wctx->level];
870     const struct section *parent_section = wctx->level ?
871         wctx->section[wctx->level-1] : NULL;
872
873     /* build section header */
874     av_bprint_clear(buf);
875     if (!parent_section)
876         return;
877     av_bprintf(buf, "%s", wctx->section_pbuf[wctx->level-1].str);
878
879     if (flat->hierarchical ||
880         !(section->flags & (SECTION_FLAG_IS_ARRAY|SECTION_FLAG_IS_WRAPPER))) {
881         av_bprintf(buf, "%s%s", wctx->section[wctx->level]->name, flat->sep_str);
882
883         if (parent_section->flags & SECTION_FLAG_IS_ARRAY) {
884             int n = parent_section->id == SECTION_ID_PACKETS_AND_FRAMES ?
885                 wctx->nb_section_packet_frame : wctx->nb_item[wctx->level-1];
886             av_bprintf(buf, "%d%s", n, flat->sep_str);
887         }
888     }
889 }
890
891 static void flat_print_int(WriterContext *wctx, const char *key, long long int value)
892 {
893     printf("%s%s=%lld\n", wctx->section_pbuf[wctx->level].str, key, value);
894 }
895
896 static void flat_print_str(WriterContext *wctx, const char *key, const char *value)
897 {
898     FlatContext *flat = wctx->priv;
899     AVBPrint buf;
900
901     printf("%s", wctx->section_pbuf[wctx->level].str);
902     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
903     printf("%s=", flat_escape_key_str(&buf, key, flat->sep));
904     av_bprint_clear(&buf);
905     printf("\"%s\"\n", flat_escape_value_str(&buf, value));
906     av_bprint_finalize(&buf, NULL);
907 }
908
909 static const Writer flat_writer = {
910     .name                  = "flat",
911     .priv_size             = sizeof(FlatContext),
912     .init                  = flat_init,
913     .print_section_header  = flat_print_section_header,
914     .print_integer         = flat_print_int,
915     .print_string          = flat_print_str,
916     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS|WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
917     .priv_class            = &flat_class,
918 };
919
920 /* INI format output */
921
922 typedef struct {
923     const AVClass *class;
924     int hierarchical;
925 } INIContext;
926
927 #undef OFFSET
928 #define OFFSET(x) offsetof(INIContext, x)
929
930 static const AVOption ini_options[] = {
931     {"hierarchical", "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
932     {"h",           "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
933     {NULL},
934 };
935
936 DEFINE_WRITER_CLASS(ini);
937
938 static char *ini_escape_str(AVBPrint *dst, const char *src)
939 {
940     int i = 0;
941     char c = 0;
942
943     while (c = src[i++]) {
944         switch (c) {
945         case '\b': av_bprintf(dst, "%s", "\\b"); break;
946         case '\f': av_bprintf(dst, "%s", "\\f"); break;
947         case '\n': av_bprintf(dst, "%s", "\\n"); break;
948         case '\r': av_bprintf(dst, "%s", "\\r"); break;
949         case '\t': av_bprintf(dst, "%s", "\\t"); break;
950         case '\\':
951         case '#' :
952         case '=' :
953         case ':' : av_bprint_chars(dst, '\\', 1);
954         default:
955             if ((unsigned char)c < 32)
956                 av_bprintf(dst, "\\x00%02x", c & 0xff);
957             else
958                 av_bprint_chars(dst, c, 1);
959             break;
960         }
961     }
962     return dst->str;
963 }
964
965 static void ini_print_section_header(WriterContext *wctx)
966 {
967     INIContext *ini = wctx->priv;
968     AVBPrint *buf = &wctx->section_pbuf[wctx->level];
969     const struct section *section = wctx->section[wctx->level];
970     const struct section *parent_section = wctx->level ?
971         wctx->section[wctx->level-1] : NULL;
972
973     av_bprint_clear(buf);
974     if (!parent_section) {
975         printf("# ffprobe output\n\n");
976         return;
977     }
978
979     if (wctx->nb_item[wctx->level-1])
980         printf("\n");
981
982     av_bprintf(buf, "%s", wctx->section_pbuf[wctx->level-1].str);
983     if (ini->hierarchical ||
984         !(section->flags & (SECTION_FLAG_IS_ARRAY|SECTION_FLAG_IS_WRAPPER))) {
985         av_bprintf(buf, "%s%s", buf->str[0] ? "." : "", wctx->section[wctx->level]->name);
986
987         if (parent_section->flags & SECTION_FLAG_IS_ARRAY) {
988             int n = parent_section->id == SECTION_ID_PACKETS_AND_FRAMES ?
989                 wctx->nb_section_packet_frame : wctx->nb_item[wctx->level-1];
990             av_bprintf(buf, ".%d", n);
991         }
992     }
993
994     if (!(section->flags & (SECTION_FLAG_IS_ARRAY|SECTION_FLAG_IS_WRAPPER)))
995         printf("[%s]\n", buf->str);
996 }
997
998 static void ini_print_str(WriterContext *wctx, const char *key, const char *value)
999 {
1000     AVBPrint buf;
1001
1002     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
1003     printf("%s=", ini_escape_str(&buf, key));
1004     av_bprint_clear(&buf);
1005     printf("%s\n", ini_escape_str(&buf, value));
1006     av_bprint_finalize(&buf, NULL);
1007 }
1008
1009 static void ini_print_int(WriterContext *wctx, const char *key, long long int value)
1010 {
1011     printf("%s=%lld\n", key, value);
1012 }
1013
1014 static const Writer ini_writer = {
1015     .name                  = "ini",
1016     .priv_size             = sizeof(INIContext),
1017     .print_section_header  = ini_print_section_header,
1018     .print_integer         = ini_print_int,
1019     .print_string          = ini_print_str,
1020     .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS|WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
1021     .priv_class            = &ini_class,
1022 };
1023
1024 /* JSON output */
1025
1026 typedef struct {
1027     const AVClass *class;
1028     int indent_level;
1029     int compact;
1030     const char *item_sep, *item_start_end;
1031 } JSONContext;
1032
1033 #undef OFFSET
1034 #define OFFSET(x) offsetof(JSONContext, x)
1035
1036 static const AVOption json_options[]= {
1037     { "compact", "enable compact output", OFFSET(compact), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
1038     { "c",       "enable compact output", OFFSET(compact), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
1039     { NULL }
1040 };
1041
1042 DEFINE_WRITER_CLASS(json);
1043
1044 static av_cold int json_init(WriterContext *wctx)
1045 {
1046     JSONContext *json = wctx->priv;
1047
1048     json->item_sep       = json->compact ? ", " : ",\n";
1049     json->item_start_end = json->compact ? " "  : "\n";
1050
1051     return 0;
1052 }
1053
1054 static const char *json_escape_str(AVBPrint *dst, const char *src, void *log_ctx)
1055 {
1056     static const char json_escape[] = {'"', '\\', '\b', '\f', '\n', '\r', '\t', 0};
1057     static const char json_subst[]  = {'"', '\\',  'b',  'f',  'n',  'r',  't', 0};
1058     const char *p;
1059
1060     for (p = src; *p; p++) {
1061         char *s = strchr(json_escape, *p);
1062         if (s) {
1063             av_bprint_chars(dst, '\\', 1);
1064             av_bprint_chars(dst, json_subst[s - json_escape], 1);
1065         } else if ((unsigned char)*p < 32) {
1066             av_bprintf(dst, "\\u00%02x", *p & 0xff);
1067         } else {
1068             av_bprint_chars(dst, *p, 1);
1069         }
1070     }
1071     return dst->str;
1072 }
1073
1074 #define JSON_INDENT() printf("%*c", json->indent_level * 4, ' ')
1075
1076 static void json_print_section_header(WriterContext *wctx)
1077 {
1078     JSONContext *json = wctx->priv;
1079     AVBPrint buf;
1080     const struct section *section = wctx->section[wctx->level];
1081     const struct section *parent_section = wctx->level ?
1082         wctx->section[wctx->level-1] : NULL;
1083
1084     if (wctx->level && wctx->nb_item[wctx->level-1])
1085         printf(",\n");
1086
1087     if (section->flags & SECTION_FLAG_IS_WRAPPER) {
1088         printf("{\n");
1089         json->indent_level++;
1090     } else {
1091         av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
1092         json_escape_str(&buf, section->name, wctx);
1093         JSON_INDENT();
1094
1095         json->indent_level++;
1096         if (section->flags & SECTION_FLAG_IS_ARRAY) {
1097             printf("\"%s\": [\n", buf.str);
1098         } else if (!(parent_section->flags & SECTION_FLAG_IS_ARRAY)) {
1099             printf("\"%s\": {%s", buf.str, json->item_start_end);
1100         } else {
1101             printf("{%s", json->item_start_end);
1102
1103             /* this is required so the parser can distinguish between packets and frames */
1104             if (parent_section->id == SECTION_ID_PACKETS_AND_FRAMES) {
1105                 if (!json->compact)
1106                     JSON_INDENT();
1107                 printf("\"type\": \"%s\"%s", section->name, json->item_sep);
1108             }
1109         }
1110         av_bprint_finalize(&buf, NULL);
1111     }
1112 }
1113
1114 static void json_print_section_footer(WriterContext *wctx)
1115 {
1116     JSONContext *json = wctx->priv;
1117     const struct section *section = wctx->section[wctx->level];
1118
1119     if (wctx->level == 0) {
1120         json->indent_level--;
1121         printf("\n}\n");
1122     } else if (section->flags & SECTION_FLAG_IS_ARRAY) {
1123         printf("\n");
1124         json->indent_level--;
1125         JSON_INDENT();
1126         printf("]");
1127     } else {
1128         printf("%s", json->item_start_end);
1129         json->indent_level--;
1130         if (!json->compact)
1131             JSON_INDENT();
1132         printf("}");
1133     }
1134 }
1135
1136 static inline void json_print_item_str(WriterContext *wctx,
1137                                        const char *key, const char *value)
1138 {
1139     AVBPrint buf;
1140
1141     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
1142     printf("\"%s\":", json_escape_str(&buf, key,   wctx));
1143     av_bprint_clear(&buf);
1144     printf(" \"%s\"", json_escape_str(&buf, value, wctx));
1145     av_bprint_finalize(&buf, NULL);
1146 }
1147
1148 static void json_print_str(WriterContext *wctx, const char *key, const char *value)
1149 {
1150     JSONContext *json = wctx->priv;
1151
1152     if (wctx->nb_item[wctx->level])
1153         printf("%s", json->item_sep);
1154     if (!json->compact)
1155         JSON_INDENT();
1156     json_print_item_str(wctx, key, value);
1157 }
1158
1159 static void json_print_int(WriterContext *wctx, const char *key, long long int value)
1160 {
1161     JSONContext *json = wctx->priv;
1162     AVBPrint buf;
1163
1164     if (wctx->nb_item[wctx->level])
1165         printf("%s", json->item_sep);
1166     if (!json->compact)
1167         JSON_INDENT();
1168
1169     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
1170     printf("\"%s\": %lld", json_escape_str(&buf, key, wctx), value);
1171     av_bprint_finalize(&buf, NULL);
1172 }
1173
1174 static const Writer json_writer = {
1175     .name                 = "json",
1176     .priv_size            = sizeof(JSONContext),
1177     .init                 = json_init,
1178     .print_section_header = json_print_section_header,
1179     .print_section_footer = json_print_section_footer,
1180     .print_integer        = json_print_int,
1181     .print_string         = json_print_str,
1182     .flags = WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
1183     .priv_class           = &json_class,
1184 };
1185
1186 /* XML output */
1187
1188 typedef struct {
1189     const AVClass *class;
1190     int within_tag;
1191     int indent_level;
1192     int fully_qualified;
1193     int xsd_strict;
1194 } XMLContext;
1195
1196 #undef OFFSET
1197 #define OFFSET(x) offsetof(XMLContext, x)
1198
1199 static const AVOption xml_options[] = {
1200     {"fully_qualified", "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_INT, {.i64=0},  0, 1 },
1201     {"q",               "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_INT, {.i64=0},  0, 1 },
1202     {"xsd_strict",      "ensure that the output is XSD compliant",         OFFSET(xsd_strict),      AV_OPT_TYPE_INT, {.i64=0},  0, 1 },
1203     {"x",               "ensure that the output is XSD compliant",         OFFSET(xsd_strict),      AV_OPT_TYPE_INT, {.i64=0},  0, 1 },
1204     {NULL},
1205 };
1206
1207 DEFINE_WRITER_CLASS(xml);
1208
1209 static av_cold int xml_init(WriterContext *wctx)
1210 {
1211     XMLContext *xml = wctx->priv;
1212
1213     if (xml->xsd_strict) {
1214         xml->fully_qualified = 1;
1215 #define CHECK_COMPLIANCE(opt, opt_name)                                 \
1216         if (opt) {                                                      \
1217             av_log(wctx, AV_LOG_ERROR,                                  \
1218                    "XSD-compliant output selected but option '%s' was selected, XML output may be non-compliant.\n" \
1219                    "You need to disable such option with '-no%s'\n", opt_name, opt_name); \
1220             return AVERROR(EINVAL);                                     \
1221         }
1222         CHECK_COMPLIANCE(show_private_data, "private");
1223         CHECK_COMPLIANCE(show_value_unit,   "unit");
1224         CHECK_COMPLIANCE(use_value_prefix,  "prefix");
1225
1226         if (do_show_frames && do_show_packets) {
1227             av_log(wctx, AV_LOG_ERROR,
1228                    "Interleaved frames and packets are not allowed in XSD. "
1229                    "Select only one between the -show_frames and the -show_packets options.\n");
1230             return AVERROR(EINVAL);
1231         }
1232     }
1233
1234     return 0;
1235 }
1236
1237 static const char *xml_escape_str(AVBPrint *dst, const char *src, void *log_ctx)
1238 {
1239     const char *p;
1240
1241     for (p = src; *p; p++) {
1242         switch (*p) {
1243         case '&' : av_bprintf(dst, "%s", "&amp;");  break;
1244         case '<' : av_bprintf(dst, "%s", "&lt;");   break;
1245         case '>' : av_bprintf(dst, "%s", "&gt;");   break;
1246         case '\"': av_bprintf(dst, "%s", "&quot;"); break;
1247         case '\'': av_bprintf(dst, "%s", "&apos;"); break;
1248         default: av_bprint_chars(dst, *p, 1);
1249         }
1250     }
1251
1252     return dst->str;
1253 }
1254
1255 #define XML_INDENT() printf("%*c", xml->indent_level * 4, ' ')
1256
1257 static void xml_print_section_header(WriterContext *wctx)
1258 {
1259     XMLContext *xml = wctx->priv;
1260     const struct section *section = wctx->section[wctx->level];
1261     const struct section *parent_section = wctx->level ?
1262         wctx->section[wctx->level-1] : NULL;
1263
1264     if (wctx->level == 0) {
1265         const char *qual = " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' "
1266             "xmlns:ffprobe='http://www.ffmpeg.org/schema/ffprobe' "
1267             "xsi:schemaLocation='http://www.ffmpeg.org/schema/ffprobe ffprobe.xsd'";
1268
1269         printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1270         printf("<%sffprobe%s>\n",
1271                xml->fully_qualified ? "ffprobe:" : "",
1272                xml->fully_qualified ? qual : "");
1273         return;
1274     }
1275
1276     if (xml->within_tag) {
1277         xml->within_tag = 0;
1278         printf(">\n");
1279     }
1280     if (section->flags & SECTION_FLAG_HAS_VARIABLE_FIELDS) {
1281         xml->indent_level++;
1282     } else {
1283         if (parent_section && (parent_section->flags & SECTION_FLAG_IS_WRAPPER) &&
1284             wctx->level && wctx->nb_item[wctx->level-1])
1285             printf("\n");
1286         xml->indent_level++;
1287
1288         if (section->flags & SECTION_FLAG_IS_ARRAY) {
1289             XML_INDENT(); printf("<%s>\n", section->name);
1290         } else {
1291             XML_INDENT(); printf("<%s ", section->name);
1292             xml->within_tag = 1;
1293         }
1294     }
1295 }
1296
1297 static void xml_print_section_footer(WriterContext *wctx)
1298 {
1299     XMLContext *xml = wctx->priv;
1300     const struct section *section = wctx->section[wctx->level];
1301
1302     if (wctx->level == 0) {
1303         printf("</%sffprobe>\n", xml->fully_qualified ? "ffprobe:" : "");
1304     } else if (xml->within_tag) {
1305         xml->within_tag = 0;
1306         printf("/>\n");
1307         xml->indent_level--;
1308     } else if (section->flags & SECTION_FLAG_HAS_VARIABLE_FIELDS) {
1309         xml->indent_level--;
1310     } else {
1311         XML_INDENT(); printf("</%s>\n", section->name);
1312         xml->indent_level--;
1313     }
1314 }
1315
1316 static void xml_print_str(WriterContext *wctx, const char *key, const char *value)
1317 {
1318     AVBPrint buf;
1319     XMLContext *xml = wctx->priv;
1320     const struct section *section = wctx->section[wctx->level];
1321
1322     av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
1323
1324     if (section->flags & SECTION_FLAG_HAS_VARIABLE_FIELDS) {
1325         XML_INDENT();
1326         printf("<%s key=\"%s\"",
1327                section->element_name, xml_escape_str(&buf, key, wctx));
1328         av_bprint_clear(&buf);
1329         printf(" value=\"%s\"/>\n", xml_escape_str(&buf, value, wctx));
1330     } else {
1331         if (wctx->nb_item[wctx->level])
1332             printf(" ");
1333         printf("%s=\"%s\"", key, xml_escape_str(&buf, value, wctx));
1334     }
1335
1336     av_bprint_finalize(&buf, NULL);
1337 }
1338
1339 static void xml_print_int(WriterContext *wctx, const char *key, long long int value)
1340 {
1341     if (wctx->nb_item[wctx->level])
1342         printf(" ");
1343     printf("%s=\"%lld\"", key, value);
1344 }
1345
1346 static Writer xml_writer = {
1347     .name                 = "xml",
1348     .priv_size            = sizeof(XMLContext),
1349     .init                 = xml_init,
1350     .print_section_header = xml_print_section_header,
1351     .print_section_footer = xml_print_section_footer,
1352     .print_integer        = xml_print_int,
1353     .print_string         = xml_print_str,
1354     .flags = WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
1355     .priv_class           = &xml_class,
1356 };
1357
1358 static void writer_register_all(void)
1359 {
1360     static int initialized;
1361
1362     if (initialized)
1363         return;
1364     initialized = 1;
1365
1366     writer_register(&default_writer);
1367     writer_register(&compact_writer);
1368     writer_register(&csv_writer);
1369     writer_register(&flat_writer);
1370     writer_register(&ini_writer);
1371     writer_register(&json_writer);
1372     writer_register(&xml_writer);
1373 }
1374
1375 #define print_fmt(k, f, ...) do {              \
1376     av_bprint_clear(&pbuf);                    \
1377     av_bprintf(&pbuf, f, __VA_ARGS__);         \
1378     writer_print_string(w, k, pbuf.str, 0);    \
1379 } while (0)
1380
1381 #define print_int(k, v)         writer_print_integer(w, k, v)
1382 #define print_q(k, v, s)        writer_print_rational(w, k, v, s)
1383 #define print_str(k, v)         writer_print_string(w, k, v, 0)
1384 #define print_str_opt(k, v)     writer_print_string(w, k, v, 1)
1385 #define print_time(k, v, tb)    writer_print_time(w, k, v, tb, 0)
1386 #define print_ts(k, v)          writer_print_ts(w, k, v, 0)
1387 #define print_duration_time(k, v, tb) writer_print_time(w, k, v, tb, 1)
1388 #define print_duration_ts(k, v)       writer_print_ts(w, k, v, 1)
1389 #define print_val(k, v, u) do {                                     \
1390     struct unit_value uv;                                           \
1391     uv.val.i = v;                                                   \
1392     uv.unit = u;                                                    \
1393     writer_print_string(w, k, value_string(val_str, sizeof(val_str), uv), 0); \
1394 } while (0)
1395
1396 #define print_section_header(s) writer_print_section_header(w, s)
1397 #define print_section_footer(s) writer_print_section_footer(w, s)
1398
1399 static inline void show_tags(WriterContext *wctx, AVDictionary *tags, int section_id)
1400 {
1401     AVDictionaryEntry *tag = NULL;
1402
1403     if (!tags)
1404         return;
1405     writer_print_section_header(wctx, section_id);
1406     while ((tag = av_dict_get(tags, "", tag, AV_DICT_IGNORE_SUFFIX)))
1407         writer_print_string(wctx, tag->key, tag->value, 0);
1408     writer_print_section_footer(wctx);
1409 }
1410
1411 static void show_packet(WriterContext *w, AVFormatContext *fmt_ctx, AVPacket *pkt, int packet_idx)
1412 {
1413     char val_str[128];
1414     AVStream *st = fmt_ctx->streams[pkt->stream_index];
1415     AVBPrint pbuf;
1416     const char *s;
1417
1418     av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
1419
1420     writer_print_section_header(w, SECTION_ID_PACKET);
1421
1422     s = av_get_media_type_string(st->codec->codec_type);
1423     if (s) print_str    ("codec_type", s);
1424     else   print_str_opt("codec_type", "unknown");
1425     print_int("stream_index",     pkt->stream_index);
1426     print_ts  ("pts",             pkt->pts);
1427     print_time("pts_time",        pkt->pts, &st->time_base);
1428     print_ts  ("dts",             pkt->dts);
1429     print_time("dts_time",        pkt->dts, &st->time_base);
1430     print_duration_ts("duration",        pkt->duration);
1431     print_duration_time("duration_time", pkt->duration, &st->time_base);
1432     print_duration_ts("convergence_duration", pkt->convergence_duration);
1433     print_duration_time("convergence_duration_time", pkt->convergence_duration, &st->time_base);
1434     print_val("size",             pkt->size, unit_byte_str);
1435     if (pkt->pos != -1) print_fmt    ("pos", "%"PRId64, pkt->pos);
1436     else                print_str_opt("pos", "N/A");
1437     print_fmt("flags", "%c",      pkt->flags & AV_PKT_FLAG_KEY ? 'K' : '_');
1438     if (do_show_data)
1439         writer_print_data(w, "data", pkt->data, pkt->size);
1440     writer_print_section_footer(w);
1441
1442     av_bprint_finalize(&pbuf, NULL);
1443     fflush(stdout);
1444 }
1445
1446 static void show_frame(WriterContext *w, AVFrame *frame, AVStream *stream,
1447                        AVFormatContext *fmt_ctx)
1448 {
1449     AVBPrint pbuf;
1450     const char *s;
1451
1452     av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
1453
1454     writer_print_section_header(w, SECTION_ID_FRAME);
1455
1456     s = av_get_media_type_string(stream->codec->codec_type);
1457     if (s) print_str    ("media_type", s);
1458     else   print_str_opt("media_type", "unknown");
1459     print_int("key_frame",              frame->key_frame);
1460     print_ts  ("pkt_pts",               frame->pkt_pts);
1461     print_time("pkt_pts_time",          frame->pkt_pts, &stream->time_base);
1462     print_ts  ("pkt_dts",               frame->pkt_dts);
1463     print_time("pkt_dts_time",          frame->pkt_dts, &stream->time_base);
1464     print_duration_ts  ("pkt_duration",      frame->pkt_duration);
1465     print_duration_time("pkt_duration_time", frame->pkt_duration, &stream->time_base);
1466     if (frame->pkt_pos != -1) print_fmt    ("pkt_pos", "%"PRId64, frame->pkt_pos);
1467     else                      print_str_opt("pkt_pos", "N/A");
1468
1469     switch (stream->codec->codec_type) {
1470         AVRational sar;
1471
1472     case AVMEDIA_TYPE_VIDEO:
1473         print_int("width",                  frame->width);
1474         print_int("height",                 frame->height);
1475         s = av_get_pix_fmt_name(frame->format);
1476         if (s) print_str    ("pix_fmt", s);
1477         else   print_str_opt("pix_fmt", "unknown");
1478         sar = av_guess_sample_aspect_ratio(fmt_ctx, stream, frame);
1479         if (sar.num) {
1480             print_q("sample_aspect_ratio", sar, ':');
1481         } else {
1482             print_str_opt("sample_aspect_ratio", "N/A");
1483         }
1484         print_fmt("pict_type",              "%c", av_get_picture_type_char(frame->pict_type));
1485         print_int("coded_picture_number",   frame->coded_picture_number);
1486         print_int("display_picture_number", frame->display_picture_number);
1487         print_int("interlaced_frame",       frame->interlaced_frame);
1488         print_int("top_field_first",        frame->top_field_first);
1489         print_int("repeat_pict",            frame->repeat_pict);
1490         print_int("reference",              frame->reference);
1491         break;
1492
1493     case AVMEDIA_TYPE_AUDIO:
1494         s = av_get_sample_fmt_name(frame->format);
1495         if (s) print_str    ("sample_fmt", s);
1496         else   print_str_opt("sample_fmt", "unknown");
1497         print_int("nb_samples",         frame->nb_samples);
1498         print_int("channels", av_frame_get_channels(frame));
1499         if (av_frame_get_channel_layout(frame)) {
1500             av_bprint_clear(&pbuf);
1501             av_bprint_channel_layout(&pbuf, av_frame_get_channels(frame),
1502                                      av_frame_get_channel_layout(frame));
1503             print_str    ("channel_layout", pbuf.str);
1504         } else
1505             print_str_opt("channel_layout", "unknown");
1506         break;
1507     }
1508     show_tags(w, av_frame_get_metadata(frame), SECTION_ID_FRAME_TAGS);
1509
1510     writer_print_section_footer(w);
1511
1512     av_bprint_finalize(&pbuf, NULL);
1513     fflush(stdout);
1514 }
1515
1516 static av_always_inline int process_frame(WriterContext *w,
1517                                           AVFormatContext *fmt_ctx,
1518                                           AVFrame *frame, AVPacket *pkt)
1519 {
1520     AVCodecContext *dec_ctx = fmt_ctx->streams[pkt->stream_index]->codec;
1521     int ret = 0, got_frame = 0;
1522
1523     avcodec_get_frame_defaults(frame);
1524     if (dec_ctx->codec) {
1525         switch (dec_ctx->codec_type) {
1526         case AVMEDIA_TYPE_VIDEO:
1527             ret = avcodec_decode_video2(dec_ctx, frame, &got_frame, pkt);
1528             break;
1529
1530         case AVMEDIA_TYPE_AUDIO:
1531             ret = avcodec_decode_audio4(dec_ctx, frame, &got_frame, pkt);
1532             break;
1533         }
1534     }
1535
1536     if (ret < 0)
1537         return ret;
1538     ret = FFMIN(ret, pkt->size); /* guard against bogus return values */
1539     pkt->data += ret;
1540     pkt->size -= ret;
1541     if (got_frame) {
1542         nb_streams_frames[pkt->stream_index]++;
1543         if (do_show_frames)
1544             show_frame(w, frame, fmt_ctx->streams[pkt->stream_index], fmt_ctx);
1545     }
1546     return got_frame;
1547 }
1548
1549 static void read_packets(WriterContext *w, AVFormatContext *fmt_ctx)
1550 {
1551     AVPacket pkt, pkt1;
1552     AVFrame frame;
1553     int i = 0;
1554
1555     av_init_packet(&pkt);
1556
1557     while (!av_read_frame(fmt_ctx, &pkt)) {
1558         if (selected_streams[pkt.stream_index]) {
1559             if (do_read_packets) {
1560                 if (do_show_packets)
1561                     show_packet(w, fmt_ctx, &pkt, i++);
1562                 nb_streams_packets[pkt.stream_index]++;
1563             }
1564             if (do_read_frames) {
1565                 pkt1 = pkt;
1566                 while (pkt1.size && process_frame(w, fmt_ctx, &frame, &pkt1) > 0);
1567             }
1568         }
1569         av_free_packet(&pkt);
1570     }
1571     av_init_packet(&pkt);
1572     pkt.data = NULL;
1573     pkt.size = 0;
1574     //Flush remaining frames that are cached in the decoder
1575     for (i = 0; i < fmt_ctx->nb_streams; i++) {
1576         pkt.stream_index = i;
1577         if (do_read_frames)
1578             while (process_frame(w, fmt_ctx, &frame, &pkt) > 0);
1579     }
1580 }
1581
1582 static void show_stream(WriterContext *w, AVFormatContext *fmt_ctx, int stream_idx)
1583 {
1584     AVStream *stream = fmt_ctx->streams[stream_idx];
1585     AVCodecContext *dec_ctx;
1586     const AVCodec *dec;
1587     char val_str[128];
1588     const char *s;
1589     AVRational sar, dar;
1590     AVBPrint pbuf;
1591
1592     av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
1593
1594     writer_print_section_header(w, SECTION_ID_STREAM);
1595
1596     print_int("index", stream->index);
1597
1598     if ((dec_ctx = stream->codec)) {
1599         const char *profile = NULL;
1600         dec = dec_ctx->codec;
1601         if (dec) {
1602             print_str("codec_name", dec->name);
1603             if (!do_bitexact) {
1604                 if (dec->long_name) print_str    ("codec_long_name", dec->long_name);
1605                 else                print_str_opt("codec_long_name", "unknown");
1606             }
1607         } else {
1608             print_str_opt("codec_name", "unknown");
1609             if (!do_bitexact) {
1610                 print_str_opt("codec_long_name", "unknown");
1611             }
1612         }
1613
1614         if (dec && (profile = av_get_profile_name(dec, dec_ctx->profile)))
1615             print_str("profile", profile);
1616         else
1617             print_str_opt("profile", "unknown");
1618
1619         s = av_get_media_type_string(dec_ctx->codec_type);
1620         if (s) print_str    ("codec_type", s);
1621         else   print_str_opt("codec_type", "unknown");
1622         print_q("codec_time_base", dec_ctx->time_base, '/');
1623
1624         /* print AVI/FourCC tag */
1625         av_get_codec_tag_string(val_str, sizeof(val_str), dec_ctx->codec_tag);
1626         print_str("codec_tag_string",    val_str);
1627         print_fmt("codec_tag", "0x%04x", dec_ctx->codec_tag);
1628
1629         switch (dec_ctx->codec_type) {
1630         case AVMEDIA_TYPE_VIDEO:
1631             print_int("width",        dec_ctx->width);
1632             print_int("height",       dec_ctx->height);
1633             print_int("has_b_frames", dec_ctx->has_b_frames);
1634             sar = av_guess_sample_aspect_ratio(fmt_ctx, stream, NULL);
1635             if (sar.den) {
1636                 print_q("sample_aspect_ratio", sar, ':');
1637                 av_reduce(&dar.num, &dar.den,
1638                           dec_ctx->width  * sar.num,
1639                           dec_ctx->height * sar.den,
1640                           1024*1024);
1641                 print_q("display_aspect_ratio", dar, ':');
1642             } else {
1643                 print_str_opt("sample_aspect_ratio", "N/A");
1644                 print_str_opt("display_aspect_ratio", "N/A");
1645             }
1646             s = av_get_pix_fmt_name(dec_ctx->pix_fmt);
1647             if (s) print_str    ("pix_fmt", s);
1648             else   print_str_opt("pix_fmt", "unknown");
1649             print_int("level",   dec_ctx->level);
1650             if (dec_ctx->timecode_frame_start >= 0) {
1651                 char tcbuf[AV_TIMECODE_STR_SIZE];
1652                 av_timecode_make_mpeg_tc_string(tcbuf, dec_ctx->timecode_frame_start);
1653                 print_str("timecode", tcbuf);
1654             } else {
1655                 print_str_opt("timecode", "N/A");
1656             }
1657             break;
1658
1659         case AVMEDIA_TYPE_AUDIO:
1660             s = av_get_sample_fmt_name(dec_ctx->sample_fmt);
1661             if (s) print_str    ("sample_fmt", s);
1662             else   print_str_opt("sample_fmt", "unknown");
1663             print_val("sample_rate",     dec_ctx->sample_rate, unit_hertz_str);
1664             print_int("channels",        dec_ctx->channels);
1665             print_int("bits_per_sample", av_get_bits_per_sample(dec_ctx->codec_id));
1666             break;
1667         }
1668     } else {
1669         print_str_opt("codec_type", "unknown");
1670     }
1671     if (dec_ctx->codec && dec_ctx->codec->priv_class && show_private_data) {
1672         const AVOption *opt = NULL;
1673         while (opt = av_opt_next(dec_ctx->priv_data,opt)) {
1674             uint8_t *str;
1675             if (opt->flags) continue;
1676             if (av_opt_get(dec_ctx->priv_data, opt->name, 0, &str) >= 0) {
1677                 print_str(opt->name, str);
1678                 av_free(str);
1679             }
1680         }
1681     }
1682
1683     if (fmt_ctx->iformat->flags & AVFMT_SHOW_IDS) print_fmt    ("id", "0x%x", stream->id);
1684     else                                          print_str_opt("id", "N/A");
1685     print_q("r_frame_rate",   stream->r_frame_rate,   '/');
1686     print_q("avg_frame_rate", stream->avg_frame_rate, '/');
1687     print_q("time_base",      stream->time_base,      '/');
1688     print_ts  ("start_pts",   stream->start_time);
1689     print_time("start_time",  stream->start_time, &stream->time_base);
1690     print_ts  ("duration_ts", stream->duration);
1691     print_time("duration",    stream->duration, &stream->time_base);
1692     if (dec_ctx->bit_rate > 0) print_val    ("bit_rate", dec_ctx->bit_rate, unit_bit_per_second_str);
1693     else                       print_str_opt("bit_rate", "N/A");
1694     if (stream->nb_frames) print_fmt    ("nb_frames", "%"PRId64, stream->nb_frames);
1695     else                   print_str_opt("nb_frames", "N/A");
1696     if (nb_streams_frames[stream_idx])  print_fmt    ("nb_read_frames", "%"PRIu64, nb_streams_frames[stream_idx]);
1697     else                                print_str_opt("nb_read_frames", "N/A");
1698     if (nb_streams_packets[stream_idx]) print_fmt    ("nb_read_packets", "%"PRIu64, nb_streams_packets[stream_idx]);
1699     else                                print_str_opt("nb_read_packets", "N/A");
1700     if (do_show_data)
1701         writer_print_data(w, "extradata", dec_ctx->extradata,
1702                                           dec_ctx->extradata_size);
1703
1704     /* Print disposition information */
1705 #define PRINT_DISPOSITION(flagname, name) do {                                \
1706         print_int(name, !!(stream->disposition & AV_DISPOSITION_##flagname)); \
1707     } while (0)
1708
1709     writer_print_section_header(w, SECTION_ID_STREAM_DISPOSITION);
1710     PRINT_DISPOSITION(DEFAULT,          "default");
1711     PRINT_DISPOSITION(DUB,              "dub");
1712     PRINT_DISPOSITION(ORIGINAL,         "original");
1713     PRINT_DISPOSITION(COMMENT,          "comment");
1714     PRINT_DISPOSITION(LYRICS,           "lyrics");
1715     PRINT_DISPOSITION(KARAOKE,          "karaoke");
1716     PRINT_DISPOSITION(FORCED,           "forced");
1717     PRINT_DISPOSITION(HEARING_IMPAIRED, "hearing_impaired");
1718     PRINT_DISPOSITION(VISUAL_IMPAIRED,  "visual_impaired");
1719     PRINT_DISPOSITION(CLEAN_EFFECTS,    "clean_effects");
1720     PRINT_DISPOSITION(ATTACHED_PIC,     "attached_pic");
1721     writer_print_section_footer(w);
1722
1723     show_tags(w, stream->metadata, SECTION_ID_STREAM_TAGS);
1724
1725     writer_print_section_footer(w);
1726     av_bprint_finalize(&pbuf, NULL);
1727     fflush(stdout);
1728 }
1729
1730 static void show_streams(WriterContext *w, AVFormatContext *fmt_ctx)
1731 {
1732     int i;
1733     writer_print_section_header(w, SECTION_ID_STREAMS);
1734     for (i = 0; i < fmt_ctx->nb_streams; i++)
1735         if (selected_streams[i])
1736             show_stream(w, fmt_ctx, i);
1737     writer_print_section_footer(w);
1738 }
1739
1740 static void show_format(WriterContext *w, AVFormatContext *fmt_ctx)
1741 {
1742     char val_str[128];
1743     int64_t size = fmt_ctx->pb ? avio_size(fmt_ctx->pb) : -1;
1744
1745     writer_print_section_header(w, SECTION_ID_FORMAT);
1746     print_str("filename",         fmt_ctx->filename);
1747     print_int("nb_streams",       fmt_ctx->nb_streams);
1748     print_str("format_name",      fmt_ctx->iformat->name);
1749     if (!do_bitexact) {
1750         if (fmt_ctx->iformat->long_name) print_str    ("format_long_name", fmt_ctx->iformat->long_name);
1751         else                             print_str_opt("format_long_name", "unknown");
1752     }
1753     print_time("start_time",      fmt_ctx->start_time, &AV_TIME_BASE_Q);
1754     print_time("duration",        fmt_ctx->duration,   &AV_TIME_BASE_Q);
1755     if (size >= 0) print_val    ("size", size, unit_byte_str);
1756     else           print_str_opt("size", "N/A");
1757     if (fmt_ctx->bit_rate > 0) print_val    ("bit_rate", fmt_ctx->bit_rate, unit_bit_per_second_str);
1758     else                       print_str_opt("bit_rate", "N/A");
1759     show_tags(w, fmt_ctx->metadata, SECTION_ID_FORMAT_TAGS);
1760
1761     writer_print_section_footer(w);
1762     fflush(stdout);
1763 }
1764
1765 static void show_error(WriterContext *w, int err)
1766 {
1767     char errbuf[128];
1768     const char *errbuf_ptr = errbuf;
1769
1770     if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
1771         errbuf_ptr = strerror(AVUNERROR(err));
1772
1773     writer_print_section_header(w, SECTION_ID_ERROR);
1774     print_int("code", err);
1775     print_str("string", errbuf_ptr);
1776     writer_print_section_footer(w);
1777 }
1778
1779 static int open_input_file(AVFormatContext **fmt_ctx_ptr, const char *filename)
1780 {
1781     int err, i;
1782     AVFormatContext *fmt_ctx = NULL;
1783     AVDictionaryEntry *t;
1784
1785     if ((err = avformat_open_input(&fmt_ctx, filename,
1786                                    iformat, &format_opts)) < 0) {
1787         print_error(filename, err);
1788         return err;
1789     }
1790     if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
1791         av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
1792         return AVERROR_OPTION_NOT_FOUND;
1793     }
1794
1795
1796     /* fill the streams in the format context */
1797     if ((err = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
1798         print_error(filename, err);
1799         return err;
1800     }
1801
1802     av_dump_format(fmt_ctx, 0, filename, 0);
1803
1804     /* bind a decoder to each input stream */
1805     for (i = 0; i < fmt_ctx->nb_streams; i++) {
1806         AVStream *stream = fmt_ctx->streams[i];
1807         AVCodec *codec;
1808
1809         if (stream->codec->codec_id == AV_CODEC_ID_PROBE) {
1810             av_log(NULL, AV_LOG_ERROR,
1811                    "Failed to probe codec for input stream %d\n",
1812                     stream->index);
1813         } else if (!(codec = avcodec_find_decoder(stream->codec->codec_id))) {
1814             av_log(NULL, AV_LOG_ERROR,
1815                     "Unsupported codec with id %d for input stream %d\n",
1816                     stream->codec->codec_id, stream->index);
1817         } else if (avcodec_open2(stream->codec, codec, NULL) < 0) {
1818             av_log(NULL, AV_LOG_ERROR, "Error while opening codec for input stream %d\n",
1819                    stream->index);
1820         }
1821     }
1822
1823     *fmt_ctx_ptr = fmt_ctx;
1824     return 0;
1825 }
1826
1827 static void close_input_file(AVFormatContext **ctx_ptr)
1828 {
1829     int i;
1830     AVFormatContext *fmt_ctx = *ctx_ptr;
1831
1832     /* close decoder for each stream */
1833     for (i = 0; i < fmt_ctx->nb_streams; i++)
1834         if (fmt_ctx->streams[i]->codec->codec_id != AV_CODEC_ID_NONE)
1835             avcodec_close(fmt_ctx->streams[i]->codec);
1836
1837     avformat_close_input(ctx_ptr);
1838 }
1839
1840 static int probe_file(WriterContext *wctx, const char *filename)
1841 {
1842     AVFormatContext *fmt_ctx;
1843     int ret, i;
1844     int section_id;
1845
1846     do_read_frames = do_show_frames || do_count_frames;
1847     do_read_packets = do_show_packets || do_count_packets;
1848
1849     ret = open_input_file(&fmt_ctx, filename);
1850     if (ret >= 0) {
1851         nb_streams_frames  = av_calloc(fmt_ctx->nb_streams, sizeof(*nb_streams_frames));
1852         nb_streams_packets = av_calloc(fmt_ctx->nb_streams, sizeof(*nb_streams_packets));
1853         selected_streams   = av_calloc(fmt_ctx->nb_streams, sizeof(*selected_streams));
1854
1855         for (i = 0; i < fmt_ctx->nb_streams; i++) {
1856             if (stream_specifier) {
1857                 ret = avformat_match_stream_specifier(fmt_ctx,
1858                                                       fmt_ctx->streams[i],
1859                                                       stream_specifier);
1860                 if (ret < 0)
1861                     goto end;
1862                 else
1863                     selected_streams[i] = ret;
1864             } else {
1865                 selected_streams[i] = 1;
1866             }
1867         }
1868
1869         if (do_read_frames || do_read_packets) {
1870             if (do_show_frames && do_show_packets &&
1871                 wctx->writer->flags & WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER)
1872                 section_id = SECTION_ID_PACKETS_AND_FRAMES;
1873             else if (do_show_packets && !do_show_frames)
1874                 section_id = SECTION_ID_PACKETS;
1875             else // (!do_show_packets && do_show_frames)
1876                 section_id = SECTION_ID_FRAMES;
1877             if (do_show_frames || do_show_packets)
1878                 writer_print_section_header(wctx, section_id);
1879             read_packets(wctx, fmt_ctx);
1880             if (do_show_frames || do_show_packets)
1881                 writer_print_section_footer(wctx);
1882         }
1883         if (do_show_streams)
1884             show_streams(wctx, fmt_ctx);
1885         if (do_show_format)
1886             show_format(wctx, fmt_ctx);
1887
1888     end:
1889         close_input_file(&fmt_ctx);
1890         av_freep(&nb_streams_frames);
1891         av_freep(&nb_streams_packets);
1892         av_freep(&selected_streams);
1893     }
1894     return ret;
1895 }
1896
1897 static void show_usage(void)
1898 {
1899     av_log(NULL, AV_LOG_INFO, "Simple multimedia streams analyzer\n");
1900     av_log(NULL, AV_LOG_INFO, "usage: %s [OPTIONS] [INPUT_FILE]\n", program_name);
1901     av_log(NULL, AV_LOG_INFO, "\n");
1902 }
1903
1904 static void ffprobe_show_program_version(WriterContext *w)
1905 {
1906     AVBPrint pbuf;
1907     av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
1908
1909     writer_print_section_header(w, SECTION_ID_PROGRAM_VERSION);
1910     print_str("version", FFMPEG_VERSION);
1911     print_fmt("copyright", "Copyright (c) %d-%d the FFmpeg developers",
1912               program_birth_year, this_year);
1913     print_str("build_date", __DATE__);
1914     print_str("build_time", __TIME__);
1915     print_str("compiler_ident", CC_IDENT);
1916     print_str("configuration", FFMPEG_CONFIGURATION);
1917     writer_print_section_footer(w);
1918
1919     av_bprint_finalize(&pbuf, NULL);
1920 }
1921
1922 #define SHOW_LIB_VERSION(libname, LIBNAME)                              \
1923     do {                                                                \
1924         if (CONFIG_##LIBNAME) {                                         \
1925             unsigned int version = libname##_version();                 \
1926             writer_print_section_header(w, SECTION_ID_LIBRARY_VERSION); \
1927             print_str("name",    "lib" #libname);                       \
1928             print_int("major",   LIB##LIBNAME##_VERSION_MAJOR);         \
1929             print_int("minor",   LIB##LIBNAME##_VERSION_MINOR);         \
1930             print_int("micro",   LIB##LIBNAME##_VERSION_MICRO);         \
1931             print_int("version", version);                              \
1932             print_str("ident",   LIB##LIBNAME##_IDENT);                 \
1933             writer_print_section_footer(w);                             \
1934         }                                                               \
1935     } while (0)
1936
1937 static void ffprobe_show_library_versions(WriterContext *w)
1938 {
1939     writer_print_section_header(w, SECTION_ID_LIBRARY_VERSIONS);
1940     SHOW_LIB_VERSION(avutil,     AVUTIL);
1941     SHOW_LIB_VERSION(avcodec,    AVCODEC);
1942     SHOW_LIB_VERSION(avformat,   AVFORMAT);
1943     SHOW_LIB_VERSION(avdevice,   AVDEVICE);
1944     SHOW_LIB_VERSION(avfilter,   AVFILTER);
1945     SHOW_LIB_VERSION(swscale,    SWSCALE);
1946     SHOW_LIB_VERSION(swresample, SWRESAMPLE);
1947     SHOW_LIB_VERSION(postproc,   POSTPROC);
1948     writer_print_section_footer(w);
1949 }
1950
1951 static int opt_format(void *optctx, const char *opt, const char *arg)
1952 {
1953     iformat = av_find_input_format(arg);
1954     if (!iformat) {
1955         av_log(NULL, AV_LOG_ERROR, "Unknown input format: %s\n", arg);
1956         return AVERROR(EINVAL);
1957     }
1958     return 0;
1959 }
1960
1961 static int opt_show_format_entry(void *optctx, const char *opt, const char *arg)
1962 {
1963     do_show_format = 1;
1964     av_dict_set(&fmt_entries_to_show, arg, "", 0);
1965     return 0;
1966 }
1967
1968 static void opt_input_file(void *optctx, const char *arg)
1969 {
1970     if (input_filename) {
1971         av_log(NULL, AV_LOG_ERROR,
1972                 "Argument '%s' provided as input filename, but '%s' was already specified.\n",
1973                 arg, input_filename);
1974         exit(1);
1975     }
1976     if (!strcmp(arg, "-"))
1977         arg = "pipe:";
1978     input_filename = arg;
1979 }
1980
1981 static int opt_input_file_i(void *optctx, const char *opt, const char *arg)
1982 {
1983     opt_input_file(optctx, arg);
1984     return 0;
1985 }
1986
1987 void show_help_default(const char *opt, const char *arg)
1988 {
1989     av_log_set_callback(log_callback_help);
1990     show_usage();
1991     show_help_options(options, "Main options:", 0, 0, 0);
1992     printf("\n");
1993
1994     show_help_children(avformat_get_class(), AV_OPT_FLAG_DECODING_PARAM);
1995 }
1996
1997 static int opt_pretty(void *optctx, const char *opt, const char *arg)
1998 {
1999     show_value_unit              = 1;
2000     use_value_prefix             = 1;
2001     use_byte_value_binary_prefix = 1;
2002     use_value_sexagesimal_format = 1;
2003     return 0;
2004 }
2005
2006 static int opt_show_versions(const char *opt, const char *arg)
2007 {
2008     do_show_program_version  = 1;
2009     do_show_library_versions = 1;
2010     return 0;
2011 }
2012
2013 static const OptionDef real_options[] = {
2014 #include "cmdutils_common_opts.h"
2015     { "f", HAS_ARG, {.func_arg = opt_format}, "force format", "format" },
2016     { "unit", OPT_BOOL, {&show_value_unit}, "show unit of the displayed values" },
2017     { "prefix", OPT_BOOL, {&use_value_prefix}, "use SI prefixes for the displayed values" },
2018     { "byte_binary_prefix", OPT_BOOL, {&use_byte_value_binary_prefix},
2019       "use binary prefixes for byte units" },
2020     { "sexagesimal", OPT_BOOL,  {&use_value_sexagesimal_format},
2021       "use sexagesimal format HOURS:MM:SS.MICROSECONDS for time units" },
2022     { "pretty", 0, {.func_arg = opt_pretty},
2023       "prettify the format of displayed values, make it more human readable" },
2024     { "print_format", OPT_STRING | HAS_ARG, {(void*)&print_format},
2025       "set the output printing format (available formats are: default, compact, csv, flat, ini, json, xml)", "format" },
2026     { "of", OPT_STRING | HAS_ARG, {(void*)&print_format}, "alias for -print_format", "format" },
2027     { "select_streams", OPT_STRING | HAS_ARG, {(void*)&stream_specifier}, "select the specified streams", "stream_specifier" },
2028     { "show_data",    OPT_BOOL, {(void*)&do_show_data}, "show packets data" },
2029     { "show_error",   OPT_BOOL, {(void*)&do_show_error} ,  "show probing error" },
2030     { "show_format",  OPT_BOOL, {&do_show_format} , "show format/container info" },
2031     { "show_frames",  OPT_BOOL, {(void*)&do_show_frames} , "show frames info" },
2032     { "show_format_entry", HAS_ARG, {.func_arg = opt_show_format_entry},
2033       "show a particular entry from the format/container info", "entry" },
2034     { "show_packets", OPT_BOOL, {&do_show_packets}, "show packets info" },
2035     { "show_streams", OPT_BOOL, {&do_show_streams}, "show streams info" },
2036     { "count_frames", OPT_BOOL, {(void*)&do_count_frames}, "count the number of frames per stream" },
2037     { "count_packets", OPT_BOOL, {(void*)&do_count_packets}, "count the number of packets per stream" },
2038     { "show_program_version",  OPT_BOOL, {(void*)&do_show_program_version},  "show ffprobe version" },
2039     { "show_library_versions", OPT_BOOL, {(void*)&do_show_library_versions}, "show library versions" },
2040     { "show_versions",         0, {(void*)&opt_show_versions}, "show program and library versions" },
2041     { "show_private_data", OPT_BOOL, {(void*)&show_private_data}, "show private data" },
2042     { "private",           OPT_BOOL, {(void*)&show_private_data}, "same as show_private_data" },
2043     { "bitexact", OPT_BOOL, {&do_bitexact}, "force bitexact output" },
2044     { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {.func_arg = opt_default}, "generic catch all option", "" },
2045     { "i", HAS_ARG, {.func_arg = opt_input_file_i}, "read specified file", "input_file"},
2046     { NULL, },
2047 };
2048
2049 int main(int argc, char **argv)
2050 {
2051     const Writer *w;
2052     WriterContext *wctx;
2053     char *buf;
2054     char *w_name = NULL, *w_args = NULL;
2055     int ret;
2056
2057     av_log_set_flags(AV_LOG_SKIP_REPEATED);
2058     atexit(exit_program);
2059
2060     options = real_options;
2061     parse_loglevel(argc, argv, options);
2062     av_register_all();
2063     avformat_network_init();
2064     init_opts();
2065 #if CONFIG_AVDEVICE
2066     avdevice_register_all();
2067 #endif
2068
2069     show_banner(argc, argv, options);
2070     parse_options(NULL, argc, argv, options, opt_input_file);
2071
2072     if (do_bitexact && (do_show_program_version || do_show_library_versions)) {
2073         av_log(NULL, AV_LOG_ERROR,
2074                "-bitexact and -show_program_version or -show_library_versions "
2075                "options are incompatible\n");
2076         ret = AVERROR(EINVAL);
2077         goto end;
2078     }
2079
2080     writer_register_all();
2081
2082     if (!print_format)
2083         print_format = av_strdup("default");
2084     if (!print_format) {
2085         ret = AVERROR(ENOMEM);
2086         goto end;
2087     }
2088     w_name = av_strtok(print_format, "=", &buf);
2089     w_args = buf;
2090
2091     w = writer_get_by_name(w_name);
2092     if (!w) {
2093         av_log(NULL, AV_LOG_ERROR, "Unknown output format with name '%s'\n", w_name);
2094         ret = AVERROR(EINVAL);
2095         goto end;
2096     }
2097
2098     if ((ret = writer_open(&wctx, w, w_args,
2099                            sections, FF_ARRAY_ELEMS(sections))) >= 0) {
2100         writer_print_section_header(wctx, SECTION_ID_ROOT);
2101
2102         if (do_show_program_version)
2103             ffprobe_show_program_version(wctx);
2104         if (do_show_library_versions)
2105             ffprobe_show_library_versions(wctx);
2106
2107         if (!input_filename &&
2108             ((do_show_format || do_show_streams || do_show_packets || do_show_error) ||
2109              (!do_show_program_version && !do_show_library_versions))) {
2110             show_usage();
2111             av_log(NULL, AV_LOG_ERROR, "You have to specify one input file.\n");
2112             av_log(NULL, AV_LOG_ERROR, "Use -h to get full help or, even better, run 'man %s'.\n", program_name);
2113             ret = AVERROR(EINVAL);
2114         } else if (input_filename) {
2115             ret = probe_file(wctx, input_filename);
2116             if (ret < 0 && do_show_error)
2117                 show_error(wctx, ret);
2118         }
2119
2120         writer_print_section_footer(wctx);
2121         writer_close(&wctx);
2122     }
2123
2124 end:
2125     av_freep(&print_format);
2126
2127     uninit_opts();
2128     av_dict_free(&fmt_entries_to_show);
2129
2130     avformat_network_deinit();
2131
2132     return ret;
2133 }