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