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