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