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