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