ffprobe.c 110 KB

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