ffprobe.c 163 KB

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