You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3811 lines
140KB

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