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