ffmpeg.c 167 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809
  1. /*
  2. * Copyright (c) 2000-2003 Fabrice Bellard
  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. * multimedia converter based on the FFmpeg libraries
  23. */
  24. #include "config.h"
  25. #include <ctype.h>
  26. #include <string.h>
  27. #include <math.h>
  28. #include <stdlib.h>
  29. #include <errno.h>
  30. #include <limits.h>
  31. #include <stdatomic.h>
  32. #include <stdint.h>
  33. #if HAVE_IO_H
  34. #include <io.h>
  35. #endif
  36. #if HAVE_UNISTD_H
  37. #include <unistd.h>
  38. #endif
  39. #include "libavformat/avformat.h"
  40. #include "libavdevice/avdevice.h"
  41. #include "libswresample/swresample.h"
  42. #include "libavutil/opt.h"
  43. #include "libavutil/channel_layout.h"
  44. #include "libavutil/parseutils.h"
  45. #include "libavutil/samplefmt.h"
  46. #include "libavutil/fifo.h"
  47. #include "libavutil/hwcontext.h"
  48. #include "libavutil/internal.h"
  49. #include "libavutil/intreadwrite.h"
  50. #include "libavutil/dict.h"
  51. #include "libavutil/display.h"
  52. #include "libavutil/mathematics.h"
  53. #include "libavutil/pixdesc.h"
  54. #include "libavutil/avstring.h"
  55. #include "libavutil/libm.h"
  56. #include "libavutil/imgutils.h"
  57. #include "libavutil/timestamp.h"
  58. #include "libavutil/bprint.h"
  59. #include "libavutil/time.h"
  60. #include "libavutil/threadmessage.h"
  61. #include "libavcodec/mathops.h"
  62. #include "libavformat/os_support.h"
  63. # include "libavfilter/avfilter.h"
  64. # include "libavfilter/buffersrc.h"
  65. # include "libavfilter/buffersink.h"
  66. #if HAVE_SYS_RESOURCE_H
  67. #include <sys/time.h>
  68. #include <sys/types.h>
  69. #include <sys/resource.h>
  70. #elif HAVE_GETPROCESSTIMES
  71. #include <windows.h>
  72. #endif
  73. #if HAVE_GETPROCESSMEMORYINFO
  74. #include <windows.h>
  75. #include <psapi.h>
  76. #endif
  77. #if HAVE_SETCONSOLECTRLHANDLER
  78. #include <windows.h>
  79. #endif
  80. #if HAVE_SYS_SELECT_H
  81. #include <sys/select.h>
  82. #endif
  83. #if HAVE_TERMIOS_H
  84. #include <fcntl.h>
  85. #include <sys/ioctl.h>
  86. #include <sys/time.h>
  87. #include <termios.h>
  88. #elif HAVE_KBHIT
  89. #include <conio.h>
  90. #endif
  91. #if HAVE_PTHREADS
  92. #include <pthread.h>
  93. #endif
  94. #include <time.h>
  95. #include "ffmpeg.h"
  96. #include "cmdutils.h"
  97. #include "libavutil/avassert.h"
  98. const char program_name[] = "ffmpeg";
  99. const int program_birth_year = 2000;
  100. static FILE *vstats_file;
  101. const char *const forced_keyframes_const_names[] = {
  102. "n",
  103. "n_forced",
  104. "prev_forced_n",
  105. "prev_forced_t",
  106. "t",
  107. NULL
  108. };
  109. static void do_video_stats(OutputStream *ost, int frame_size);
  110. static int64_t getutime(void);
  111. static int64_t getmaxrss(void);
  112. static int ifilter_has_all_input_formats(FilterGraph *fg);
  113. static int run_as_daemon = 0;
  114. static int nb_frames_dup = 0;
  115. static unsigned dup_warning = 1000;
  116. static int nb_frames_drop = 0;
  117. static int64_t decode_error_stat[2];
  118. static int want_sdp = 1;
  119. static int current_time;
  120. AVIOContext *progress_avio = NULL;
  121. static uint8_t *subtitle_out;
  122. InputStream **input_streams = NULL;
  123. int nb_input_streams = 0;
  124. InputFile **input_files = NULL;
  125. int nb_input_files = 0;
  126. OutputStream **output_streams = NULL;
  127. int nb_output_streams = 0;
  128. OutputFile **output_files = NULL;
  129. int nb_output_files = 0;
  130. FilterGraph **filtergraphs;
  131. int nb_filtergraphs;
  132. #if HAVE_TERMIOS_H
  133. /* init terminal so that we can grab keys */
  134. static struct termios oldtty;
  135. static int restore_tty;
  136. #endif
  137. #if HAVE_PTHREADS
  138. static void free_input_threads(void);
  139. #endif
  140. /* sub2video hack:
  141. Convert subtitles to video with alpha to insert them in filter graphs.
  142. This is a temporary solution until libavfilter gets real subtitles support.
  143. */
  144. static int sub2video_get_blank_frame(InputStream *ist)
  145. {
  146. int ret;
  147. AVFrame *frame = ist->sub2video.frame;
  148. av_frame_unref(frame);
  149. ist->sub2video.frame->width = ist->dec_ctx->width ? ist->dec_ctx->width : ist->sub2video.w;
  150. ist->sub2video.frame->height = ist->dec_ctx->height ? ist->dec_ctx->height : ist->sub2video.h;
  151. ist->sub2video.frame->format = AV_PIX_FMT_RGB32;
  152. if ((ret = av_frame_get_buffer(frame, 32)) < 0)
  153. return ret;
  154. memset(frame->data[0], 0, frame->height * frame->linesize[0]);
  155. return 0;
  156. }
  157. static void sub2video_copy_rect(uint8_t *dst, int dst_linesize, int w, int h,
  158. AVSubtitleRect *r)
  159. {
  160. uint32_t *pal, *dst2;
  161. uint8_t *src, *src2;
  162. int x, y;
  163. if (r->type != SUBTITLE_BITMAP) {
  164. av_log(NULL, AV_LOG_WARNING, "sub2video: non-bitmap subtitle\n");
  165. return;
  166. }
  167. if (r->x < 0 || r->x + r->w > w || r->y < 0 || r->y + r->h > h) {
  168. av_log(NULL, AV_LOG_WARNING, "sub2video: rectangle (%d %d %d %d) overflowing %d %d\n",
  169. r->x, r->y, r->w, r->h, w, h
  170. );
  171. return;
  172. }
  173. dst += r->y * dst_linesize + r->x * 4;
  174. src = r->data[0];
  175. pal = (uint32_t *)r->data[1];
  176. for (y = 0; y < r->h; y++) {
  177. dst2 = (uint32_t *)dst;
  178. src2 = src;
  179. for (x = 0; x < r->w; x++)
  180. *(dst2++) = pal[*(src2++)];
  181. dst += dst_linesize;
  182. src += r->linesize[0];
  183. }
  184. }
  185. static void sub2video_push_ref(InputStream *ist, int64_t pts)
  186. {
  187. AVFrame *frame = ist->sub2video.frame;
  188. int i;
  189. av_assert1(frame->data[0]);
  190. ist->sub2video.last_pts = frame->pts = pts;
  191. for (i = 0; i < ist->nb_filters; i++)
  192. av_buffersrc_add_frame_flags(ist->filters[i]->filter, frame,
  193. AV_BUFFERSRC_FLAG_KEEP_REF |
  194. AV_BUFFERSRC_FLAG_PUSH);
  195. }
  196. void sub2video_update(InputStream *ist, AVSubtitle *sub)
  197. {
  198. AVFrame *frame = ist->sub2video.frame;
  199. int8_t *dst;
  200. int dst_linesize;
  201. int num_rects, i;
  202. int64_t pts, end_pts;
  203. if (!frame)
  204. return;
  205. if (sub) {
  206. pts = av_rescale_q(sub->pts + sub->start_display_time * 1000LL,
  207. AV_TIME_BASE_Q, ist->st->time_base);
  208. end_pts = av_rescale_q(sub->pts + sub->end_display_time * 1000LL,
  209. AV_TIME_BASE_Q, ist->st->time_base);
  210. num_rects = sub->num_rects;
  211. } else {
  212. pts = ist->sub2video.end_pts;
  213. end_pts = INT64_MAX;
  214. num_rects = 0;
  215. }
  216. if (sub2video_get_blank_frame(ist) < 0) {
  217. av_log(ist->dec_ctx, AV_LOG_ERROR,
  218. "Impossible to get a blank canvas.\n");
  219. return;
  220. }
  221. dst = frame->data [0];
  222. dst_linesize = frame->linesize[0];
  223. for (i = 0; i < num_rects; i++)
  224. sub2video_copy_rect(dst, dst_linesize, frame->width, frame->height, sub->rects[i]);
  225. sub2video_push_ref(ist, pts);
  226. ist->sub2video.end_pts = end_pts;
  227. }
  228. static void sub2video_heartbeat(InputStream *ist, int64_t pts)
  229. {
  230. InputFile *infile = input_files[ist->file_index];
  231. int i, j, nb_reqs;
  232. int64_t pts2;
  233. /* When a frame is read from a file, examine all sub2video streams in
  234. the same file and send the sub2video frame again. Otherwise, decoded
  235. video frames could be accumulating in the filter graph while a filter
  236. (possibly overlay) is desperately waiting for a subtitle frame. */
  237. for (i = 0; i < infile->nb_streams; i++) {
  238. InputStream *ist2 = input_streams[infile->ist_index + i];
  239. if (!ist2->sub2video.frame)
  240. continue;
  241. /* subtitles seem to be usually muxed ahead of other streams;
  242. if not, subtracting a larger time here is necessary */
  243. pts2 = av_rescale_q(pts, ist->st->time_base, ist2->st->time_base) - 1;
  244. /* do not send the heartbeat frame if the subtitle is already ahead */
  245. if (pts2 <= ist2->sub2video.last_pts)
  246. continue;
  247. if (pts2 >= ist2->sub2video.end_pts || !ist2->sub2video.frame->data[0])
  248. sub2video_update(ist2, NULL);
  249. for (j = 0, nb_reqs = 0; j < ist2->nb_filters; j++)
  250. nb_reqs += av_buffersrc_get_nb_failed_requests(ist2->filters[j]->filter);
  251. if (nb_reqs)
  252. sub2video_push_ref(ist2, pts2);
  253. }
  254. }
  255. static void sub2video_flush(InputStream *ist)
  256. {
  257. int i;
  258. if (ist->sub2video.end_pts < INT64_MAX)
  259. sub2video_update(ist, NULL);
  260. for (i = 0; i < ist->nb_filters; i++)
  261. av_buffersrc_add_frame(ist->filters[i]->filter, NULL);
  262. }
  263. /* end of sub2video hack */
  264. static void term_exit_sigsafe(void)
  265. {
  266. #if HAVE_TERMIOS_H
  267. if(restore_tty)
  268. tcsetattr (0, TCSANOW, &oldtty);
  269. #endif
  270. }
  271. void term_exit(void)
  272. {
  273. av_log(NULL, AV_LOG_QUIET, "%s", "");
  274. term_exit_sigsafe();
  275. }
  276. static volatile int received_sigterm = 0;
  277. static volatile int received_nb_signals = 0;
  278. static atomic_int transcode_init_done = ATOMIC_VAR_INIT(0);
  279. static volatile int ffmpeg_exited = 0;
  280. static int main_return_code = 0;
  281. static void
  282. sigterm_handler(int sig)
  283. {
  284. received_sigterm = sig;
  285. received_nb_signals++;
  286. term_exit_sigsafe();
  287. if(received_nb_signals > 3) {
  288. write(2/*STDERR_FILENO*/, "Received > 3 system signals, hard exiting\n",
  289. strlen("Received > 3 system signals, hard exiting\n"));
  290. exit(123);
  291. }
  292. }
  293. #if HAVE_SETCONSOLECTRLHANDLER
  294. static BOOL WINAPI CtrlHandler(DWORD fdwCtrlType)
  295. {
  296. av_log(NULL, AV_LOG_DEBUG, "\nReceived windows signal %ld\n", fdwCtrlType);
  297. switch (fdwCtrlType)
  298. {
  299. case CTRL_C_EVENT:
  300. case CTRL_BREAK_EVENT:
  301. sigterm_handler(SIGINT);
  302. return TRUE;
  303. case CTRL_CLOSE_EVENT:
  304. case CTRL_LOGOFF_EVENT:
  305. case CTRL_SHUTDOWN_EVENT:
  306. sigterm_handler(SIGTERM);
  307. /* Basically, with these 3 events, when we return from this method the
  308. process is hard terminated, so stall as long as we need to
  309. to try and let the main thread(s) clean up and gracefully terminate
  310. (we have at most 5 seconds, but should be done far before that). */
  311. while (!ffmpeg_exited) {
  312. Sleep(0);
  313. }
  314. return TRUE;
  315. default:
  316. av_log(NULL, AV_LOG_ERROR, "Received unknown windows signal %ld\n", fdwCtrlType);
  317. return FALSE;
  318. }
  319. }
  320. #endif
  321. void term_init(void)
  322. {
  323. #if HAVE_TERMIOS_H
  324. if (!run_as_daemon && stdin_interaction) {
  325. struct termios tty;
  326. if (tcgetattr (0, &tty) == 0) {
  327. oldtty = tty;
  328. restore_tty = 1;
  329. tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
  330. |INLCR|IGNCR|ICRNL|IXON);
  331. tty.c_oflag |= OPOST;
  332. tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
  333. tty.c_cflag &= ~(CSIZE|PARENB);
  334. tty.c_cflag |= CS8;
  335. tty.c_cc[VMIN] = 1;
  336. tty.c_cc[VTIME] = 0;
  337. tcsetattr (0, TCSANOW, &tty);
  338. }
  339. signal(SIGQUIT, sigterm_handler); /* Quit (POSIX). */
  340. }
  341. #endif
  342. signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
  343. signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
  344. #ifdef SIGXCPU
  345. signal(SIGXCPU, sigterm_handler);
  346. #endif
  347. #if HAVE_SETCONSOLECTRLHANDLER
  348. SetConsoleCtrlHandler((PHANDLER_ROUTINE) CtrlHandler, TRUE);
  349. #endif
  350. }
  351. /* read a key without blocking */
  352. static int read_key(void)
  353. {
  354. unsigned char ch;
  355. #if HAVE_TERMIOS_H
  356. int n = 1;
  357. struct timeval tv;
  358. fd_set rfds;
  359. FD_ZERO(&rfds);
  360. FD_SET(0, &rfds);
  361. tv.tv_sec = 0;
  362. tv.tv_usec = 0;
  363. n = select(1, &rfds, NULL, NULL, &tv);
  364. if (n > 0) {
  365. n = read(0, &ch, 1);
  366. if (n == 1)
  367. return ch;
  368. return n;
  369. }
  370. #elif HAVE_KBHIT
  371. # if HAVE_PEEKNAMEDPIPE
  372. static int is_pipe;
  373. static HANDLE input_handle;
  374. DWORD dw, nchars;
  375. if(!input_handle){
  376. input_handle = GetStdHandle(STD_INPUT_HANDLE);
  377. is_pipe = !GetConsoleMode(input_handle, &dw);
  378. }
  379. if (is_pipe) {
  380. /* When running under a GUI, you will end here. */
  381. if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL)) {
  382. // input pipe may have been closed by the program that ran ffmpeg
  383. return -1;
  384. }
  385. //Read it
  386. if(nchars != 0) {
  387. read(0, &ch, 1);
  388. return ch;
  389. }else{
  390. return -1;
  391. }
  392. }
  393. # endif
  394. if(kbhit())
  395. return(getch());
  396. #endif
  397. return -1;
  398. }
  399. static int decode_interrupt_cb(void *ctx)
  400. {
  401. return received_nb_signals > atomic_load(&transcode_init_done);
  402. }
  403. const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
  404. static void ffmpeg_cleanup(int ret)
  405. {
  406. int i, j;
  407. if (do_benchmark) {
  408. int maxrss = getmaxrss() / 1024;
  409. av_log(NULL, AV_LOG_INFO, "bench: maxrss=%ikB\n", maxrss);
  410. }
  411. for (i = 0; i < nb_filtergraphs; i++) {
  412. FilterGraph *fg = filtergraphs[i];
  413. avfilter_graph_free(&fg->graph);
  414. for (j = 0; j < fg->nb_inputs; j++) {
  415. while (av_fifo_size(fg->inputs[j]->frame_queue)) {
  416. AVFrame *frame;
  417. av_fifo_generic_read(fg->inputs[j]->frame_queue, &frame,
  418. sizeof(frame), NULL);
  419. av_frame_free(&frame);
  420. }
  421. av_fifo_free(fg->inputs[j]->frame_queue);
  422. if (fg->inputs[j]->ist->sub2video.sub_queue) {
  423. while (av_fifo_size(fg->inputs[j]->ist->sub2video.sub_queue)) {
  424. AVSubtitle sub;
  425. av_fifo_generic_read(fg->inputs[j]->ist->sub2video.sub_queue,
  426. &sub, sizeof(sub), NULL);
  427. avsubtitle_free(&sub);
  428. }
  429. av_fifo_free(fg->inputs[j]->ist->sub2video.sub_queue);
  430. }
  431. av_buffer_unref(&fg->inputs[j]->hw_frames_ctx);
  432. av_freep(&fg->inputs[j]->name);
  433. av_freep(&fg->inputs[j]);
  434. }
  435. av_freep(&fg->inputs);
  436. for (j = 0; j < fg->nb_outputs; j++) {
  437. av_freep(&fg->outputs[j]->name);
  438. av_freep(&fg->outputs[j]->formats);
  439. av_freep(&fg->outputs[j]->channel_layouts);
  440. av_freep(&fg->outputs[j]->sample_rates);
  441. av_freep(&fg->outputs[j]);
  442. }
  443. av_freep(&fg->outputs);
  444. av_freep(&fg->graph_desc);
  445. av_freep(&filtergraphs[i]);
  446. }
  447. av_freep(&filtergraphs);
  448. av_freep(&subtitle_out);
  449. /* close files */
  450. for (i = 0; i < nb_output_files; i++) {
  451. OutputFile *of = output_files[i];
  452. AVFormatContext *s;
  453. if (!of)
  454. continue;
  455. s = of->ctx;
  456. if (s && s->oformat && !(s->oformat->flags & AVFMT_NOFILE))
  457. avio_closep(&s->pb);
  458. avformat_free_context(s);
  459. av_dict_free(&of->opts);
  460. av_freep(&output_files[i]);
  461. }
  462. for (i = 0; i < nb_output_streams; i++) {
  463. OutputStream *ost = output_streams[i];
  464. if (!ost)
  465. continue;
  466. for (j = 0; j < ost->nb_bitstream_filters; j++)
  467. av_bsf_free(&ost->bsf_ctx[j]);
  468. av_freep(&ost->bsf_ctx);
  469. av_freep(&ost->bsf_extradata_updated);
  470. av_frame_free(&ost->filtered_frame);
  471. av_frame_free(&ost->last_frame);
  472. av_dict_free(&ost->encoder_opts);
  473. av_parser_close(ost->parser);
  474. avcodec_free_context(&ost->parser_avctx);
  475. av_freep(&ost->forced_keyframes);
  476. av_expr_free(ost->forced_keyframes_pexpr);
  477. av_freep(&ost->avfilter);
  478. av_freep(&ost->logfile_prefix);
  479. av_freep(&ost->audio_channels_map);
  480. ost->audio_channels_mapped = 0;
  481. av_dict_free(&ost->sws_dict);
  482. av_dict_free(&ost->swr_opts);
  483. avcodec_free_context(&ost->enc_ctx);
  484. avcodec_parameters_free(&ost->ref_par);
  485. if (ost->muxing_queue) {
  486. while (av_fifo_size(ost->muxing_queue)) {
  487. AVPacket pkt;
  488. av_fifo_generic_read(ost->muxing_queue, &pkt, sizeof(pkt), NULL);
  489. av_packet_unref(&pkt);
  490. }
  491. av_fifo_freep(&ost->muxing_queue);
  492. }
  493. av_freep(&output_streams[i]);
  494. }
  495. #if HAVE_PTHREADS
  496. free_input_threads();
  497. #endif
  498. for (i = 0; i < nb_input_files; i++) {
  499. avformat_close_input(&input_files[i]->ctx);
  500. av_freep(&input_files[i]);
  501. }
  502. for (i = 0; i < nb_input_streams; i++) {
  503. InputStream *ist = input_streams[i];
  504. av_frame_free(&ist->decoded_frame);
  505. av_frame_free(&ist->filter_frame);
  506. av_dict_free(&ist->decoder_opts);
  507. avsubtitle_free(&ist->prev_sub.subtitle);
  508. av_frame_free(&ist->sub2video.frame);
  509. av_freep(&ist->filters);
  510. av_freep(&ist->hwaccel_device);
  511. av_freep(&ist->dts_buffer);
  512. avcodec_free_context(&ist->dec_ctx);
  513. av_freep(&input_streams[i]);
  514. }
  515. if (vstats_file) {
  516. if (fclose(vstats_file))
  517. av_log(NULL, AV_LOG_ERROR,
  518. "Error closing vstats file, loss of information possible: %s\n",
  519. av_err2str(AVERROR(errno)));
  520. }
  521. av_freep(&vstats_filename);
  522. av_freep(&input_streams);
  523. av_freep(&input_files);
  524. av_freep(&output_streams);
  525. av_freep(&output_files);
  526. uninit_opts();
  527. avformat_network_deinit();
  528. if (received_sigterm) {
  529. av_log(NULL, AV_LOG_INFO, "Exiting normally, received signal %d.\n",
  530. (int) received_sigterm);
  531. } else if (ret && atomic_load(&transcode_init_done)) {
  532. av_log(NULL, AV_LOG_INFO, "Conversion failed!\n");
  533. }
  534. term_exit();
  535. ffmpeg_exited = 1;
  536. }
  537. void remove_avoptions(AVDictionary **a, AVDictionary *b)
  538. {
  539. AVDictionaryEntry *t = NULL;
  540. while ((t = av_dict_get(b, "", t, AV_DICT_IGNORE_SUFFIX))) {
  541. av_dict_set(a, t->key, NULL, AV_DICT_MATCH_CASE);
  542. }
  543. }
  544. void assert_avoptions(AVDictionary *m)
  545. {
  546. AVDictionaryEntry *t;
  547. if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
  548. av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
  549. exit_program(1);
  550. }
  551. }
  552. static void abort_codec_experimental(AVCodec *c, int encoder)
  553. {
  554. exit_program(1);
  555. }
  556. static void update_benchmark(const char *fmt, ...)
  557. {
  558. if (do_benchmark_all) {
  559. int64_t t = getutime();
  560. va_list va;
  561. char buf[1024];
  562. if (fmt) {
  563. va_start(va, fmt);
  564. vsnprintf(buf, sizeof(buf), fmt, va);
  565. va_end(va);
  566. av_log(NULL, AV_LOG_INFO, "bench: %8"PRIu64" %s \n", t - current_time, buf);
  567. }
  568. current_time = t;
  569. }
  570. }
  571. static void close_all_output_streams(OutputStream *ost, OSTFinished this_stream, OSTFinished others)
  572. {
  573. int i;
  574. for (i = 0; i < nb_output_streams; i++) {
  575. OutputStream *ost2 = output_streams[i];
  576. ost2->finished |= ost == ost2 ? this_stream : others;
  577. }
  578. }
  579. static void write_packet(OutputFile *of, AVPacket *pkt, OutputStream *ost, int unqueue)
  580. {
  581. AVFormatContext *s = of->ctx;
  582. AVStream *st = ost->st;
  583. int ret;
  584. /*
  585. * Audio encoders may split the packets -- #frames in != #packets out.
  586. * But there is no reordering, so we can limit the number of output packets
  587. * by simply dropping them here.
  588. * Counting encoded video frames needs to be done separately because of
  589. * reordering, see do_video_out().
  590. * Do not count the packet when unqueued because it has been counted when queued.
  591. */
  592. if (!(st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && ost->encoding_needed) && !unqueue) {
  593. if (ost->frame_number >= ost->max_frames) {
  594. av_packet_unref(pkt);
  595. return;
  596. }
  597. ost->frame_number++;
  598. }
  599. if (!of->header_written) {
  600. AVPacket tmp_pkt = {0};
  601. /* the muxer is not initialized yet, buffer the packet */
  602. if (!av_fifo_space(ost->muxing_queue)) {
  603. int new_size = FFMIN(2 * av_fifo_size(ost->muxing_queue),
  604. ost->max_muxing_queue_size);
  605. if (new_size <= av_fifo_size(ost->muxing_queue)) {
  606. av_log(NULL, AV_LOG_ERROR,
  607. "Too many packets buffered for output stream %d:%d.\n",
  608. ost->file_index, ost->st->index);
  609. exit_program(1);
  610. }
  611. ret = av_fifo_realloc2(ost->muxing_queue, new_size);
  612. if (ret < 0)
  613. exit_program(1);
  614. }
  615. ret = av_packet_ref(&tmp_pkt, pkt);
  616. if (ret < 0)
  617. exit_program(1);
  618. av_fifo_generic_write(ost->muxing_queue, &tmp_pkt, sizeof(tmp_pkt), NULL);
  619. av_packet_unref(pkt);
  620. return;
  621. }
  622. if ((st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && video_sync_method == VSYNC_DROP) ||
  623. (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && audio_sync_method < 0))
  624. pkt->pts = pkt->dts = AV_NOPTS_VALUE;
  625. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  626. int i;
  627. uint8_t *sd = av_packet_get_side_data(pkt, AV_PKT_DATA_QUALITY_STATS,
  628. NULL);
  629. ost->quality = sd ? AV_RL32(sd) : -1;
  630. ost->pict_type = sd ? sd[4] : AV_PICTURE_TYPE_NONE;
  631. for (i = 0; i<FF_ARRAY_ELEMS(ost->error); i++) {
  632. if (sd && i < sd[5])
  633. ost->error[i] = AV_RL64(sd + 8 + 8*i);
  634. else
  635. ost->error[i] = -1;
  636. }
  637. if (ost->frame_rate.num && ost->is_cfr) {
  638. if (pkt->duration > 0)
  639. av_log(NULL, AV_LOG_WARNING, "Overriding packet duration by frame rate, this should not happen\n");
  640. pkt->duration = av_rescale_q(1, av_inv_q(ost->frame_rate),
  641. ost->mux_timebase);
  642. }
  643. }
  644. av_packet_rescale_ts(pkt, ost->mux_timebase, ost->st->time_base);
  645. if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
  646. if (pkt->dts != AV_NOPTS_VALUE &&
  647. pkt->pts != AV_NOPTS_VALUE &&
  648. pkt->dts > pkt->pts) {
  649. av_log(s, AV_LOG_WARNING, "Invalid DTS: %"PRId64" PTS: %"PRId64" in output stream %d:%d, replacing by guess\n",
  650. pkt->dts, pkt->pts,
  651. ost->file_index, ost->st->index);
  652. pkt->pts =
  653. pkt->dts = pkt->pts + pkt->dts + ost->last_mux_dts + 1
  654. - FFMIN3(pkt->pts, pkt->dts, ost->last_mux_dts + 1)
  655. - FFMAX3(pkt->pts, pkt->dts, ost->last_mux_dts + 1);
  656. }
  657. if ((st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) &&
  658. pkt->dts != AV_NOPTS_VALUE &&
  659. !(st->codecpar->codec_id == AV_CODEC_ID_VP9 && ost->stream_copy) &&
  660. ost->last_mux_dts != AV_NOPTS_VALUE) {
  661. int64_t max = ost->last_mux_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);
  662. if (pkt->dts < max) {
  663. int loglevel = max - pkt->dts > 2 || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ? AV_LOG_WARNING : AV_LOG_DEBUG;
  664. av_log(s, loglevel, "Non-monotonous DTS in output stream "
  665. "%d:%d; previous: %"PRId64", current: %"PRId64"; ",
  666. ost->file_index, ost->st->index, ost->last_mux_dts, pkt->dts);
  667. if (exit_on_error) {
  668. av_log(NULL, AV_LOG_FATAL, "aborting.\n");
  669. exit_program(1);
  670. }
  671. av_log(s, loglevel, "changing to %"PRId64". This may result "
  672. "in incorrect timestamps in the output file.\n",
  673. max);
  674. if (pkt->pts >= pkt->dts)
  675. pkt->pts = FFMAX(pkt->pts, max);
  676. pkt->dts = max;
  677. }
  678. }
  679. }
  680. ost->last_mux_dts = pkt->dts;
  681. ost->data_size += pkt->size;
  682. ost->packets_written++;
  683. pkt->stream_index = ost->index;
  684. if (debug_ts) {
  685. av_log(NULL, AV_LOG_INFO, "muxer <- type:%s "
  686. "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s size:%d\n",
  687. av_get_media_type_string(ost->enc_ctx->codec_type),
  688. av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &ost->st->time_base),
  689. av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &ost->st->time_base),
  690. pkt->size
  691. );
  692. }
  693. ret = av_interleaved_write_frame(s, pkt);
  694. if (ret < 0) {
  695. print_error("av_interleaved_write_frame()", ret);
  696. main_return_code = 1;
  697. close_all_output_streams(ost, MUXER_FINISHED | ENCODER_FINISHED, ENCODER_FINISHED);
  698. }
  699. av_packet_unref(pkt);
  700. }
  701. static void close_output_stream(OutputStream *ost)
  702. {
  703. OutputFile *of = output_files[ost->file_index];
  704. ost->finished |= ENCODER_FINISHED;
  705. if (of->shortest) {
  706. int64_t end = av_rescale_q(ost->sync_opts - ost->first_pts, ost->enc_ctx->time_base, AV_TIME_BASE_Q);
  707. of->recording_time = FFMIN(of->recording_time, end);
  708. }
  709. }
  710. static void output_packet(OutputFile *of, AVPacket *pkt, OutputStream *ost)
  711. {
  712. int ret = 0;
  713. /* apply the output bitstream filters, if any */
  714. if (ost->nb_bitstream_filters) {
  715. int idx;
  716. ret = av_bsf_send_packet(ost->bsf_ctx[0], pkt);
  717. if (ret < 0)
  718. goto finish;
  719. idx = 1;
  720. while (idx) {
  721. /* get a packet from the previous filter up the chain */
  722. ret = av_bsf_receive_packet(ost->bsf_ctx[idx - 1], pkt);
  723. if (ret == AVERROR(EAGAIN)) {
  724. ret = 0;
  725. idx--;
  726. continue;
  727. } else if (ret < 0)
  728. goto finish;
  729. /* HACK! - aac_adtstoasc updates extradata after filtering the first frame when
  730. * the api states this shouldn't happen after init(). Propagate it here to the
  731. * muxer and to the next filters in the chain to workaround this.
  732. * TODO/FIXME - Make aac_adtstoasc use new packet side data instead of changing
  733. * par_out->extradata and adapt muxers accordingly to get rid of this. */
  734. if (!(ost->bsf_extradata_updated[idx - 1] & 1)) {
  735. ret = avcodec_parameters_copy(ost->st->codecpar, ost->bsf_ctx[idx - 1]->par_out);
  736. if (ret < 0)
  737. goto finish;
  738. ost->bsf_extradata_updated[idx - 1] |= 1;
  739. }
  740. /* send it to the next filter down the chain or to the muxer */
  741. if (idx < ost->nb_bitstream_filters) {
  742. /* HACK/FIXME! - See above */
  743. if (!(ost->bsf_extradata_updated[idx] & 2)) {
  744. ret = avcodec_parameters_copy(ost->bsf_ctx[idx]->par_out, ost->bsf_ctx[idx - 1]->par_out);
  745. if (ret < 0)
  746. goto finish;
  747. ost->bsf_extradata_updated[idx] |= 2;
  748. }
  749. ret = av_bsf_send_packet(ost->bsf_ctx[idx], pkt);
  750. if (ret < 0)
  751. goto finish;
  752. idx++;
  753. } else
  754. write_packet(of, pkt, ost, 0);
  755. }
  756. } else
  757. write_packet(of, pkt, ost, 0);
  758. finish:
  759. if (ret < 0 && ret != AVERROR_EOF) {
  760. av_log(NULL, AV_LOG_ERROR, "Error applying bitstream filters to an output "
  761. "packet for stream #%d:%d.\n", ost->file_index, ost->index);
  762. if(exit_on_error)
  763. exit_program(1);
  764. }
  765. }
  766. static int check_recording_time(OutputStream *ost)
  767. {
  768. OutputFile *of = output_files[ost->file_index];
  769. if (of->recording_time != INT64_MAX &&
  770. av_compare_ts(ost->sync_opts - ost->first_pts, ost->enc_ctx->time_base, of->recording_time,
  771. AV_TIME_BASE_Q) >= 0) {
  772. close_output_stream(ost);
  773. return 0;
  774. }
  775. return 1;
  776. }
  777. static void do_audio_out(OutputFile *of, OutputStream *ost,
  778. AVFrame *frame)
  779. {
  780. AVCodecContext *enc = ost->enc_ctx;
  781. AVPacket pkt;
  782. int ret;
  783. av_init_packet(&pkt);
  784. pkt.data = NULL;
  785. pkt.size = 0;
  786. if (!check_recording_time(ost))
  787. return;
  788. if (frame->pts == AV_NOPTS_VALUE || audio_sync_method < 0)
  789. frame->pts = ost->sync_opts;
  790. ost->sync_opts = frame->pts + frame->nb_samples;
  791. ost->samples_encoded += frame->nb_samples;
  792. ost->frames_encoded++;
  793. av_assert0(pkt.size || !pkt.data);
  794. update_benchmark(NULL);
  795. if (debug_ts) {
  796. av_log(NULL, AV_LOG_INFO, "encoder <- type:audio "
  797. "frame_pts:%s frame_pts_time:%s time_base:%d/%d\n",
  798. av_ts2str(frame->pts), av_ts2timestr(frame->pts, &enc->time_base),
  799. enc->time_base.num, enc->time_base.den);
  800. }
  801. ret = avcodec_send_frame(enc, frame);
  802. if (ret < 0)
  803. goto error;
  804. while (1) {
  805. ret = avcodec_receive_packet(enc, &pkt);
  806. if (ret == AVERROR(EAGAIN))
  807. break;
  808. if (ret < 0)
  809. goto error;
  810. update_benchmark("encode_audio %d.%d", ost->file_index, ost->index);
  811. av_packet_rescale_ts(&pkt, enc->time_base, ost->mux_timebase);
  812. if (debug_ts) {
  813. av_log(NULL, AV_LOG_INFO, "encoder -> type:audio "
  814. "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
  815. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &enc->time_base),
  816. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &enc->time_base));
  817. }
  818. output_packet(of, &pkt, ost);
  819. }
  820. return;
  821. error:
  822. av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
  823. exit_program(1);
  824. }
  825. static void do_subtitle_out(OutputFile *of,
  826. OutputStream *ost,
  827. AVSubtitle *sub)
  828. {
  829. int subtitle_out_max_size = 1024 * 1024;
  830. int subtitle_out_size, nb, i;
  831. AVCodecContext *enc;
  832. AVPacket pkt;
  833. int64_t pts;
  834. if (sub->pts == AV_NOPTS_VALUE) {
  835. av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
  836. if (exit_on_error)
  837. exit_program(1);
  838. return;
  839. }
  840. enc = ost->enc_ctx;
  841. if (!subtitle_out) {
  842. subtitle_out = av_malloc(subtitle_out_max_size);
  843. if (!subtitle_out) {
  844. av_log(NULL, AV_LOG_FATAL, "Failed to allocate subtitle_out\n");
  845. exit_program(1);
  846. }
  847. }
  848. /* Note: DVB subtitle need one packet to draw them and one other
  849. packet to clear them */
  850. /* XXX: signal it in the codec context ? */
  851. if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
  852. nb = 2;
  853. else
  854. nb = 1;
  855. /* shift timestamp to honor -ss and make check_recording_time() work with -t */
  856. pts = sub->pts;
  857. if (output_files[ost->file_index]->start_time != AV_NOPTS_VALUE)
  858. pts -= output_files[ost->file_index]->start_time;
  859. for (i = 0; i < nb; i++) {
  860. unsigned save_num_rects = sub->num_rects;
  861. ost->sync_opts = av_rescale_q(pts, AV_TIME_BASE_Q, enc->time_base);
  862. if (!check_recording_time(ost))
  863. return;
  864. sub->pts = pts;
  865. // start_display_time is required to be 0
  866. sub->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
  867. sub->end_display_time -= sub->start_display_time;
  868. sub->start_display_time = 0;
  869. if (i == 1)
  870. sub->num_rects = 0;
  871. ost->frames_encoded++;
  872. subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
  873. subtitle_out_max_size, sub);
  874. if (i == 1)
  875. sub->num_rects = save_num_rects;
  876. if (subtitle_out_size < 0) {
  877. av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
  878. exit_program(1);
  879. }
  880. av_init_packet(&pkt);
  881. pkt.data = subtitle_out;
  882. pkt.size = subtitle_out_size;
  883. pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->mux_timebase);
  884. pkt.duration = av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, ost->mux_timebase);
  885. if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
  886. /* XXX: the pts correction is handled here. Maybe handling
  887. it in the codec would be better */
  888. if (i == 0)
  889. pkt.pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, ost->mux_timebase);
  890. else
  891. pkt.pts += av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, ost->mux_timebase);
  892. }
  893. pkt.dts = pkt.pts;
  894. output_packet(of, &pkt, ost);
  895. }
  896. }
  897. static void do_video_out(OutputFile *of,
  898. OutputStream *ost,
  899. AVFrame *next_picture,
  900. double sync_ipts)
  901. {
  902. int ret, format_video_sync;
  903. AVPacket pkt;
  904. AVCodecContext *enc = ost->enc_ctx;
  905. AVCodecParameters *mux_par = ost->st->codecpar;
  906. AVRational frame_rate;
  907. int nb_frames, nb0_frames, i;
  908. double delta, delta0;
  909. double duration = 0;
  910. int frame_size = 0;
  911. InputStream *ist = NULL;
  912. AVFilterContext *filter = ost->filter->filter;
  913. if (ost->source_index >= 0)
  914. ist = input_streams[ost->source_index];
  915. frame_rate = av_buffersink_get_frame_rate(filter);
  916. if (frame_rate.num > 0 && frame_rate.den > 0)
  917. duration = 1/(av_q2d(frame_rate) * av_q2d(enc->time_base));
  918. if(ist && ist->st->start_time != AV_NOPTS_VALUE && ist->st->first_dts != AV_NOPTS_VALUE && ost->frame_rate.num)
  919. duration = FFMIN(duration, 1/(av_q2d(ost->frame_rate) * av_q2d(enc->time_base)));
  920. if (!ost->filters_script &&
  921. !ost->filters &&
  922. next_picture &&
  923. ist &&
  924. lrintf(av_frame_get_pkt_duration(next_picture) * av_q2d(ist->st->time_base) / av_q2d(enc->time_base)) > 0) {
  925. duration = lrintf(av_frame_get_pkt_duration(next_picture) * av_q2d(ist->st->time_base) / av_q2d(enc->time_base));
  926. }
  927. if (!next_picture) {
  928. //end, flushing
  929. nb0_frames = nb_frames = mid_pred(ost->last_nb0_frames[0],
  930. ost->last_nb0_frames[1],
  931. ost->last_nb0_frames[2]);
  932. } else {
  933. delta0 = sync_ipts - ost->sync_opts; // delta0 is the "drift" between the input frame (next_picture) and where it would fall in the output.
  934. delta = delta0 + duration;
  935. /* by default, we output a single frame */
  936. nb0_frames = 0; // tracks the number of times the PREVIOUS frame should be duplicated, mostly for variable framerate (VFR)
  937. nb_frames = 1;
  938. format_video_sync = video_sync_method;
  939. if (format_video_sync == VSYNC_AUTO) {
  940. if(!strcmp(of->ctx->oformat->name, "avi")) {
  941. format_video_sync = VSYNC_VFR;
  942. } else
  943. format_video_sync = (of->ctx->oformat->flags & AVFMT_VARIABLE_FPS) ? ((of->ctx->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH : VSYNC_VFR) : VSYNC_CFR;
  944. if ( ist
  945. && format_video_sync == VSYNC_CFR
  946. && input_files[ist->file_index]->ctx->nb_streams == 1
  947. && input_files[ist->file_index]->input_ts_offset == 0) {
  948. format_video_sync = VSYNC_VSCFR;
  949. }
  950. if (format_video_sync == VSYNC_CFR && copy_ts) {
  951. format_video_sync = VSYNC_VSCFR;
  952. }
  953. }
  954. ost->is_cfr = (format_video_sync == VSYNC_CFR || format_video_sync == VSYNC_VSCFR);
  955. if (delta0 < 0 &&
  956. delta > 0 &&
  957. format_video_sync != VSYNC_PASSTHROUGH &&
  958. format_video_sync != VSYNC_DROP) {
  959. if (delta0 < -0.6) {
  960. av_log(NULL, AV_LOG_WARNING, "Past duration %f too large\n", -delta0);
  961. } else
  962. av_log(NULL, AV_LOG_DEBUG, "Clipping frame in rate conversion by %f\n", -delta0);
  963. sync_ipts = ost->sync_opts;
  964. duration += delta0;
  965. delta0 = 0;
  966. }
  967. switch (format_video_sync) {
  968. case VSYNC_VSCFR:
  969. if (ost->frame_number == 0 && delta0 >= 0.5) {
  970. av_log(NULL, AV_LOG_DEBUG, "Not duplicating %d initial frames\n", (int)lrintf(delta0));
  971. delta = duration;
  972. delta0 = 0;
  973. ost->sync_opts = lrint(sync_ipts);
  974. }
  975. case VSYNC_CFR:
  976. // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
  977. if (frame_drop_threshold && delta < frame_drop_threshold && ost->frame_number) {
  978. nb_frames = 0;
  979. } else if (delta < -1.1)
  980. nb_frames = 0;
  981. else if (delta > 1.1) {
  982. nb_frames = lrintf(delta);
  983. if (delta0 > 1.1)
  984. nb0_frames = lrintf(delta0 - 0.6);
  985. }
  986. break;
  987. case VSYNC_VFR:
  988. if (delta <= -0.6)
  989. nb_frames = 0;
  990. else if (delta > 0.6)
  991. ost->sync_opts = lrint(sync_ipts);
  992. break;
  993. case VSYNC_DROP:
  994. case VSYNC_PASSTHROUGH:
  995. ost->sync_opts = lrint(sync_ipts);
  996. break;
  997. default:
  998. av_assert0(0);
  999. }
  1000. }
  1001. nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
  1002. nb0_frames = FFMIN(nb0_frames, nb_frames);
  1003. memmove(ost->last_nb0_frames + 1,
  1004. ost->last_nb0_frames,
  1005. sizeof(ost->last_nb0_frames[0]) * (FF_ARRAY_ELEMS(ost->last_nb0_frames) - 1));
  1006. ost->last_nb0_frames[0] = nb0_frames;
  1007. if (nb0_frames == 0 && ost->last_dropped) {
  1008. nb_frames_drop++;
  1009. av_log(NULL, AV_LOG_VERBOSE,
  1010. "*** dropping frame %d from stream %d at ts %"PRId64"\n",
  1011. ost->frame_number, ost->st->index, ost->last_frame->pts);
  1012. }
  1013. if (nb_frames > (nb0_frames && ost->last_dropped) + (nb_frames > nb0_frames)) {
  1014. if (nb_frames > dts_error_threshold * 30) {
  1015. av_log(NULL, AV_LOG_ERROR, "%d frame duplication too large, skipping\n", nb_frames - 1);
  1016. nb_frames_drop++;
  1017. return;
  1018. }
  1019. nb_frames_dup += nb_frames - (nb0_frames && ost->last_dropped) - (nb_frames > nb0_frames);
  1020. av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);
  1021. if (nb_frames_dup > dup_warning) {
  1022. av_log(NULL, AV_LOG_WARNING, "More than %d frames duplicated\n", dup_warning);
  1023. dup_warning *= 10;
  1024. }
  1025. }
  1026. ost->last_dropped = nb_frames == nb0_frames && next_picture;
  1027. /* duplicates frame if needed */
  1028. for (i = 0; i < nb_frames; i++) {
  1029. AVFrame *in_picture;
  1030. av_init_packet(&pkt);
  1031. pkt.data = NULL;
  1032. pkt.size = 0;
  1033. if (i < nb0_frames && ost->last_frame) {
  1034. in_picture = ost->last_frame;
  1035. } else
  1036. in_picture = next_picture;
  1037. if (!in_picture)
  1038. return;
  1039. in_picture->pts = ost->sync_opts;
  1040. #if 1
  1041. if (!check_recording_time(ost))
  1042. #else
  1043. if (ost->frame_number >= ost->max_frames)
  1044. #endif
  1045. return;
  1046. #if FF_API_LAVF_FMT_RAWPICTURE
  1047. if (of->ctx->oformat->flags & AVFMT_RAWPICTURE &&
  1048. enc->codec->id == AV_CODEC_ID_RAWVIDEO) {
  1049. /* raw pictures are written as AVPicture structure to
  1050. avoid any copies. We support temporarily the older
  1051. method. */
  1052. if (in_picture->interlaced_frame)
  1053. mux_par->field_order = in_picture->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
  1054. else
  1055. mux_par->field_order = AV_FIELD_PROGRESSIVE;
  1056. pkt.data = (uint8_t *)in_picture;
  1057. pkt.size = sizeof(AVPicture);
  1058. pkt.pts = av_rescale_q(in_picture->pts, enc->time_base, ost->mux_timebase);
  1059. pkt.flags |= AV_PKT_FLAG_KEY;
  1060. output_packet(of, &pkt, ost);
  1061. } else
  1062. #endif
  1063. {
  1064. int forced_keyframe = 0;
  1065. double pts_time;
  1066. if (enc->flags & (AV_CODEC_FLAG_INTERLACED_DCT | AV_CODEC_FLAG_INTERLACED_ME) &&
  1067. ost->top_field_first >= 0)
  1068. in_picture->top_field_first = !!ost->top_field_first;
  1069. if (in_picture->interlaced_frame) {
  1070. if (enc->codec->id == AV_CODEC_ID_MJPEG)
  1071. mux_par->field_order = in_picture->top_field_first ? AV_FIELD_TT:AV_FIELD_BB;
  1072. else
  1073. mux_par->field_order = in_picture->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
  1074. } else
  1075. mux_par->field_order = AV_FIELD_PROGRESSIVE;
  1076. in_picture->quality = enc->global_quality;
  1077. in_picture->pict_type = 0;
  1078. pts_time = in_picture->pts != AV_NOPTS_VALUE ?
  1079. in_picture->pts * av_q2d(enc->time_base) : NAN;
  1080. if (ost->forced_kf_index < ost->forced_kf_count &&
  1081. in_picture->pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
  1082. ost->forced_kf_index++;
  1083. forced_keyframe = 1;
  1084. } else if (ost->forced_keyframes_pexpr) {
  1085. double res;
  1086. ost->forced_keyframes_expr_const_values[FKF_T] = pts_time;
  1087. res = av_expr_eval(ost->forced_keyframes_pexpr,
  1088. ost->forced_keyframes_expr_const_values, NULL);
  1089. ff_dlog(NULL, "force_key_frame: n:%f n_forced:%f prev_forced_n:%f t:%f prev_forced_t:%f -> res:%f\n",
  1090. ost->forced_keyframes_expr_const_values[FKF_N],
  1091. ost->forced_keyframes_expr_const_values[FKF_N_FORCED],
  1092. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N],
  1093. ost->forced_keyframes_expr_const_values[FKF_T],
  1094. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T],
  1095. res);
  1096. if (res) {
  1097. forced_keyframe = 1;
  1098. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] =
  1099. ost->forced_keyframes_expr_const_values[FKF_N];
  1100. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] =
  1101. ost->forced_keyframes_expr_const_values[FKF_T];
  1102. ost->forced_keyframes_expr_const_values[FKF_N_FORCED] += 1;
  1103. }
  1104. ost->forced_keyframes_expr_const_values[FKF_N] += 1;
  1105. } else if ( ost->forced_keyframes
  1106. && !strncmp(ost->forced_keyframes, "source", 6)
  1107. && in_picture->key_frame==1) {
  1108. forced_keyframe = 1;
  1109. }
  1110. if (forced_keyframe) {
  1111. in_picture->pict_type = AV_PICTURE_TYPE_I;
  1112. av_log(NULL, AV_LOG_DEBUG, "Forced keyframe at time %f\n", pts_time);
  1113. }
  1114. update_benchmark(NULL);
  1115. if (debug_ts) {
  1116. av_log(NULL, AV_LOG_INFO, "encoder <- type:video "
  1117. "frame_pts:%s frame_pts_time:%s time_base:%d/%d\n",
  1118. av_ts2str(in_picture->pts), av_ts2timestr(in_picture->pts, &enc->time_base),
  1119. enc->time_base.num, enc->time_base.den);
  1120. }
  1121. ost->frames_encoded++;
  1122. ret = avcodec_send_frame(enc, in_picture);
  1123. if (ret < 0)
  1124. goto error;
  1125. while (1) {
  1126. ret = avcodec_receive_packet(enc, &pkt);
  1127. update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
  1128. if (ret == AVERROR(EAGAIN))
  1129. break;
  1130. if (ret < 0)
  1131. goto error;
  1132. if (debug_ts) {
  1133. av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
  1134. "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
  1135. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &enc->time_base),
  1136. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &enc->time_base));
  1137. }
  1138. if (pkt.pts == AV_NOPTS_VALUE && !(enc->codec->capabilities & AV_CODEC_CAP_DELAY))
  1139. pkt.pts = ost->sync_opts;
  1140. av_packet_rescale_ts(&pkt, enc->time_base, ost->mux_timebase);
  1141. if (debug_ts) {
  1142. av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
  1143. "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
  1144. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->mux_timebase),
  1145. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->mux_timebase));
  1146. }
  1147. frame_size = pkt.size;
  1148. output_packet(of, &pkt, ost);
  1149. /* if two pass, output log */
  1150. if (ost->logfile && enc->stats_out) {
  1151. fprintf(ost->logfile, "%s", enc->stats_out);
  1152. }
  1153. }
  1154. }
  1155. ost->sync_opts++;
  1156. /*
  1157. * For video, number of frames in == number of packets out.
  1158. * But there may be reordering, so we can't throw away frames on encoder
  1159. * flush, we need to limit them here, before they go into encoder.
  1160. */
  1161. ost->frame_number++;
  1162. if (vstats_filename && frame_size)
  1163. do_video_stats(ost, frame_size);
  1164. }
  1165. if (!ost->last_frame)
  1166. ost->last_frame = av_frame_alloc();
  1167. av_frame_unref(ost->last_frame);
  1168. if (next_picture && ost->last_frame)
  1169. av_frame_ref(ost->last_frame, next_picture);
  1170. else
  1171. av_frame_free(&ost->last_frame);
  1172. return;
  1173. error:
  1174. av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
  1175. exit_program(1);
  1176. }
  1177. static double psnr(double d)
  1178. {
  1179. return -10.0 * log10(d);
  1180. }
  1181. static void do_video_stats(OutputStream *ost, int frame_size)
  1182. {
  1183. AVCodecContext *enc;
  1184. int frame_number;
  1185. double ti1, bitrate, avg_bitrate;
  1186. /* this is executed just the first time do_video_stats is called */
  1187. if (!vstats_file) {
  1188. vstats_file = fopen(vstats_filename, "w");
  1189. if (!vstats_file) {
  1190. perror("fopen");
  1191. exit_program(1);
  1192. }
  1193. }
  1194. enc = ost->enc_ctx;
  1195. if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  1196. frame_number = ost->st->nb_frames;
  1197. if (vstats_version <= 1) {
  1198. fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number,
  1199. ost->quality / (float)FF_QP2LAMBDA);
  1200. } else {
  1201. fprintf(vstats_file, "out= %2d st= %2d frame= %5d q= %2.1f ", ost->file_index, ost->index, frame_number,
  1202. ost->quality / (float)FF_QP2LAMBDA);
  1203. }
  1204. if (ost->error[0]>=0 && (enc->flags & AV_CODEC_FLAG_PSNR))
  1205. fprintf(vstats_file, "PSNR= %6.2f ", psnr(ost->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
  1206. fprintf(vstats_file,"f_size= %6d ", frame_size);
  1207. /* compute pts value */
  1208. ti1 = av_stream_get_end_pts(ost->st) * av_q2d(ost->st->time_base);
  1209. if (ti1 < 0.01)
  1210. ti1 = 0.01;
  1211. bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
  1212. avg_bitrate = (double)(ost->data_size * 8) / ti1 / 1000.0;
  1213. fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
  1214. (double)ost->data_size / 1024, ti1, bitrate, avg_bitrate);
  1215. fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(ost->pict_type));
  1216. }
  1217. }
  1218. static int init_output_stream(OutputStream *ost, char *error, int error_len);
  1219. static void finish_output_stream(OutputStream *ost)
  1220. {
  1221. OutputFile *of = output_files[ost->file_index];
  1222. int i;
  1223. ost->finished = ENCODER_FINISHED | MUXER_FINISHED;
  1224. if (of->shortest) {
  1225. for (i = 0; i < of->ctx->nb_streams; i++)
  1226. output_streams[of->ost_index + i]->finished = ENCODER_FINISHED | MUXER_FINISHED;
  1227. }
  1228. }
  1229. /**
  1230. * Get and encode new output from any of the filtergraphs, without causing
  1231. * activity.
  1232. *
  1233. * @return 0 for success, <0 for severe errors
  1234. */
  1235. static int reap_filters(int flush)
  1236. {
  1237. AVFrame *filtered_frame = NULL;
  1238. int i;
  1239. /* Reap all buffers present in the buffer sinks */
  1240. for (i = 0; i < nb_output_streams; i++) {
  1241. OutputStream *ost = output_streams[i];
  1242. OutputFile *of = output_files[ost->file_index];
  1243. AVFilterContext *filter;
  1244. AVCodecContext *enc = ost->enc_ctx;
  1245. int ret = 0;
  1246. if (!ost->filter || !ost->filter->graph->graph)
  1247. continue;
  1248. filter = ost->filter->filter;
  1249. if (!ost->initialized) {
  1250. char error[1024] = "";
  1251. ret = init_output_stream(ost, error, sizeof(error));
  1252. if (ret < 0) {
  1253. av_log(NULL, AV_LOG_ERROR, "Error initializing output stream %d:%d -- %s\n",
  1254. ost->file_index, ost->index, error);
  1255. exit_program(1);
  1256. }
  1257. }
  1258. if (!ost->filtered_frame && !(ost->filtered_frame = av_frame_alloc())) {
  1259. return AVERROR(ENOMEM);
  1260. }
  1261. filtered_frame = ost->filtered_frame;
  1262. while (1) {
  1263. double float_pts = AV_NOPTS_VALUE; // this is identical to filtered_frame.pts but with higher precision
  1264. ret = av_buffersink_get_frame_flags(filter, filtered_frame,
  1265. AV_BUFFERSINK_FLAG_NO_REQUEST);
  1266. if (ret < 0) {
  1267. if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) {
  1268. av_log(NULL, AV_LOG_WARNING,
  1269. "Error in av_buffersink_get_frame_flags(): %s\n", av_err2str(ret));
  1270. } else if (flush && ret == AVERROR_EOF) {
  1271. if (av_buffersink_get_type(filter) == AVMEDIA_TYPE_VIDEO)
  1272. do_video_out(of, ost, NULL, AV_NOPTS_VALUE);
  1273. }
  1274. break;
  1275. }
  1276. if (ost->finished) {
  1277. av_frame_unref(filtered_frame);
  1278. continue;
  1279. }
  1280. if (filtered_frame->pts != AV_NOPTS_VALUE) {
  1281. int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
  1282. AVRational filter_tb = av_buffersink_get_time_base(filter);
  1283. AVRational tb = enc->time_base;
  1284. int extra_bits = av_clip(29 - av_log2(tb.den), 0, 16);
  1285. tb.den <<= extra_bits;
  1286. float_pts =
  1287. av_rescale_q(filtered_frame->pts, filter_tb, tb) -
  1288. av_rescale_q(start_time, AV_TIME_BASE_Q, tb);
  1289. float_pts /= 1 << extra_bits;
  1290. // avoid exact midoints to reduce the chance of rounding differences, this can be removed in case the fps code is changed to work with integers
  1291. float_pts += FFSIGN(float_pts) * 1.0 / (1<<17);
  1292. filtered_frame->pts =
  1293. av_rescale_q(filtered_frame->pts, filter_tb, enc->time_base) -
  1294. av_rescale_q(start_time, AV_TIME_BASE_Q, enc->time_base);
  1295. }
  1296. //if (ost->source_index >= 0)
  1297. // *filtered_frame= *input_streams[ost->source_index]->decoded_frame; //for me_threshold
  1298. switch (av_buffersink_get_type(filter)) {
  1299. case AVMEDIA_TYPE_VIDEO:
  1300. if (!ost->frame_aspect_ratio.num)
  1301. enc->sample_aspect_ratio = filtered_frame->sample_aspect_ratio;
  1302. if (debug_ts) {
  1303. av_log(NULL, AV_LOG_INFO, "filter -> pts:%s pts_time:%s exact:%f time_base:%d/%d\n",
  1304. av_ts2str(filtered_frame->pts), av_ts2timestr(filtered_frame->pts, &enc->time_base),
  1305. float_pts,
  1306. enc->time_base.num, enc->time_base.den);
  1307. }
  1308. do_video_out(of, ost, filtered_frame, float_pts);
  1309. break;
  1310. case AVMEDIA_TYPE_AUDIO:
  1311. if (!(enc->codec->capabilities & AV_CODEC_CAP_PARAM_CHANGE) &&
  1312. enc->channels != av_frame_get_channels(filtered_frame)) {
  1313. av_log(NULL, AV_LOG_ERROR,
  1314. "Audio filter graph output is not normalized and encoder does not support parameter changes\n");
  1315. break;
  1316. }
  1317. do_audio_out(of, ost, filtered_frame);
  1318. break;
  1319. default:
  1320. // TODO support subtitle filters
  1321. av_assert0(0);
  1322. }
  1323. av_frame_unref(filtered_frame);
  1324. }
  1325. }
  1326. return 0;
  1327. }
  1328. static void print_final_stats(int64_t total_size)
  1329. {
  1330. uint64_t video_size = 0, audio_size = 0, extra_size = 0, other_size = 0;
  1331. uint64_t subtitle_size = 0;
  1332. uint64_t data_size = 0;
  1333. float percent = -1.0;
  1334. int i, j;
  1335. int pass1_used = 1;
  1336. for (i = 0; i < nb_output_streams; i++) {
  1337. OutputStream *ost = output_streams[i];
  1338. switch (ost->enc_ctx->codec_type) {
  1339. case AVMEDIA_TYPE_VIDEO: video_size += ost->data_size; break;
  1340. case AVMEDIA_TYPE_AUDIO: audio_size += ost->data_size; break;
  1341. case AVMEDIA_TYPE_SUBTITLE: subtitle_size += ost->data_size; break;
  1342. default: other_size += ost->data_size; break;
  1343. }
  1344. extra_size += ost->enc_ctx->extradata_size;
  1345. data_size += ost->data_size;
  1346. if ( (ost->enc_ctx->flags & (AV_CODEC_FLAG_PASS1 | AV_CODEC_FLAG_PASS2))
  1347. != AV_CODEC_FLAG_PASS1)
  1348. pass1_used = 0;
  1349. }
  1350. if (data_size && total_size>0 && total_size >= data_size)
  1351. percent = 100.0 * (total_size - data_size) / data_size;
  1352. av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB subtitle:%1.0fkB other streams:%1.0fkB global headers:%1.0fkB muxing overhead: ",
  1353. video_size / 1024.0,
  1354. audio_size / 1024.0,
  1355. subtitle_size / 1024.0,
  1356. other_size / 1024.0,
  1357. extra_size / 1024.0);
  1358. if (percent >= 0.0)
  1359. av_log(NULL, AV_LOG_INFO, "%f%%", percent);
  1360. else
  1361. av_log(NULL, AV_LOG_INFO, "unknown");
  1362. av_log(NULL, AV_LOG_INFO, "\n");
  1363. /* print verbose per-stream stats */
  1364. for (i = 0; i < nb_input_files; i++) {
  1365. InputFile *f = input_files[i];
  1366. uint64_t total_packets = 0, total_size = 0;
  1367. av_log(NULL, AV_LOG_VERBOSE, "Input file #%d (%s):\n",
  1368. i, f->ctx->filename);
  1369. for (j = 0; j < f->nb_streams; j++) {
  1370. InputStream *ist = input_streams[f->ist_index + j];
  1371. enum AVMediaType type = ist->dec_ctx->codec_type;
  1372. total_size += ist->data_size;
  1373. total_packets += ist->nb_packets;
  1374. av_log(NULL, AV_LOG_VERBOSE, " Input stream #%d:%d (%s): ",
  1375. i, j, media_type_string(type));
  1376. av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" packets read (%"PRIu64" bytes); ",
  1377. ist->nb_packets, ist->data_size);
  1378. if (ist->decoding_needed) {
  1379. av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" frames decoded",
  1380. ist->frames_decoded);
  1381. if (type == AVMEDIA_TYPE_AUDIO)
  1382. av_log(NULL, AV_LOG_VERBOSE, " (%"PRIu64" samples)", ist->samples_decoded);
  1383. av_log(NULL, AV_LOG_VERBOSE, "; ");
  1384. }
  1385. av_log(NULL, AV_LOG_VERBOSE, "\n");
  1386. }
  1387. av_log(NULL, AV_LOG_VERBOSE, " Total: %"PRIu64" packets (%"PRIu64" bytes) demuxed\n",
  1388. total_packets, total_size);
  1389. }
  1390. for (i = 0; i < nb_output_files; i++) {
  1391. OutputFile *of = output_files[i];
  1392. uint64_t total_packets = 0, total_size = 0;
  1393. av_log(NULL, AV_LOG_VERBOSE, "Output file #%d (%s):\n",
  1394. i, of->ctx->filename);
  1395. for (j = 0; j < of->ctx->nb_streams; j++) {
  1396. OutputStream *ost = output_streams[of->ost_index + j];
  1397. enum AVMediaType type = ost->enc_ctx->codec_type;
  1398. total_size += ost->data_size;
  1399. total_packets += ost->packets_written;
  1400. av_log(NULL, AV_LOG_VERBOSE, " Output stream #%d:%d (%s): ",
  1401. i, j, media_type_string(type));
  1402. if (ost->encoding_needed) {
  1403. av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" frames encoded",
  1404. ost->frames_encoded);
  1405. if (type == AVMEDIA_TYPE_AUDIO)
  1406. av_log(NULL, AV_LOG_VERBOSE, " (%"PRIu64" samples)", ost->samples_encoded);
  1407. av_log(NULL, AV_LOG_VERBOSE, "; ");
  1408. }
  1409. av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" packets muxed (%"PRIu64" bytes); ",
  1410. ost->packets_written, ost->data_size);
  1411. av_log(NULL, AV_LOG_VERBOSE, "\n");
  1412. }
  1413. av_log(NULL, AV_LOG_VERBOSE, " Total: %"PRIu64" packets (%"PRIu64" bytes) muxed\n",
  1414. total_packets, total_size);
  1415. }
  1416. if(video_size + data_size + audio_size + subtitle_size + extra_size == 0){
  1417. av_log(NULL, AV_LOG_WARNING, "Output file is empty, nothing was encoded ");
  1418. if (pass1_used) {
  1419. av_log(NULL, AV_LOG_WARNING, "\n");
  1420. } else {
  1421. av_log(NULL, AV_LOG_WARNING, "(check -ss / -t / -frames parameters if used)\n");
  1422. }
  1423. }
  1424. }
  1425. static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
  1426. {
  1427. char buf[1024];
  1428. AVBPrint buf_script;
  1429. OutputStream *ost;
  1430. AVFormatContext *oc;
  1431. int64_t total_size;
  1432. AVCodecContext *enc;
  1433. int frame_number, vid, i;
  1434. double bitrate;
  1435. double speed;
  1436. int64_t pts = INT64_MIN + 1;
  1437. static int64_t last_time = -1;
  1438. static int qp_histogram[52];
  1439. int hours, mins, secs, us;
  1440. int ret;
  1441. float t;
  1442. if (!print_stats && !is_last_report && !progress_avio)
  1443. return;
  1444. if (!is_last_report) {
  1445. if (last_time == -1) {
  1446. last_time = cur_time;
  1447. return;
  1448. }
  1449. if ((cur_time - last_time) < 500000)
  1450. return;
  1451. last_time = cur_time;
  1452. }
  1453. t = (cur_time-timer_start) / 1000000.0;
  1454. oc = output_files[0]->ctx;
  1455. total_size = avio_size(oc->pb);
  1456. if (total_size <= 0) // FIXME improve avio_size() so it works with non seekable output too
  1457. total_size = avio_tell(oc->pb);
  1458. buf[0] = '\0';
  1459. vid = 0;
  1460. av_bprint_init(&buf_script, 0, 1);
  1461. for (i = 0; i < nb_output_streams; i++) {
  1462. float q = -1;
  1463. ost = output_streams[i];
  1464. enc = ost->enc_ctx;
  1465. if (!ost->stream_copy)
  1466. q = ost->quality / (float) FF_QP2LAMBDA;
  1467. if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  1468. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
  1469. av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
  1470. ost->file_index, ost->index, q);
  1471. }
  1472. if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  1473. float fps;
  1474. frame_number = ost->frame_number;
  1475. fps = t > 1 ? frame_number / t : 0;
  1476. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3.*f q=%3.1f ",
  1477. frame_number, fps < 9.95, fps, q);
  1478. av_bprintf(&buf_script, "frame=%d\n", frame_number);
  1479. av_bprintf(&buf_script, "fps=%.1f\n", fps);
  1480. av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
  1481. ost->file_index, ost->index, q);
  1482. if (is_last_report)
  1483. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
  1484. if (qp_hist) {
  1485. int j;
  1486. int qp = lrintf(q);
  1487. if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
  1488. qp_histogram[qp]++;
  1489. for (j = 0; j < 32; j++)
  1490. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", av_log2(qp_histogram[j] + 1));
  1491. }
  1492. if ((enc->flags & AV_CODEC_FLAG_PSNR) && (ost->pict_type != AV_PICTURE_TYPE_NONE || is_last_report)) {
  1493. int j;
  1494. double error, error_sum = 0;
  1495. double scale, scale_sum = 0;
  1496. double p;
  1497. char type[3] = { 'Y','U','V' };
  1498. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
  1499. for (j = 0; j < 3; j++) {
  1500. if (is_last_report) {
  1501. error = enc->error[j];
  1502. scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
  1503. } else {
  1504. error = ost->error[j];
  1505. scale = enc->width * enc->height * 255.0 * 255.0;
  1506. }
  1507. if (j)
  1508. scale /= 4;
  1509. error_sum += error;
  1510. scale_sum += scale;
  1511. p = psnr(error / scale);
  1512. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], p);
  1513. av_bprintf(&buf_script, "stream_%d_%d_psnr_%c=%2.2f\n",
  1514. ost->file_index, ost->index, type[j] | 32, p);
  1515. }
  1516. p = psnr(error_sum / scale_sum);
  1517. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
  1518. av_bprintf(&buf_script, "stream_%d_%d_psnr_all=%2.2f\n",
  1519. ost->file_index, ost->index, p);
  1520. }
  1521. vid = 1;
  1522. }
  1523. /* compute min output value */
  1524. if (av_stream_get_end_pts(ost->st) != AV_NOPTS_VALUE)
  1525. pts = FFMAX(pts, av_rescale_q(av_stream_get_end_pts(ost->st),
  1526. ost->st->time_base, AV_TIME_BASE_Q));
  1527. if (is_last_report)
  1528. nb_frames_drop += ost->last_dropped;
  1529. }
  1530. secs = FFABS(pts) / AV_TIME_BASE;
  1531. us = FFABS(pts) % AV_TIME_BASE;
  1532. mins = secs / 60;
  1533. secs %= 60;
  1534. hours = mins / 60;
  1535. mins %= 60;
  1536. bitrate = pts && total_size >= 0 ? total_size * 8 / (pts / 1000.0) : -1;
  1537. speed = t != 0.0 ? (double)pts / AV_TIME_BASE / t : -1;
  1538. if (total_size < 0) snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  1539. "size=N/A time=");
  1540. else snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  1541. "size=%8.0fkB time=", total_size / 1024.0);
  1542. if (pts < 0)
  1543. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "-");
  1544. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  1545. "%02d:%02d:%02d.%02d ", hours, mins, secs,
  1546. (100 * us) / AV_TIME_BASE);
  1547. if (bitrate < 0) {
  1548. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),"bitrate=N/A");
  1549. av_bprintf(&buf_script, "bitrate=N/A\n");
  1550. }else{
  1551. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),"bitrate=%6.1fkbits/s", bitrate);
  1552. av_bprintf(&buf_script, "bitrate=%6.1fkbits/s\n", bitrate);
  1553. }
  1554. if (total_size < 0) av_bprintf(&buf_script, "total_size=N/A\n");
  1555. else av_bprintf(&buf_script, "total_size=%"PRId64"\n", total_size);
  1556. av_bprintf(&buf_script, "out_time_ms=%"PRId64"\n", pts);
  1557. av_bprintf(&buf_script, "out_time=%02d:%02d:%02d.%06d\n",
  1558. hours, mins, secs, us);
  1559. if (nb_frames_dup || nb_frames_drop)
  1560. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
  1561. nb_frames_dup, nb_frames_drop);
  1562. av_bprintf(&buf_script, "dup_frames=%d\n", nb_frames_dup);
  1563. av_bprintf(&buf_script, "drop_frames=%d\n", nb_frames_drop);
  1564. if (speed < 0) {
  1565. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf)," speed=N/A");
  1566. av_bprintf(&buf_script, "speed=N/A\n");
  1567. } else {
  1568. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf)," speed=%4.3gx", speed);
  1569. av_bprintf(&buf_script, "speed=%4.3gx\n", speed);
  1570. }
  1571. if (print_stats || is_last_report) {
  1572. const char end = is_last_report ? '\n' : '\r';
  1573. if (print_stats==1 && AV_LOG_INFO > av_log_get_level()) {
  1574. fprintf(stderr, "%s %c", buf, end);
  1575. } else
  1576. av_log(NULL, AV_LOG_INFO, "%s %c", buf, end);
  1577. fflush(stderr);
  1578. }
  1579. if (progress_avio) {
  1580. av_bprintf(&buf_script, "progress=%s\n",
  1581. is_last_report ? "end" : "continue");
  1582. avio_write(progress_avio, buf_script.str,
  1583. FFMIN(buf_script.len, buf_script.size - 1));
  1584. avio_flush(progress_avio);
  1585. av_bprint_finalize(&buf_script, NULL);
  1586. if (is_last_report) {
  1587. if ((ret = avio_closep(&progress_avio)) < 0)
  1588. av_log(NULL, AV_LOG_ERROR,
  1589. "Error closing progress log, loss of information possible: %s\n", av_err2str(ret));
  1590. }
  1591. }
  1592. if (is_last_report)
  1593. print_final_stats(total_size);
  1594. }
  1595. static void flush_encoders(void)
  1596. {
  1597. int i, ret;
  1598. for (i = 0; i < nb_output_streams; i++) {
  1599. OutputStream *ost = output_streams[i];
  1600. AVCodecContext *enc = ost->enc_ctx;
  1601. OutputFile *of = output_files[ost->file_index];
  1602. if (!ost->encoding_needed)
  1603. continue;
  1604. // Try to enable encoding with no input frames.
  1605. // Maybe we should just let encoding fail instead.
  1606. if (!ost->initialized) {
  1607. FilterGraph *fg = ost->filter->graph;
  1608. char error[1024] = "";
  1609. av_log(NULL, AV_LOG_WARNING,
  1610. "Finishing stream %d:%d without any data written to it.\n",
  1611. ost->file_index, ost->st->index);
  1612. if (ost->filter && !fg->graph) {
  1613. int x;
  1614. for (x = 0; x < fg->nb_inputs; x++) {
  1615. InputFilter *ifilter = fg->inputs[x];
  1616. if (ifilter->format < 0) {
  1617. AVCodecParameters *par = ifilter->ist->st->codecpar;
  1618. // We never got any input. Set a fake format, which will
  1619. // come from libavformat.
  1620. ifilter->format = par->format;
  1621. ifilter->sample_rate = par->sample_rate;
  1622. ifilter->channels = par->channels;
  1623. ifilter->channel_layout = par->channel_layout;
  1624. ifilter->width = par->width;
  1625. ifilter->height = par->height;
  1626. ifilter->sample_aspect_ratio = par->sample_aspect_ratio;
  1627. }
  1628. }
  1629. if (!ifilter_has_all_input_formats(fg))
  1630. continue;
  1631. ret = configure_filtergraph(fg);
  1632. if (ret < 0) {
  1633. av_log(NULL, AV_LOG_ERROR, "Error configuring filter graph\n");
  1634. exit_program(1);
  1635. }
  1636. finish_output_stream(ost);
  1637. }
  1638. ret = init_output_stream(ost, error, sizeof(error));
  1639. if (ret < 0) {
  1640. av_log(NULL, AV_LOG_ERROR, "Error initializing output stream %d:%d -- %s\n",
  1641. ost->file_index, ost->index, error);
  1642. exit_program(1);
  1643. }
  1644. }
  1645. if (enc->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
  1646. continue;
  1647. #if FF_API_LAVF_FMT_RAWPICTURE
  1648. if (enc->codec_type == AVMEDIA_TYPE_VIDEO && (of->ctx->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == AV_CODEC_ID_RAWVIDEO)
  1649. continue;
  1650. #endif
  1651. if (enc->codec_type != AVMEDIA_TYPE_VIDEO && enc->codec_type != AVMEDIA_TYPE_AUDIO)
  1652. continue;
  1653. for (;;) {
  1654. const char *desc = NULL;
  1655. AVPacket pkt;
  1656. int pkt_size;
  1657. switch (enc->codec_type) {
  1658. case AVMEDIA_TYPE_AUDIO:
  1659. desc = "audio";
  1660. break;
  1661. case AVMEDIA_TYPE_VIDEO:
  1662. desc = "video";
  1663. break;
  1664. default:
  1665. av_assert0(0);
  1666. }
  1667. av_init_packet(&pkt);
  1668. pkt.data = NULL;
  1669. pkt.size = 0;
  1670. update_benchmark(NULL);
  1671. while ((ret = avcodec_receive_packet(enc, &pkt)) == AVERROR(EAGAIN)) {
  1672. ret = avcodec_send_frame(enc, NULL);
  1673. if (ret < 0) {
  1674. av_log(NULL, AV_LOG_FATAL, "%s encoding failed: %s\n",
  1675. desc,
  1676. av_err2str(ret));
  1677. exit_program(1);
  1678. }
  1679. }
  1680. update_benchmark("flush_%s %d.%d", desc, ost->file_index, ost->index);
  1681. if (ret < 0 && ret != AVERROR_EOF) {
  1682. av_log(NULL, AV_LOG_FATAL, "%s encoding failed: %s\n",
  1683. desc,
  1684. av_err2str(ret));
  1685. exit_program(1);
  1686. }
  1687. if (ost->logfile && enc->stats_out) {
  1688. fprintf(ost->logfile, "%s", enc->stats_out);
  1689. }
  1690. if (ret == AVERROR_EOF) {
  1691. break;
  1692. }
  1693. if (ost->finished & MUXER_FINISHED) {
  1694. av_packet_unref(&pkt);
  1695. continue;
  1696. }
  1697. av_packet_rescale_ts(&pkt, enc->time_base, ost->mux_timebase);
  1698. pkt_size = pkt.size;
  1699. output_packet(of, &pkt, ost);
  1700. if (ost->enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO && vstats_filename) {
  1701. do_video_stats(ost, pkt_size);
  1702. }
  1703. }
  1704. }
  1705. }
  1706. /*
  1707. * Check whether a packet from ist should be written into ost at this time
  1708. */
  1709. static int check_output_constraints(InputStream *ist, OutputStream *ost)
  1710. {
  1711. OutputFile *of = output_files[ost->file_index];
  1712. int ist_index = input_files[ist->file_index]->ist_index + ist->st->index;
  1713. if (ost->source_index != ist_index)
  1714. return 0;
  1715. if (ost->finished)
  1716. return 0;
  1717. if (of->start_time != AV_NOPTS_VALUE && ist->pts < of->start_time)
  1718. return 0;
  1719. return 1;
  1720. }
  1721. static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
  1722. {
  1723. OutputFile *of = output_files[ost->file_index];
  1724. InputFile *f = input_files [ist->file_index];
  1725. int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
  1726. int64_t ost_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q, ost->mux_timebase);
  1727. AVPicture pict;
  1728. AVPacket opkt;
  1729. av_init_packet(&opkt);
  1730. if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
  1731. !ost->copy_initial_nonkeyframes)
  1732. return;
  1733. if (!ost->frame_number && !ost->copy_prior_start) {
  1734. int64_t comp_start = start_time;
  1735. if (copy_ts && f->start_time != AV_NOPTS_VALUE)
  1736. comp_start = FFMAX(start_time, f->start_time + f->ts_offset);
  1737. if (pkt->pts == AV_NOPTS_VALUE ?
  1738. ist->pts < comp_start :
  1739. pkt->pts < av_rescale_q(comp_start, AV_TIME_BASE_Q, ist->st->time_base))
  1740. return;
  1741. }
  1742. if (of->recording_time != INT64_MAX &&
  1743. ist->pts >= of->recording_time + start_time) {
  1744. close_output_stream(ost);
  1745. return;
  1746. }
  1747. if (f->recording_time != INT64_MAX) {
  1748. start_time = f->ctx->start_time;
  1749. if (f->start_time != AV_NOPTS_VALUE && copy_ts)
  1750. start_time += f->start_time;
  1751. if (ist->pts >= f->recording_time + start_time) {
  1752. close_output_stream(ost);
  1753. return;
  1754. }
  1755. }
  1756. /* force the input stream PTS */
  1757. if (ost->enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO)
  1758. ost->sync_opts++;
  1759. if (pkt->pts != AV_NOPTS_VALUE)
  1760. opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->mux_timebase) - ost_tb_start_time;
  1761. else
  1762. opkt.pts = AV_NOPTS_VALUE;
  1763. if (pkt->dts == AV_NOPTS_VALUE)
  1764. opkt.dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ost->mux_timebase);
  1765. else
  1766. opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->mux_timebase);
  1767. opkt.dts -= ost_tb_start_time;
  1768. if (ost->st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && pkt->dts != AV_NOPTS_VALUE) {
  1769. int duration = av_get_audio_frame_duration(ist->dec_ctx, pkt->size);
  1770. if(!duration)
  1771. duration = ist->dec_ctx->frame_size;
  1772. opkt.dts = opkt.pts = av_rescale_delta(ist->st->time_base, pkt->dts,
  1773. (AVRational){1, ist->dec_ctx->sample_rate}, duration, &ist->filter_in_rescale_delta_last,
  1774. ost->mux_timebase) - ost_tb_start_time;
  1775. }
  1776. opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->mux_timebase);
  1777. opkt.flags = pkt->flags;
  1778. // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
  1779. if ( ost->st->codecpar->codec_id != AV_CODEC_ID_H264
  1780. && ost->st->codecpar->codec_id != AV_CODEC_ID_MPEG1VIDEO
  1781. && ost->st->codecpar->codec_id != AV_CODEC_ID_MPEG2VIDEO
  1782. && ost->st->codecpar->codec_id != AV_CODEC_ID_VC1
  1783. ) {
  1784. int ret = av_parser_change(ost->parser, ost->parser_avctx,
  1785. &opkt.data, &opkt.size,
  1786. pkt->data, pkt->size,
  1787. pkt->flags & AV_PKT_FLAG_KEY);
  1788. if (ret < 0) {
  1789. av_log(NULL, AV_LOG_FATAL, "av_parser_change failed: %s\n",
  1790. av_err2str(ret));
  1791. exit_program(1);
  1792. }
  1793. if (ret) {
  1794. opkt.buf = av_buffer_create(opkt.data, opkt.size, av_buffer_default_free, NULL, 0);
  1795. if (!opkt.buf)
  1796. exit_program(1);
  1797. }
  1798. } else {
  1799. opkt.data = pkt->data;
  1800. opkt.size = pkt->size;
  1801. }
  1802. av_copy_packet_side_data(&opkt, pkt);
  1803. #if FF_API_LAVF_FMT_RAWPICTURE
  1804. if (ost->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
  1805. ost->st->codecpar->codec_id == AV_CODEC_ID_RAWVIDEO &&
  1806. (of->ctx->oformat->flags & AVFMT_RAWPICTURE)) {
  1807. /* store AVPicture in AVPacket, as expected by the output format */
  1808. int ret = avpicture_fill(&pict, opkt.data, ost->st->codecpar->format, ost->st->codecpar->width, ost->st->codecpar->height);
  1809. if (ret < 0) {
  1810. av_log(NULL, AV_LOG_FATAL, "avpicture_fill failed: %s\n",
  1811. av_err2str(ret));
  1812. exit_program(1);
  1813. }
  1814. opkt.data = (uint8_t *)&pict;
  1815. opkt.size = sizeof(AVPicture);
  1816. opkt.flags |= AV_PKT_FLAG_KEY;
  1817. }
  1818. #endif
  1819. output_packet(of, &opkt, ost);
  1820. }
  1821. int guess_input_channel_layout(InputStream *ist)
  1822. {
  1823. AVCodecContext *dec = ist->dec_ctx;
  1824. if (!dec->channel_layout) {
  1825. char layout_name[256];
  1826. if (dec->channels > ist->guess_layout_max)
  1827. return 0;
  1828. dec->channel_layout = av_get_default_channel_layout(dec->channels);
  1829. if (!dec->channel_layout)
  1830. return 0;
  1831. av_get_channel_layout_string(layout_name, sizeof(layout_name),
  1832. dec->channels, dec->channel_layout);
  1833. av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Input Stream "
  1834. "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
  1835. }
  1836. return 1;
  1837. }
  1838. static void check_decode_result(InputStream *ist, int *got_output, int ret)
  1839. {
  1840. if (*got_output || ret<0)
  1841. decode_error_stat[ret<0] ++;
  1842. if (ret < 0 && exit_on_error)
  1843. exit_program(1);
  1844. if (exit_on_error && *got_output && ist) {
  1845. if (av_frame_get_decode_error_flags(ist->decoded_frame) || (ist->decoded_frame->flags & AV_FRAME_FLAG_CORRUPT)) {
  1846. av_log(NULL, AV_LOG_FATAL, "%s: corrupt decoded frame in stream %d\n", input_files[ist->file_index]->ctx->filename, ist->st->index);
  1847. exit_program(1);
  1848. }
  1849. }
  1850. }
  1851. // Filters can be configured only if the formats of all inputs are known.
  1852. static int ifilter_has_all_input_formats(FilterGraph *fg)
  1853. {
  1854. int i;
  1855. for (i = 0; i < fg->nb_inputs; i++) {
  1856. if (fg->inputs[i]->format < 0 && (fg->inputs[i]->type == AVMEDIA_TYPE_AUDIO ||
  1857. fg->inputs[i]->type == AVMEDIA_TYPE_VIDEO))
  1858. return 0;
  1859. }
  1860. return 1;
  1861. }
  1862. static int ifilter_send_frame(InputFilter *ifilter, AVFrame *frame)
  1863. {
  1864. FilterGraph *fg = ifilter->graph;
  1865. int need_reinit, ret, i;
  1866. /* determine if the parameters for this input changed */
  1867. need_reinit = ifilter->format != frame->format;
  1868. switch (ifilter->ist->st->codecpar->codec_type) {
  1869. case AVMEDIA_TYPE_AUDIO:
  1870. need_reinit |= ifilter->sample_rate != frame->sample_rate ||
  1871. ifilter->channels != frame->channels ||
  1872. ifilter->channel_layout != frame->channel_layout;
  1873. break;
  1874. case AVMEDIA_TYPE_VIDEO:
  1875. need_reinit |= ifilter->width != frame->width ||
  1876. ifilter->height != frame->height;
  1877. break;
  1878. }
  1879. if (!ifilter->ist->reinit_filters && fg->graph)
  1880. need_reinit = 0;
  1881. if (!!ifilter->hw_frames_ctx != !!frame->hw_frames_ctx ||
  1882. (ifilter->hw_frames_ctx && ifilter->hw_frames_ctx->data != frame->hw_frames_ctx->data))
  1883. need_reinit = 1;
  1884. if (need_reinit) {
  1885. ret = ifilter_parameters_from_frame(ifilter, frame);
  1886. if (ret < 0)
  1887. return ret;
  1888. }
  1889. /* (re)init the graph if possible, otherwise buffer the frame and return */
  1890. if (need_reinit || !fg->graph) {
  1891. for (i = 0; i < fg->nb_inputs; i++) {
  1892. if (!ifilter_has_all_input_formats(fg)) {
  1893. AVFrame *tmp = av_frame_clone(frame);
  1894. if (!tmp)
  1895. return AVERROR(ENOMEM);
  1896. av_frame_unref(frame);
  1897. if (!av_fifo_space(ifilter->frame_queue)) {
  1898. ret = av_fifo_realloc2(ifilter->frame_queue, 2 * av_fifo_size(ifilter->frame_queue));
  1899. if (ret < 0) {
  1900. av_frame_free(&tmp);
  1901. return ret;
  1902. }
  1903. }
  1904. av_fifo_generic_write(ifilter->frame_queue, &tmp, sizeof(tmp), NULL);
  1905. return 0;
  1906. }
  1907. }
  1908. ret = reap_filters(1);
  1909. if (ret < 0 && ret != AVERROR_EOF) {
  1910. char errbuf[128];
  1911. av_strerror(ret, errbuf, sizeof(errbuf));
  1912. av_log(NULL, AV_LOG_ERROR, "Error while filtering: %s\n", errbuf);
  1913. return ret;
  1914. }
  1915. ret = configure_filtergraph(fg);
  1916. if (ret < 0) {
  1917. av_log(NULL, AV_LOG_ERROR, "Error reinitializing filters!\n");
  1918. return ret;
  1919. }
  1920. }
  1921. ret = av_buffersrc_add_frame_flags(ifilter->filter, frame, AV_BUFFERSRC_FLAG_PUSH);
  1922. if (ret < 0) {
  1923. av_log(NULL, AV_LOG_ERROR, "Error while filtering\n");
  1924. return ret;
  1925. }
  1926. return 0;
  1927. }
  1928. static int ifilter_send_eof(InputFilter *ifilter)
  1929. {
  1930. int i, j, ret;
  1931. ifilter->eof = 1;
  1932. if (ifilter->filter) {
  1933. ret = av_buffersrc_add_frame_flags(ifilter->filter, NULL, AV_BUFFERSRC_FLAG_PUSH);
  1934. if (ret < 0)
  1935. return ret;
  1936. } else {
  1937. // the filtergraph was never configured
  1938. FilterGraph *fg = ifilter->graph;
  1939. for (i = 0; i < fg->nb_inputs; i++)
  1940. if (!fg->inputs[i]->eof)
  1941. break;
  1942. if (i == fg->nb_inputs) {
  1943. // All the input streams have finished without the filtergraph
  1944. // ever being configured.
  1945. // Mark the output streams as finished.
  1946. for (j = 0; j < fg->nb_outputs; j++)
  1947. finish_output_stream(fg->outputs[j]->ost);
  1948. }
  1949. }
  1950. return 0;
  1951. }
  1952. // This does not quite work like avcodec_decode_audio4/avcodec_decode_video2.
  1953. // There is the following difference: if you got a frame, you must call
  1954. // it again with pkt=NULL. pkt==NULL is treated differently from pkt.size==0
  1955. // (pkt==NULL means get more output, pkt.size==0 is a flush/drain packet)
  1956. static int decode(AVCodecContext *avctx, AVFrame *frame, int *got_frame, AVPacket *pkt)
  1957. {
  1958. int ret;
  1959. *got_frame = 0;
  1960. if (pkt) {
  1961. ret = avcodec_send_packet(avctx, pkt);
  1962. // In particular, we don't expect AVERROR(EAGAIN), because we read all
  1963. // decoded frames with avcodec_receive_frame() until done.
  1964. if (ret < 0 && ret != AVERROR_EOF)
  1965. return ret;
  1966. }
  1967. ret = avcodec_receive_frame(avctx, frame);
  1968. if (ret < 0 && ret != AVERROR(EAGAIN))
  1969. return ret;
  1970. if (ret >= 0)
  1971. *got_frame = 1;
  1972. return 0;
  1973. }
  1974. static int send_frame_to_filters(InputStream *ist, AVFrame *decoded_frame)
  1975. {
  1976. int i, ret;
  1977. AVFrame *f;
  1978. av_assert1(ist->nb_filters > 0); /* ensure ret is initialized */
  1979. for (i = 0; i < ist->nb_filters; i++) {
  1980. if (i < ist->nb_filters - 1) {
  1981. f = ist->filter_frame;
  1982. ret = av_frame_ref(f, decoded_frame);
  1983. if (ret < 0)
  1984. break;
  1985. } else
  1986. f = decoded_frame;
  1987. ret = ifilter_send_frame(ist->filters[i], f);
  1988. if (ret == AVERROR_EOF)
  1989. ret = 0; /* ignore */
  1990. if (ret < 0) {
  1991. av_log(NULL, AV_LOG_ERROR,
  1992. "Failed to inject frame into filter network: %s\n", av_err2str(ret));
  1993. break;
  1994. }
  1995. }
  1996. return ret;
  1997. }
  1998. static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output,
  1999. int *decode_failed)
  2000. {
  2001. AVFrame *decoded_frame;
  2002. AVCodecContext *avctx = ist->dec_ctx;
  2003. int ret, err = 0;
  2004. AVRational decoded_frame_tb;
  2005. if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
  2006. return AVERROR(ENOMEM);
  2007. if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
  2008. return AVERROR(ENOMEM);
  2009. decoded_frame = ist->decoded_frame;
  2010. update_benchmark(NULL);
  2011. ret = decode(avctx, decoded_frame, got_output, pkt);
  2012. update_benchmark("decode_audio %d.%d", ist->file_index, ist->st->index);
  2013. if (ret < 0)
  2014. *decode_failed = 1;
  2015. if (ret >= 0 && avctx->sample_rate <= 0) {
  2016. av_log(avctx, AV_LOG_ERROR, "Sample rate %d invalid\n", avctx->sample_rate);
  2017. ret = AVERROR_INVALIDDATA;
  2018. }
  2019. if (ret != AVERROR_EOF)
  2020. check_decode_result(ist, got_output, ret);
  2021. if (!*got_output || ret < 0)
  2022. return ret;
  2023. ist->samples_decoded += decoded_frame->nb_samples;
  2024. ist->frames_decoded++;
  2025. #if 1
  2026. /* increment next_dts to use for the case where the input stream does not
  2027. have timestamps or there are multiple frames in the packet */
  2028. ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
  2029. avctx->sample_rate;
  2030. ist->next_dts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
  2031. avctx->sample_rate;
  2032. #endif
  2033. if (decoded_frame->pts != AV_NOPTS_VALUE) {
  2034. decoded_frame_tb = ist->st->time_base;
  2035. } else if (pkt && pkt->pts != AV_NOPTS_VALUE) {
  2036. decoded_frame->pts = pkt->pts;
  2037. decoded_frame_tb = ist->st->time_base;
  2038. }else {
  2039. decoded_frame->pts = ist->dts;
  2040. decoded_frame_tb = AV_TIME_BASE_Q;
  2041. }
  2042. if (decoded_frame->pts != AV_NOPTS_VALUE)
  2043. decoded_frame->pts = av_rescale_delta(decoded_frame_tb, decoded_frame->pts,
  2044. (AVRational){1, avctx->sample_rate}, decoded_frame->nb_samples, &ist->filter_in_rescale_delta_last,
  2045. (AVRational){1, avctx->sample_rate});
  2046. ist->nb_samples = decoded_frame->nb_samples;
  2047. err = send_frame_to_filters(ist, decoded_frame);
  2048. av_frame_unref(ist->filter_frame);
  2049. av_frame_unref(decoded_frame);
  2050. return err < 0 ? err : ret;
  2051. }
  2052. static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output, int eof,
  2053. int *decode_failed)
  2054. {
  2055. AVFrame *decoded_frame;
  2056. int i, ret = 0, err = 0;
  2057. int64_t best_effort_timestamp;
  2058. int64_t dts = AV_NOPTS_VALUE;
  2059. AVPacket avpkt;
  2060. // With fate-indeo3-2, we're getting 0-sized packets before EOF for some
  2061. // reason. This seems like a semi-critical bug. Don't trigger EOF, and
  2062. // skip the packet.
  2063. if (!eof && pkt && pkt->size == 0)
  2064. return 0;
  2065. if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
  2066. return AVERROR(ENOMEM);
  2067. if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
  2068. return AVERROR(ENOMEM);
  2069. decoded_frame = ist->decoded_frame;
  2070. if (ist->dts != AV_NOPTS_VALUE)
  2071. dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ist->st->time_base);
  2072. if (pkt) {
  2073. avpkt = *pkt;
  2074. avpkt.dts = dts; // ffmpeg.c probably shouldn't do this
  2075. }
  2076. // The old code used to set dts on the drain packet, which does not work
  2077. // with the new API anymore.
  2078. if (eof) {
  2079. void *new = av_realloc_array(ist->dts_buffer, ist->nb_dts_buffer + 1, sizeof(ist->dts_buffer[0]));
  2080. if (!new)
  2081. return AVERROR(ENOMEM);
  2082. ist->dts_buffer = new;
  2083. ist->dts_buffer[ist->nb_dts_buffer++] = dts;
  2084. }
  2085. update_benchmark(NULL);
  2086. ret = decode(ist->dec_ctx, decoded_frame, got_output, pkt ? &avpkt : NULL);
  2087. update_benchmark("decode_video %d.%d", ist->file_index, ist->st->index);
  2088. if (ret < 0)
  2089. *decode_failed = 1;
  2090. // The following line may be required in some cases where there is no parser
  2091. // or the parser does not has_b_frames correctly
  2092. if (ist->st->codecpar->video_delay < ist->dec_ctx->has_b_frames) {
  2093. if (ist->dec_ctx->codec_id == AV_CODEC_ID_H264) {
  2094. ist->st->codecpar->video_delay = ist->dec_ctx->has_b_frames;
  2095. } else
  2096. av_log(ist->dec_ctx, AV_LOG_WARNING,
  2097. "video_delay is larger in decoder than demuxer %d > %d.\n"
  2098. "If you want to help, upload a sample "
  2099. "of this file to ftp://upload.ffmpeg.org/incoming/ "
  2100. "and contact the ffmpeg-devel mailing list. (ffmpeg-devel@ffmpeg.org)\n",
  2101. ist->dec_ctx->has_b_frames,
  2102. ist->st->codecpar->video_delay);
  2103. }
  2104. if (ret != AVERROR_EOF)
  2105. check_decode_result(ist, got_output, ret);
  2106. if (*got_output && ret >= 0) {
  2107. if (ist->dec_ctx->width != decoded_frame->width ||
  2108. ist->dec_ctx->height != decoded_frame->height ||
  2109. ist->dec_ctx->pix_fmt != decoded_frame->format) {
  2110. av_log(NULL, AV_LOG_DEBUG, "Frame parameters mismatch context %d,%d,%d != %d,%d,%d\n",
  2111. decoded_frame->width,
  2112. decoded_frame->height,
  2113. decoded_frame->format,
  2114. ist->dec_ctx->width,
  2115. ist->dec_ctx->height,
  2116. ist->dec_ctx->pix_fmt);
  2117. }
  2118. }
  2119. if (!*got_output || ret < 0)
  2120. return ret;
  2121. if(ist->top_field_first>=0)
  2122. decoded_frame->top_field_first = ist->top_field_first;
  2123. ist->frames_decoded++;
  2124. if (ist->hwaccel_retrieve_data && decoded_frame->format == ist->hwaccel_pix_fmt) {
  2125. err = ist->hwaccel_retrieve_data(ist->dec_ctx, decoded_frame);
  2126. if (err < 0)
  2127. goto fail;
  2128. }
  2129. ist->hwaccel_retrieved_pix_fmt = decoded_frame->format;
  2130. best_effort_timestamp= av_frame_get_best_effort_timestamp(decoded_frame);
  2131. if (ist->framerate.num)
  2132. best_effort_timestamp = ist->cfr_next_pts++;
  2133. if (eof && best_effort_timestamp == AV_NOPTS_VALUE && ist->nb_dts_buffer > 0) {
  2134. best_effort_timestamp = ist->dts_buffer[0];
  2135. for (i = 0; i < ist->nb_dts_buffer - 1; i++)
  2136. ist->dts_buffer[i] = ist->dts_buffer[i + 1];
  2137. ist->nb_dts_buffer--;
  2138. }
  2139. if(best_effort_timestamp != AV_NOPTS_VALUE) {
  2140. int64_t ts = av_rescale_q(decoded_frame->pts = best_effort_timestamp, ist->st->time_base, AV_TIME_BASE_Q);
  2141. if (ts != AV_NOPTS_VALUE)
  2142. ist->next_pts = ist->pts = ts;
  2143. }
  2144. if (debug_ts) {
  2145. av_log(NULL, AV_LOG_INFO, "decoder -> ist_index:%d type:video "
  2146. "frame_pts:%s frame_pts_time:%s best_effort_ts:%"PRId64" best_effort_ts_time:%s keyframe:%d frame_type:%d time_base:%d/%d\n",
  2147. ist->st->index, av_ts2str(decoded_frame->pts),
  2148. av_ts2timestr(decoded_frame->pts, &ist->st->time_base),
  2149. best_effort_timestamp,
  2150. av_ts2timestr(best_effort_timestamp, &ist->st->time_base),
  2151. decoded_frame->key_frame, decoded_frame->pict_type,
  2152. ist->st->time_base.num, ist->st->time_base.den);
  2153. }
  2154. if (ist->st->sample_aspect_ratio.num)
  2155. decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
  2156. err = send_frame_to_filters(ist, decoded_frame);
  2157. fail:
  2158. av_frame_unref(ist->filter_frame);
  2159. av_frame_unref(decoded_frame);
  2160. return err < 0 ? err : ret;
  2161. }
  2162. static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output,
  2163. int *decode_failed)
  2164. {
  2165. AVSubtitle subtitle;
  2166. int free_sub = 1;
  2167. int i, ret = avcodec_decode_subtitle2(ist->dec_ctx,
  2168. &subtitle, got_output, pkt);
  2169. check_decode_result(NULL, got_output, ret);
  2170. if (ret < 0 || !*got_output) {
  2171. *decode_failed = 1;
  2172. if (!pkt->size)
  2173. sub2video_flush(ist);
  2174. return ret;
  2175. }
  2176. if (ist->fix_sub_duration) {
  2177. int end = 1;
  2178. if (ist->prev_sub.got_output) {
  2179. end = av_rescale(subtitle.pts - ist->prev_sub.subtitle.pts,
  2180. 1000, AV_TIME_BASE);
  2181. if (end < ist->prev_sub.subtitle.end_display_time) {
  2182. av_log(ist->dec_ctx, AV_LOG_DEBUG,
  2183. "Subtitle duration reduced from %"PRId32" to %d%s\n",
  2184. ist->prev_sub.subtitle.end_display_time, end,
  2185. end <= 0 ? ", dropping it" : "");
  2186. ist->prev_sub.subtitle.end_display_time = end;
  2187. }
  2188. }
  2189. FFSWAP(int, *got_output, ist->prev_sub.got_output);
  2190. FFSWAP(int, ret, ist->prev_sub.ret);
  2191. FFSWAP(AVSubtitle, subtitle, ist->prev_sub.subtitle);
  2192. if (end <= 0)
  2193. goto out;
  2194. }
  2195. if (!*got_output)
  2196. return ret;
  2197. if (ist->sub2video.frame) {
  2198. sub2video_update(ist, &subtitle);
  2199. } else if (ist->nb_filters) {
  2200. if (!ist->sub2video.sub_queue)
  2201. ist->sub2video.sub_queue = av_fifo_alloc(8 * sizeof(AVSubtitle));
  2202. if (!ist->sub2video.sub_queue)
  2203. exit_program(1);
  2204. if (!av_fifo_space(ist->sub2video.sub_queue)) {
  2205. ret = av_fifo_realloc2(ist->sub2video.sub_queue, 2 * av_fifo_size(ist->sub2video.sub_queue));
  2206. if (ret < 0)
  2207. exit_program(1);
  2208. }
  2209. av_fifo_generic_write(ist->sub2video.sub_queue, &subtitle, sizeof(subtitle), NULL);
  2210. free_sub = 0;
  2211. }
  2212. if (!subtitle.num_rects)
  2213. goto out;
  2214. ist->frames_decoded++;
  2215. for (i = 0; i < nb_output_streams; i++) {
  2216. OutputStream *ost = output_streams[i];
  2217. if (!check_output_constraints(ist, ost) || !ost->encoding_needed
  2218. || ost->enc->type != AVMEDIA_TYPE_SUBTITLE)
  2219. continue;
  2220. do_subtitle_out(output_files[ost->file_index], ost, &subtitle);
  2221. }
  2222. out:
  2223. if (free_sub)
  2224. avsubtitle_free(&subtitle);
  2225. return ret;
  2226. }
  2227. static int send_filter_eof(InputStream *ist)
  2228. {
  2229. int i, ret;
  2230. for (i = 0; i < ist->nb_filters; i++) {
  2231. ret = ifilter_send_eof(ist->filters[i]);
  2232. if (ret < 0)
  2233. return ret;
  2234. }
  2235. return 0;
  2236. }
  2237. /* pkt = NULL means EOF (needed to flush decoder buffers) */
  2238. static int process_input_packet(InputStream *ist, const AVPacket *pkt, int no_eof)
  2239. {
  2240. int ret = 0, i;
  2241. int repeating = 0;
  2242. int eof_reached = 0;
  2243. AVPacket avpkt;
  2244. if (!ist->saw_first_ts) {
  2245. ist->dts = ist->st->avg_frame_rate.num ? - ist->dec_ctx->has_b_frames * AV_TIME_BASE / av_q2d(ist->st->avg_frame_rate) : 0;
  2246. ist->pts = 0;
  2247. if (pkt && pkt->pts != AV_NOPTS_VALUE && !ist->decoding_needed) {
  2248. ist->dts += av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
  2249. ist->pts = ist->dts; //unused but better to set it to a value thats not totally wrong
  2250. }
  2251. ist->saw_first_ts = 1;
  2252. }
  2253. if (ist->next_dts == AV_NOPTS_VALUE)
  2254. ist->next_dts = ist->dts;
  2255. if (ist->next_pts == AV_NOPTS_VALUE)
  2256. ist->next_pts = ist->pts;
  2257. if (!pkt) {
  2258. /* EOF handling */
  2259. av_init_packet(&avpkt);
  2260. avpkt.data = NULL;
  2261. avpkt.size = 0;
  2262. } else {
  2263. avpkt = *pkt;
  2264. }
  2265. if (pkt && pkt->dts != AV_NOPTS_VALUE) {
  2266. ist->next_dts = ist->dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
  2267. if (ist->dec_ctx->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)
  2268. ist->next_pts = ist->pts = ist->dts;
  2269. }
  2270. // while we have more to decode or while the decoder did output something on EOF
  2271. while (ist->decoding_needed) {
  2272. int duration = 0;
  2273. int got_output = 0;
  2274. int decode_failed = 0;
  2275. ist->pts = ist->next_pts;
  2276. ist->dts = ist->next_dts;
  2277. switch (ist->dec_ctx->codec_type) {
  2278. case AVMEDIA_TYPE_AUDIO:
  2279. ret = decode_audio (ist, repeating ? NULL : &avpkt, &got_output,
  2280. &decode_failed);
  2281. break;
  2282. case AVMEDIA_TYPE_VIDEO:
  2283. ret = decode_video (ist, repeating ? NULL : &avpkt, &got_output, !pkt,
  2284. &decode_failed);
  2285. if (!repeating || !pkt || got_output) {
  2286. if (pkt && pkt->duration) {
  2287. duration = av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
  2288. } else if(ist->dec_ctx->framerate.num != 0 && ist->dec_ctx->framerate.den != 0) {
  2289. int ticks= av_stream_get_parser(ist->st) ? av_stream_get_parser(ist->st)->repeat_pict+1 : ist->dec_ctx->ticks_per_frame;
  2290. duration = ((int64_t)AV_TIME_BASE *
  2291. ist->dec_ctx->framerate.den * ticks) /
  2292. ist->dec_ctx->framerate.num / ist->dec_ctx->ticks_per_frame;
  2293. }
  2294. if(ist->dts != AV_NOPTS_VALUE && duration) {
  2295. ist->next_dts += duration;
  2296. }else
  2297. ist->next_dts = AV_NOPTS_VALUE;
  2298. }
  2299. if (got_output)
  2300. ist->next_pts += duration; //FIXME the duration is not correct in some cases
  2301. break;
  2302. case AVMEDIA_TYPE_SUBTITLE:
  2303. if (repeating)
  2304. break;
  2305. ret = transcode_subtitles(ist, &avpkt, &got_output, &decode_failed);
  2306. if (!pkt && ret >= 0)
  2307. ret = AVERROR_EOF;
  2308. break;
  2309. default:
  2310. return -1;
  2311. }
  2312. if (ret == AVERROR_EOF) {
  2313. eof_reached = 1;
  2314. break;
  2315. }
  2316. if (ret < 0) {
  2317. if (decode_failed) {
  2318. av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d: %s\n",
  2319. ist->file_index, ist->st->index, av_err2str(ret));
  2320. } else {
  2321. av_log(NULL, AV_LOG_FATAL, "Error while processing the decoded "
  2322. "data for stream #%d:%d\n", ist->file_index, ist->st->index);
  2323. }
  2324. if (!decode_failed || exit_on_error)
  2325. exit_program(1);
  2326. break;
  2327. }
  2328. if (got_output)
  2329. ist->got_output = 1;
  2330. if (!got_output)
  2331. break;
  2332. // During draining, we might get multiple output frames in this loop.
  2333. // ffmpeg.c does not drain the filter chain on configuration changes,
  2334. // which means if we send multiple frames at once to the filters, and
  2335. // one of those frames changes configuration, the buffered frames will
  2336. // be lost. This can upset certain FATE tests.
  2337. // Decode only 1 frame per call on EOF to appease these FATE tests.
  2338. // The ideal solution would be to rewrite decoding to use the new
  2339. // decoding API in a better way.
  2340. if (!pkt)
  2341. break;
  2342. repeating = 1;
  2343. }
  2344. /* after flushing, send an EOF on all the filter inputs attached to the stream */
  2345. /* except when looping we need to flush but not to send an EOF */
  2346. if (!pkt && ist->decoding_needed && eof_reached && !no_eof) {
  2347. int ret = send_filter_eof(ist);
  2348. if (ret < 0) {
  2349. av_log(NULL, AV_LOG_FATAL, "Error marking filters as finished\n");
  2350. exit_program(1);
  2351. }
  2352. }
  2353. /* handle stream copy */
  2354. if (!ist->decoding_needed) {
  2355. ist->dts = ist->next_dts;
  2356. switch (ist->dec_ctx->codec_type) {
  2357. case AVMEDIA_TYPE_AUDIO:
  2358. if (ist->dec_ctx->sample_rate) {
  2359. ist->next_dts += ((int64_t)AV_TIME_BASE * ist->dec_ctx->frame_size) /
  2360. ist->dec_ctx->sample_rate;
  2361. } else {
  2362. ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
  2363. }
  2364. break;
  2365. case AVMEDIA_TYPE_VIDEO:
  2366. if (ist->framerate.num) {
  2367. // TODO: Remove work-around for c99-to-c89 issue 7
  2368. AVRational time_base_q = AV_TIME_BASE_Q;
  2369. int64_t next_dts = av_rescale_q(ist->next_dts, time_base_q, av_inv_q(ist->framerate));
  2370. ist->next_dts = av_rescale_q(next_dts + 1, av_inv_q(ist->framerate), time_base_q);
  2371. } else if (pkt->duration) {
  2372. ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
  2373. } else if(ist->dec_ctx->framerate.num != 0) {
  2374. int ticks= av_stream_get_parser(ist->st) ? av_stream_get_parser(ist->st)->repeat_pict + 1 : ist->dec_ctx->ticks_per_frame;
  2375. ist->next_dts += ((int64_t)AV_TIME_BASE *
  2376. ist->dec_ctx->framerate.den * ticks) /
  2377. ist->dec_ctx->framerate.num / ist->dec_ctx->ticks_per_frame;
  2378. }
  2379. break;
  2380. }
  2381. ist->pts = ist->dts;
  2382. ist->next_pts = ist->next_dts;
  2383. }
  2384. for (i = 0; pkt && i < nb_output_streams; i++) {
  2385. OutputStream *ost = output_streams[i];
  2386. if (!check_output_constraints(ist, ost) || ost->encoding_needed)
  2387. continue;
  2388. do_streamcopy(ist, ost, pkt);
  2389. }
  2390. return !eof_reached;
  2391. }
  2392. static void print_sdp(void)
  2393. {
  2394. char sdp[16384];
  2395. int i;
  2396. int j;
  2397. AVIOContext *sdp_pb;
  2398. AVFormatContext **avc;
  2399. for (i = 0; i < nb_output_files; i++) {
  2400. if (!output_files[i]->header_written)
  2401. return;
  2402. }
  2403. avc = av_malloc_array(nb_output_files, sizeof(*avc));
  2404. if (!avc)
  2405. exit_program(1);
  2406. for (i = 0, j = 0; i < nb_output_files; i++) {
  2407. if (!strcmp(output_files[i]->ctx->oformat->name, "rtp")) {
  2408. avc[j] = output_files[i]->ctx;
  2409. j++;
  2410. }
  2411. }
  2412. if (!j)
  2413. goto fail;
  2414. av_sdp_create(avc, j, sdp, sizeof(sdp));
  2415. if (!sdp_filename) {
  2416. printf("SDP:\n%s\n", sdp);
  2417. fflush(stdout);
  2418. } else {
  2419. if (avio_open2(&sdp_pb, sdp_filename, AVIO_FLAG_WRITE, &int_cb, NULL) < 0) {
  2420. av_log(NULL, AV_LOG_ERROR, "Failed to open sdp file '%s'\n", sdp_filename);
  2421. } else {
  2422. avio_printf(sdp_pb, "SDP:\n%s", sdp);
  2423. avio_closep(&sdp_pb);
  2424. av_freep(&sdp_filename);
  2425. }
  2426. }
  2427. fail:
  2428. av_freep(&avc);
  2429. }
  2430. static const HWAccel *get_hwaccel(enum AVPixelFormat pix_fmt)
  2431. {
  2432. int i;
  2433. for (i = 0; hwaccels[i].name; i++)
  2434. if (hwaccels[i].pix_fmt == pix_fmt)
  2435. return &hwaccels[i];
  2436. return NULL;
  2437. }
  2438. static enum AVPixelFormat get_format(AVCodecContext *s, const enum AVPixelFormat *pix_fmts)
  2439. {
  2440. InputStream *ist = s->opaque;
  2441. const enum AVPixelFormat *p;
  2442. int ret;
  2443. for (p = pix_fmts; *p != -1; p++) {
  2444. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(*p);
  2445. const HWAccel *hwaccel;
  2446. if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
  2447. break;
  2448. hwaccel = get_hwaccel(*p);
  2449. if (!hwaccel ||
  2450. (ist->active_hwaccel_id && ist->active_hwaccel_id != hwaccel->id) ||
  2451. (ist->hwaccel_id != HWACCEL_AUTO && ist->hwaccel_id != hwaccel->id))
  2452. continue;
  2453. ret = hwaccel->init(s);
  2454. if (ret < 0) {
  2455. if (ist->hwaccel_id == hwaccel->id) {
  2456. av_log(NULL, AV_LOG_FATAL,
  2457. "%s hwaccel requested for input stream #%d:%d, "
  2458. "but cannot be initialized.\n", hwaccel->name,
  2459. ist->file_index, ist->st->index);
  2460. return AV_PIX_FMT_NONE;
  2461. }
  2462. continue;
  2463. }
  2464. if (ist->hw_frames_ctx) {
  2465. s->hw_frames_ctx = av_buffer_ref(ist->hw_frames_ctx);
  2466. if (!s->hw_frames_ctx)
  2467. return AV_PIX_FMT_NONE;
  2468. }
  2469. ist->active_hwaccel_id = hwaccel->id;
  2470. ist->hwaccel_pix_fmt = *p;
  2471. break;
  2472. }
  2473. return *p;
  2474. }
  2475. static int get_buffer(AVCodecContext *s, AVFrame *frame, int flags)
  2476. {
  2477. InputStream *ist = s->opaque;
  2478. if (ist->hwaccel_get_buffer && frame->format == ist->hwaccel_pix_fmt)
  2479. return ist->hwaccel_get_buffer(s, frame, flags);
  2480. return avcodec_default_get_buffer2(s, frame, flags);
  2481. }
  2482. static int init_input_stream(int ist_index, char *error, int error_len)
  2483. {
  2484. int ret;
  2485. InputStream *ist = input_streams[ist_index];
  2486. if (ist->decoding_needed) {
  2487. AVCodec *codec = ist->dec;
  2488. if (!codec) {
  2489. snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
  2490. avcodec_get_name(ist->dec_ctx->codec_id), ist->file_index, ist->st->index);
  2491. return AVERROR(EINVAL);
  2492. }
  2493. ist->dec_ctx->opaque = ist;
  2494. ist->dec_ctx->get_format = get_format;
  2495. ist->dec_ctx->get_buffer2 = get_buffer;
  2496. ist->dec_ctx->thread_safe_callbacks = 1;
  2497. av_opt_set_int(ist->dec_ctx, "refcounted_frames", 1, 0);
  2498. if (ist->dec_ctx->codec_id == AV_CODEC_ID_DVB_SUBTITLE &&
  2499. (ist->decoding_needed & DECODING_FOR_OST)) {
  2500. av_dict_set(&ist->decoder_opts, "compute_edt", "1", AV_DICT_DONT_OVERWRITE);
  2501. if (ist->decoding_needed & DECODING_FOR_FILTER)
  2502. av_log(NULL, AV_LOG_WARNING, "Warning using DVB subtitles for filtering and output at the same time is not fully supported, also see -compute_edt [0|1]\n");
  2503. }
  2504. av_dict_set(&ist->decoder_opts, "sub_text_format", "ass", AV_DICT_DONT_OVERWRITE);
  2505. /* Useful for subtitles retiming by lavf (FIXME), skipping samples in
  2506. * audio, and video decoders such as cuvid or mediacodec */
  2507. av_codec_set_pkt_timebase(ist->dec_ctx, ist->st->time_base);
  2508. if (!av_dict_get(ist->decoder_opts, "threads", NULL, 0))
  2509. av_dict_set(&ist->decoder_opts, "threads", "auto", 0);
  2510. if ((ret = avcodec_open2(ist->dec_ctx, codec, &ist->decoder_opts)) < 0) {
  2511. if (ret == AVERROR_EXPERIMENTAL)
  2512. abort_codec_experimental(codec, 0);
  2513. snprintf(error, error_len,
  2514. "Error while opening decoder for input stream "
  2515. "#%d:%d : %s",
  2516. ist->file_index, ist->st->index, av_err2str(ret));
  2517. return ret;
  2518. }
  2519. assert_avoptions(ist->decoder_opts);
  2520. }
  2521. ist->next_pts = AV_NOPTS_VALUE;
  2522. ist->next_dts = AV_NOPTS_VALUE;
  2523. return 0;
  2524. }
  2525. static InputStream *get_input_stream(OutputStream *ost)
  2526. {
  2527. if (ost->source_index >= 0)
  2528. return input_streams[ost->source_index];
  2529. return NULL;
  2530. }
  2531. static int compare_int64(const void *a, const void *b)
  2532. {
  2533. return FFDIFFSIGN(*(const int64_t *)a, *(const int64_t *)b);
  2534. }
  2535. /* open the muxer when all the streams are initialized */
  2536. static int check_init_output_file(OutputFile *of, int file_index)
  2537. {
  2538. int ret, i;
  2539. for (i = 0; i < of->ctx->nb_streams; i++) {
  2540. OutputStream *ost = output_streams[of->ost_index + i];
  2541. if (!ost->initialized)
  2542. return 0;
  2543. }
  2544. of->ctx->interrupt_callback = int_cb;
  2545. ret = avformat_write_header(of->ctx, &of->opts);
  2546. if (ret < 0) {
  2547. av_log(NULL, AV_LOG_ERROR,
  2548. "Could not write header for output file #%d "
  2549. "(incorrect codec parameters ?): %s\n",
  2550. file_index, av_err2str(ret));
  2551. return ret;
  2552. }
  2553. //assert_avoptions(of->opts);
  2554. of->header_written = 1;
  2555. av_dump_format(of->ctx, file_index, of->ctx->filename, 1);
  2556. if (sdp_filename || want_sdp)
  2557. print_sdp();
  2558. /* flush the muxing queues */
  2559. for (i = 0; i < of->ctx->nb_streams; i++) {
  2560. OutputStream *ost = output_streams[of->ost_index + i];
  2561. /* try to improve muxing time_base (only possible if nothing has been written yet) */
  2562. if (!av_fifo_size(ost->muxing_queue))
  2563. ost->mux_timebase = ost->st->time_base;
  2564. while (av_fifo_size(ost->muxing_queue)) {
  2565. AVPacket pkt;
  2566. av_fifo_generic_read(ost->muxing_queue, &pkt, sizeof(pkt), NULL);
  2567. write_packet(of, &pkt, ost, 1);
  2568. }
  2569. }
  2570. return 0;
  2571. }
  2572. static int init_output_bsfs(OutputStream *ost)
  2573. {
  2574. AVBSFContext *ctx;
  2575. int i, ret;
  2576. if (!ost->nb_bitstream_filters)
  2577. return 0;
  2578. for (i = 0; i < ost->nb_bitstream_filters; i++) {
  2579. ctx = ost->bsf_ctx[i];
  2580. ret = avcodec_parameters_copy(ctx->par_in,
  2581. i ? ost->bsf_ctx[i - 1]->par_out : ost->st->codecpar);
  2582. if (ret < 0)
  2583. return ret;
  2584. ctx->time_base_in = i ? ost->bsf_ctx[i - 1]->time_base_out : ost->st->time_base;
  2585. ret = av_bsf_init(ctx);
  2586. if (ret < 0) {
  2587. av_log(NULL, AV_LOG_ERROR, "Error initializing bitstream filter: %s\n",
  2588. ost->bsf_ctx[i]->filter->name);
  2589. return ret;
  2590. }
  2591. }
  2592. ctx = ost->bsf_ctx[ost->nb_bitstream_filters - 1];
  2593. ret = avcodec_parameters_copy(ost->st->codecpar, ctx->par_out);
  2594. if (ret < 0)
  2595. return ret;
  2596. ost->st->time_base = ctx->time_base_out;
  2597. return 0;
  2598. }
  2599. static int init_output_stream_streamcopy(OutputStream *ost)
  2600. {
  2601. OutputFile *of = output_files[ost->file_index];
  2602. InputStream *ist = get_input_stream(ost);
  2603. AVCodecParameters *par_dst = ost->st->codecpar;
  2604. AVCodecParameters *par_src = ost->ref_par;
  2605. AVRational sar;
  2606. int i, ret;
  2607. uint32_t codec_tag = par_dst->codec_tag;
  2608. av_assert0(ist && !ost->filter);
  2609. ret = avcodec_parameters_to_context(ost->enc_ctx, ist->st->codecpar);
  2610. if (ret >= 0)
  2611. ret = av_opt_set_dict(ost->enc_ctx, &ost->encoder_opts);
  2612. if (ret < 0) {
  2613. av_log(NULL, AV_LOG_FATAL,
  2614. "Error setting up codec context options.\n");
  2615. return ret;
  2616. }
  2617. avcodec_parameters_from_context(par_src, ost->enc_ctx);
  2618. if (!codec_tag) {
  2619. unsigned int codec_tag_tmp;
  2620. if (!of->ctx->oformat->codec_tag ||
  2621. av_codec_get_id (of->ctx->oformat->codec_tag, par_src->codec_tag) == par_src->codec_id ||
  2622. !av_codec_get_tag2(of->ctx->oformat->codec_tag, par_src->codec_id, &codec_tag_tmp))
  2623. codec_tag = par_src->codec_tag;
  2624. }
  2625. ret = avcodec_parameters_copy(par_dst, par_src);
  2626. if (ret < 0)
  2627. return ret;
  2628. par_dst->codec_tag = codec_tag;
  2629. if (!ost->frame_rate.num)
  2630. ost->frame_rate = ist->framerate;
  2631. ost->st->avg_frame_rate = ost->frame_rate;
  2632. ret = avformat_transfer_internal_stream_timing_info(of->ctx->oformat, ost->st, ist->st, copy_tb);
  2633. if (ret < 0)
  2634. return ret;
  2635. // copy timebase while removing common factors
  2636. if (ost->st->time_base.num <= 0 || ost->st->time_base.den <= 0)
  2637. ost->st->time_base = av_add_q(av_stream_get_codec_timebase(ost->st), (AVRational){0, 1});
  2638. // copy estimated duration as a hint to the muxer
  2639. if (ost->st->duration <= 0 && ist->st->duration > 0)
  2640. ost->st->duration = av_rescale_q(ist->st->duration, ist->st->time_base, ost->st->time_base);
  2641. // copy disposition
  2642. ost->st->disposition = ist->st->disposition;
  2643. if (ist->st->nb_side_data) {
  2644. ost->st->side_data = av_realloc_array(NULL, ist->st->nb_side_data,
  2645. sizeof(*ist->st->side_data));
  2646. if (!ost->st->side_data)
  2647. return AVERROR(ENOMEM);
  2648. ost->st->nb_side_data = 0;
  2649. for (i = 0; i < ist->st->nb_side_data; i++) {
  2650. const AVPacketSideData *sd_src = &ist->st->side_data[i];
  2651. AVPacketSideData *sd_dst = &ost->st->side_data[ost->st->nb_side_data];
  2652. sd_dst->data = av_malloc(sd_src->size);
  2653. if (!sd_dst->data)
  2654. return AVERROR(ENOMEM);
  2655. memcpy(sd_dst->data, sd_src->data, sd_src->size);
  2656. sd_dst->size = sd_src->size;
  2657. sd_dst->type = sd_src->type;
  2658. ost->st->nb_side_data++;
  2659. }
  2660. }
  2661. if (ost->rotate_overridden) {
  2662. uint8_t *sd = av_stream_new_side_data(ost->st, AV_PKT_DATA_DISPLAYMATRIX,
  2663. sizeof(int32_t) * 9);
  2664. if (sd)
  2665. av_display_rotation_set((int32_t *)sd, -ost->rotate_override_value);
  2666. }
  2667. ost->parser = av_parser_init(par_dst->codec_id);
  2668. ost->parser_avctx = avcodec_alloc_context3(NULL);
  2669. if (!ost->parser_avctx)
  2670. return AVERROR(ENOMEM);
  2671. switch (par_dst->codec_type) {
  2672. case AVMEDIA_TYPE_AUDIO:
  2673. if (audio_volume != 256) {
  2674. av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
  2675. exit_program(1);
  2676. }
  2677. if((par_dst->block_align == 1 || par_dst->block_align == 1152 || par_dst->block_align == 576) && par_dst->codec_id == AV_CODEC_ID_MP3)
  2678. par_dst->block_align= 0;
  2679. if(par_dst->codec_id == AV_CODEC_ID_AC3)
  2680. par_dst->block_align= 0;
  2681. break;
  2682. case AVMEDIA_TYPE_VIDEO:
  2683. if (ost->frame_aspect_ratio.num) { // overridden by the -aspect cli option
  2684. sar =
  2685. av_mul_q(ost->frame_aspect_ratio,
  2686. (AVRational){ par_dst->height, par_dst->width });
  2687. av_log(NULL, AV_LOG_WARNING, "Overriding aspect ratio "
  2688. "with stream copy may produce invalid files\n");
  2689. }
  2690. else if (ist->st->sample_aspect_ratio.num)
  2691. sar = ist->st->sample_aspect_ratio;
  2692. else
  2693. sar = par_src->sample_aspect_ratio;
  2694. ost->st->sample_aspect_ratio = par_dst->sample_aspect_ratio = sar;
  2695. ost->st->avg_frame_rate = ist->st->avg_frame_rate;
  2696. ost->st->r_frame_rate = ist->st->r_frame_rate;
  2697. break;
  2698. }
  2699. ost->mux_timebase = ist->st->time_base;
  2700. return 0;
  2701. }
  2702. static void set_encoder_id(OutputFile *of, OutputStream *ost)
  2703. {
  2704. AVDictionaryEntry *e;
  2705. uint8_t *encoder_string;
  2706. int encoder_string_len;
  2707. int format_flags = 0;
  2708. int codec_flags = 0;
  2709. if (av_dict_get(ost->st->metadata, "encoder", NULL, 0))
  2710. return;
  2711. e = av_dict_get(of->opts, "fflags", NULL, 0);
  2712. if (e) {
  2713. const AVOption *o = av_opt_find(of->ctx, "fflags", NULL, 0, 0);
  2714. if (!o)
  2715. return;
  2716. av_opt_eval_flags(of->ctx, o, e->value, &format_flags);
  2717. }
  2718. e = av_dict_get(ost->encoder_opts, "flags", NULL, 0);
  2719. if (e) {
  2720. const AVOption *o = av_opt_find(ost->enc_ctx, "flags", NULL, 0, 0);
  2721. if (!o)
  2722. return;
  2723. av_opt_eval_flags(ost->enc_ctx, o, e->value, &codec_flags);
  2724. }
  2725. encoder_string_len = sizeof(LIBAVCODEC_IDENT) + strlen(ost->enc->name) + 2;
  2726. encoder_string = av_mallocz(encoder_string_len);
  2727. if (!encoder_string)
  2728. exit_program(1);
  2729. if (!(format_flags & AVFMT_FLAG_BITEXACT) && !(codec_flags & AV_CODEC_FLAG_BITEXACT))
  2730. av_strlcpy(encoder_string, LIBAVCODEC_IDENT " ", encoder_string_len);
  2731. else
  2732. av_strlcpy(encoder_string, "Lavc ", encoder_string_len);
  2733. av_strlcat(encoder_string, ost->enc->name, encoder_string_len);
  2734. av_dict_set(&ost->st->metadata, "encoder", encoder_string,
  2735. AV_DICT_DONT_STRDUP_VAL | AV_DICT_DONT_OVERWRITE);
  2736. }
  2737. static void parse_forced_key_frames(char *kf, OutputStream *ost,
  2738. AVCodecContext *avctx)
  2739. {
  2740. char *p;
  2741. int n = 1, i, size, index = 0;
  2742. int64_t t, *pts;
  2743. for (p = kf; *p; p++)
  2744. if (*p == ',')
  2745. n++;
  2746. size = n;
  2747. pts = av_malloc_array(size, sizeof(*pts));
  2748. if (!pts) {
  2749. av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
  2750. exit_program(1);
  2751. }
  2752. p = kf;
  2753. for (i = 0; i < n; i++) {
  2754. char *next = strchr(p, ',');
  2755. if (next)
  2756. *next++ = 0;
  2757. if (!memcmp(p, "chapters", 8)) {
  2758. AVFormatContext *avf = output_files[ost->file_index]->ctx;
  2759. int j;
  2760. if (avf->nb_chapters > INT_MAX - size ||
  2761. !(pts = av_realloc_f(pts, size += avf->nb_chapters - 1,
  2762. sizeof(*pts)))) {
  2763. av_log(NULL, AV_LOG_FATAL,
  2764. "Could not allocate forced key frames array.\n");
  2765. exit_program(1);
  2766. }
  2767. t = p[8] ? parse_time_or_die("force_key_frames", p + 8, 1) : 0;
  2768. t = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
  2769. for (j = 0; j < avf->nb_chapters; j++) {
  2770. AVChapter *c = avf->chapters[j];
  2771. av_assert1(index < size);
  2772. pts[index++] = av_rescale_q(c->start, c->time_base,
  2773. avctx->time_base) + t;
  2774. }
  2775. } else {
  2776. t = parse_time_or_die("force_key_frames", p, 1);
  2777. av_assert1(index < size);
  2778. pts[index++] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
  2779. }
  2780. p = next;
  2781. }
  2782. av_assert0(index == size);
  2783. qsort(pts, size, sizeof(*pts), compare_int64);
  2784. ost->forced_kf_count = size;
  2785. ost->forced_kf_pts = pts;
  2786. }
  2787. static int init_output_stream_encode(OutputStream *ost)
  2788. {
  2789. InputStream *ist = get_input_stream(ost);
  2790. AVCodecContext *enc_ctx = ost->enc_ctx;
  2791. AVCodecContext *dec_ctx = NULL;
  2792. AVFormatContext *oc = output_files[ost->file_index]->ctx;
  2793. int j, ret;
  2794. set_encoder_id(output_files[ost->file_index], ost);
  2795. // Muxers use AV_PKT_DATA_DISPLAYMATRIX to signal rotation. On the other
  2796. // hand, the legacy API makes demuxers set "rotate" metadata entries,
  2797. // which have to be filtered out to prevent leaking them to output files.
  2798. av_dict_set(&ost->st->metadata, "rotate", NULL, 0);
  2799. if (ist) {
  2800. ost->st->disposition = ist->st->disposition;
  2801. dec_ctx = ist->dec_ctx;
  2802. enc_ctx->chroma_sample_location = dec_ctx->chroma_sample_location;
  2803. } else {
  2804. for (j = 0; j < oc->nb_streams; j++) {
  2805. AVStream *st = oc->streams[j];
  2806. if (st != ost->st && st->codecpar->codec_type == ost->st->codecpar->codec_type)
  2807. break;
  2808. }
  2809. if (j == oc->nb_streams)
  2810. if (ost->st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO ||
  2811. ost->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
  2812. ost->st->disposition = AV_DISPOSITION_DEFAULT;
  2813. }
  2814. if (enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO) {
  2815. if (!ost->frame_rate.num)
  2816. ost->frame_rate = av_buffersink_get_frame_rate(ost->filter->filter);
  2817. if (ist && !ost->frame_rate.num)
  2818. ost->frame_rate = ist->framerate;
  2819. if (ist && !ost->frame_rate.num)
  2820. ost->frame_rate = ist->st->r_frame_rate;
  2821. if (ist && !ost->frame_rate.num) {
  2822. ost->frame_rate = (AVRational){25, 1};
  2823. av_log(NULL, AV_LOG_WARNING,
  2824. "No information "
  2825. "about the input framerate is available. Falling "
  2826. "back to a default value of 25fps for output stream #%d:%d. Use the -r option "
  2827. "if you want a different framerate.\n",
  2828. ost->file_index, ost->index);
  2829. }
  2830. // ost->frame_rate = ist->st->avg_frame_rate.num ? ist->st->avg_frame_rate : (AVRational){25, 1};
  2831. if (ost->enc->supported_framerates && !ost->force_fps) {
  2832. int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
  2833. ost->frame_rate = ost->enc->supported_framerates[idx];
  2834. }
  2835. // reduce frame rate for mpeg4 to be within the spec limits
  2836. if (enc_ctx->codec_id == AV_CODEC_ID_MPEG4) {
  2837. av_reduce(&ost->frame_rate.num, &ost->frame_rate.den,
  2838. ost->frame_rate.num, ost->frame_rate.den, 65535);
  2839. }
  2840. }
  2841. switch (enc_ctx->codec_type) {
  2842. case AVMEDIA_TYPE_AUDIO:
  2843. enc_ctx->sample_fmt = av_buffersink_get_format(ost->filter->filter);
  2844. if (dec_ctx)
  2845. enc_ctx->bits_per_raw_sample = FFMIN(dec_ctx->bits_per_raw_sample,
  2846. av_get_bytes_per_sample(enc_ctx->sample_fmt) << 3);
  2847. enc_ctx->sample_rate = av_buffersink_get_sample_rate(ost->filter->filter);
  2848. enc_ctx->channel_layout = av_buffersink_get_channel_layout(ost->filter->filter);
  2849. enc_ctx->channels = av_buffersink_get_channels(ost->filter->filter);
  2850. enc_ctx->time_base = (AVRational){ 1, enc_ctx->sample_rate };
  2851. break;
  2852. case AVMEDIA_TYPE_VIDEO:
  2853. enc_ctx->time_base = av_inv_q(ost->frame_rate);
  2854. if (!(enc_ctx->time_base.num && enc_ctx->time_base.den))
  2855. enc_ctx->time_base = av_buffersink_get_time_base(ost->filter->filter);
  2856. if ( av_q2d(enc_ctx->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH
  2857. && (video_sync_method == VSYNC_CFR || video_sync_method == VSYNC_VSCFR || (video_sync_method == VSYNC_AUTO && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
  2858. av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"
  2859. "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
  2860. }
  2861. for (j = 0; j < ost->forced_kf_count; j++)
  2862. ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
  2863. AV_TIME_BASE_Q,
  2864. enc_ctx->time_base);
  2865. enc_ctx->width = av_buffersink_get_w(ost->filter->filter);
  2866. enc_ctx->height = av_buffersink_get_h(ost->filter->filter);
  2867. enc_ctx->sample_aspect_ratio = ost->st->sample_aspect_ratio =
  2868. ost->frame_aspect_ratio.num ? // overridden by the -aspect cli option
  2869. av_mul_q(ost->frame_aspect_ratio, (AVRational){ enc_ctx->height, enc_ctx->width }) :
  2870. av_buffersink_get_sample_aspect_ratio(ost->filter->filter);
  2871. if (!strncmp(ost->enc->name, "libx264", 7) &&
  2872. enc_ctx->pix_fmt == AV_PIX_FMT_NONE &&
  2873. av_buffersink_get_format(ost->filter->filter) != AV_PIX_FMT_YUV420P)
  2874. av_log(NULL, AV_LOG_WARNING,
  2875. "No pixel format specified, %s for H.264 encoding chosen.\n"
  2876. "Use -pix_fmt yuv420p for compatibility with outdated media players.\n",
  2877. av_get_pix_fmt_name(av_buffersink_get_format(ost->filter->filter)));
  2878. if (!strncmp(ost->enc->name, "mpeg2video", 10) &&
  2879. enc_ctx->pix_fmt == AV_PIX_FMT_NONE &&
  2880. av_buffersink_get_format(ost->filter->filter) != AV_PIX_FMT_YUV420P)
  2881. av_log(NULL, AV_LOG_WARNING,
  2882. "No pixel format specified, %s for MPEG-2 encoding chosen.\n"
  2883. "Use -pix_fmt yuv420p for compatibility with outdated media players.\n",
  2884. av_get_pix_fmt_name(av_buffersink_get_format(ost->filter->filter)));
  2885. enc_ctx->pix_fmt = av_buffersink_get_format(ost->filter->filter);
  2886. if (dec_ctx)
  2887. enc_ctx->bits_per_raw_sample = FFMIN(dec_ctx->bits_per_raw_sample,
  2888. av_pix_fmt_desc_get(enc_ctx->pix_fmt)->comp[0].depth);
  2889. enc_ctx->framerate = ost->frame_rate;
  2890. ost->st->avg_frame_rate = ost->frame_rate;
  2891. if (!dec_ctx ||
  2892. enc_ctx->width != dec_ctx->width ||
  2893. enc_ctx->height != dec_ctx->height ||
  2894. enc_ctx->pix_fmt != dec_ctx->pix_fmt) {
  2895. enc_ctx->bits_per_raw_sample = frame_bits_per_raw_sample;
  2896. }
  2897. if (ost->forced_keyframes) {
  2898. if (!strncmp(ost->forced_keyframes, "expr:", 5)) {
  2899. ret = av_expr_parse(&ost->forced_keyframes_pexpr, ost->forced_keyframes+5,
  2900. forced_keyframes_const_names, NULL, NULL, NULL, NULL, 0, NULL);
  2901. if (ret < 0) {
  2902. av_log(NULL, AV_LOG_ERROR,
  2903. "Invalid force_key_frames expression '%s'\n", ost->forced_keyframes+5);
  2904. return ret;
  2905. }
  2906. ost->forced_keyframes_expr_const_values[FKF_N] = 0;
  2907. ost->forced_keyframes_expr_const_values[FKF_N_FORCED] = 0;
  2908. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] = NAN;
  2909. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] = NAN;
  2910. // Don't parse the 'forced_keyframes' in case of 'keep-source-keyframes',
  2911. // parse it only for static kf timings
  2912. } else if(strncmp(ost->forced_keyframes, "source", 6)) {
  2913. parse_forced_key_frames(ost->forced_keyframes, ost, ost->enc_ctx);
  2914. }
  2915. }
  2916. break;
  2917. case AVMEDIA_TYPE_SUBTITLE:
  2918. enc_ctx->time_base = AV_TIME_BASE_Q;
  2919. if (!enc_ctx->width) {
  2920. enc_ctx->width = input_streams[ost->source_index]->st->codecpar->width;
  2921. enc_ctx->height = input_streams[ost->source_index]->st->codecpar->height;
  2922. }
  2923. break;
  2924. case AVMEDIA_TYPE_DATA:
  2925. break;
  2926. default:
  2927. abort();
  2928. break;
  2929. }
  2930. ost->mux_timebase = enc_ctx->time_base;
  2931. return 0;
  2932. }
  2933. static int init_output_stream(OutputStream *ost, char *error, int error_len)
  2934. {
  2935. int ret = 0;
  2936. if (ost->encoding_needed) {
  2937. AVCodec *codec = ost->enc;
  2938. AVCodecContext *dec = NULL;
  2939. InputStream *ist;
  2940. ret = init_output_stream_encode(ost);
  2941. if (ret < 0)
  2942. return ret;
  2943. if ((ist = get_input_stream(ost)))
  2944. dec = ist->dec_ctx;
  2945. if (dec && dec->subtitle_header) {
  2946. /* ASS code assumes this buffer is null terminated so add extra byte. */
  2947. ost->enc_ctx->subtitle_header = av_mallocz(dec->subtitle_header_size + 1);
  2948. if (!ost->enc_ctx->subtitle_header)
  2949. return AVERROR(ENOMEM);
  2950. memcpy(ost->enc_ctx->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
  2951. ost->enc_ctx->subtitle_header_size = dec->subtitle_header_size;
  2952. }
  2953. if (!av_dict_get(ost->encoder_opts, "threads", NULL, 0))
  2954. av_dict_set(&ost->encoder_opts, "threads", "auto", 0);
  2955. if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
  2956. !codec->defaults &&
  2957. !av_dict_get(ost->encoder_opts, "b", NULL, 0) &&
  2958. !av_dict_get(ost->encoder_opts, "ab", NULL, 0))
  2959. av_dict_set(&ost->encoder_opts, "b", "128000", 0);
  2960. if (ost->filter && av_buffersink_get_hw_frames_ctx(ost->filter->filter) &&
  2961. ((AVHWFramesContext*)av_buffersink_get_hw_frames_ctx(ost->filter->filter)->data)->format ==
  2962. av_buffersink_get_format(ost->filter->filter)) {
  2963. ost->enc_ctx->hw_frames_ctx = av_buffer_ref(av_buffersink_get_hw_frames_ctx(ost->filter->filter));
  2964. if (!ost->enc_ctx->hw_frames_ctx)
  2965. return AVERROR(ENOMEM);
  2966. }
  2967. if ((ret = avcodec_open2(ost->enc_ctx, codec, &ost->encoder_opts)) < 0) {
  2968. if (ret == AVERROR_EXPERIMENTAL)
  2969. abort_codec_experimental(codec, 1);
  2970. snprintf(error, error_len,
  2971. "Error while opening encoder for output stream #%d:%d - "
  2972. "maybe incorrect parameters such as bit_rate, rate, width or height",
  2973. ost->file_index, ost->index);
  2974. return ret;
  2975. }
  2976. if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
  2977. !(ost->enc->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE))
  2978. av_buffersink_set_frame_size(ost->filter->filter,
  2979. ost->enc_ctx->frame_size);
  2980. assert_avoptions(ost->encoder_opts);
  2981. if (ost->enc_ctx->bit_rate && ost->enc_ctx->bit_rate < 1000)
  2982. av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
  2983. " It takes bits/s as argument, not kbits/s\n");
  2984. ret = avcodec_parameters_from_context(ost->st->codecpar, ost->enc_ctx);
  2985. if (ret < 0) {
  2986. av_log(NULL, AV_LOG_FATAL,
  2987. "Error initializing the output stream codec context.\n");
  2988. exit_program(1);
  2989. }
  2990. /*
  2991. * FIXME: ost->st->codec should't be needed here anymore.
  2992. */
  2993. ret = avcodec_copy_context(ost->st->codec, ost->enc_ctx);
  2994. if (ret < 0)
  2995. return ret;
  2996. if (ost->enc_ctx->nb_coded_side_data) {
  2997. int i;
  2998. ost->st->side_data = av_realloc_array(NULL, ost->enc_ctx->nb_coded_side_data,
  2999. sizeof(*ost->st->side_data));
  3000. if (!ost->st->side_data)
  3001. return AVERROR(ENOMEM);
  3002. for (i = 0; i < ost->enc_ctx->nb_coded_side_data; i++) {
  3003. const AVPacketSideData *sd_src = &ost->enc_ctx->coded_side_data[i];
  3004. AVPacketSideData *sd_dst = &ost->st->side_data[i];
  3005. sd_dst->data = av_malloc(sd_src->size);
  3006. if (!sd_dst->data)
  3007. return AVERROR(ENOMEM);
  3008. memcpy(sd_dst->data, sd_src->data, sd_src->size);
  3009. sd_dst->size = sd_src->size;
  3010. sd_dst->type = sd_src->type;
  3011. ost->st->nb_side_data++;
  3012. }
  3013. }
  3014. /*
  3015. * Add global input side data. For now this is naive, and copies it
  3016. * from the input stream's global side data. All side data should
  3017. * really be funneled over AVFrame and libavfilter, then added back to
  3018. * packet side data, and then potentially using the first packet for
  3019. * global side data.
  3020. */
  3021. if (ist) {
  3022. int i;
  3023. for (i = 0; i < ist->st->nb_side_data; i++) {
  3024. AVPacketSideData *sd = &ist->st->side_data[i];
  3025. uint8_t *dst = av_stream_new_side_data(ost->st, sd->type, sd->size);
  3026. if (!dst)
  3027. return AVERROR(ENOMEM);
  3028. memcpy(dst, sd->data, sd->size);
  3029. if (ist->autorotate && sd->type == AV_PKT_DATA_DISPLAYMATRIX)
  3030. av_display_rotation_set((uint32_t *)dst, 0);
  3031. }
  3032. }
  3033. // copy timebase while removing common factors
  3034. if (ost->st->time_base.num <= 0 || ost->st->time_base.den <= 0)
  3035. ost->st->time_base = av_add_q(ost->enc_ctx->time_base, (AVRational){0, 1});
  3036. // copy estimated duration as a hint to the muxer
  3037. if (ost->st->duration <= 0 && ist && ist->st->duration > 0)
  3038. ost->st->duration = av_rescale_q(ist->st->duration, ist->st->time_base, ost->st->time_base);
  3039. ost->st->codec->codec= ost->enc_ctx->codec;
  3040. } else if (ost->stream_copy) {
  3041. ret = init_output_stream_streamcopy(ost);
  3042. if (ret < 0)
  3043. return ret;
  3044. /*
  3045. * FIXME: will the codec context used by the parser during streamcopy
  3046. * This should go away with the new parser API.
  3047. */
  3048. ret = avcodec_parameters_to_context(ost->parser_avctx, ost->st->codecpar);
  3049. if (ret < 0)
  3050. return ret;
  3051. }
  3052. // parse user provided disposition, and update stream values
  3053. if (ost->disposition) {
  3054. static const AVOption opts[] = {
  3055. { "disposition" , NULL, 0, AV_OPT_TYPE_FLAGS, { .i64 = 0 }, INT64_MIN, INT64_MAX, .unit = "flags" },
  3056. { "default" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DEFAULT }, .unit = "flags" },
  3057. { "dub" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DUB }, .unit = "flags" },
  3058. { "original" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_ORIGINAL }, .unit = "flags" },
  3059. { "comment" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_COMMENT }, .unit = "flags" },
  3060. { "lyrics" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_LYRICS }, .unit = "flags" },
  3061. { "karaoke" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_KARAOKE }, .unit = "flags" },
  3062. { "forced" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_FORCED }, .unit = "flags" },
  3063. { "hearing_impaired" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_HEARING_IMPAIRED }, .unit = "flags" },
  3064. { "visual_impaired" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_VISUAL_IMPAIRED }, .unit = "flags" },
  3065. { "clean_effects" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_CLEAN_EFFECTS }, .unit = "flags" },
  3066. { "captions" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_CAPTIONS }, .unit = "flags" },
  3067. { "descriptions" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DESCRIPTIONS }, .unit = "flags" },
  3068. { "metadata" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_METADATA }, .unit = "flags" },
  3069. { NULL },
  3070. };
  3071. static const AVClass class = {
  3072. .class_name = "",
  3073. .item_name = av_default_item_name,
  3074. .option = opts,
  3075. .version = LIBAVUTIL_VERSION_INT,
  3076. };
  3077. const AVClass *pclass = &class;
  3078. ret = av_opt_eval_flags(&pclass, &opts[0], ost->disposition, &ost->st->disposition);
  3079. if (ret < 0)
  3080. return ret;
  3081. }
  3082. /* initialize bitstream filters for the output stream
  3083. * needs to be done here, because the codec id for streamcopy is not
  3084. * known until now */
  3085. ret = init_output_bsfs(ost);
  3086. if (ret < 0)
  3087. return ret;
  3088. ost->initialized = 1;
  3089. ret = check_init_output_file(output_files[ost->file_index], ost->file_index);
  3090. if (ret < 0)
  3091. return ret;
  3092. return ret;
  3093. }
  3094. static void report_new_stream(int input_index, AVPacket *pkt)
  3095. {
  3096. InputFile *file = input_files[input_index];
  3097. AVStream *st = file->ctx->streams[pkt->stream_index];
  3098. if (pkt->stream_index < file->nb_streams_warn)
  3099. return;
  3100. av_log(file->ctx, AV_LOG_WARNING,
  3101. "New %s stream %d:%d at pos:%"PRId64" and DTS:%ss\n",
  3102. av_get_media_type_string(st->codecpar->codec_type),
  3103. input_index, pkt->stream_index,
  3104. pkt->pos, av_ts2timestr(pkt->dts, &st->time_base));
  3105. file->nb_streams_warn = pkt->stream_index + 1;
  3106. }
  3107. static int transcode_init(void)
  3108. {
  3109. int ret = 0, i, j, k;
  3110. AVFormatContext *oc;
  3111. OutputStream *ost;
  3112. InputStream *ist;
  3113. char error[1024] = {0};
  3114. for (i = 0; i < nb_filtergraphs; i++) {
  3115. FilterGraph *fg = filtergraphs[i];
  3116. for (j = 0; j < fg->nb_outputs; j++) {
  3117. OutputFilter *ofilter = fg->outputs[j];
  3118. if (!ofilter->ost || ofilter->ost->source_index >= 0)
  3119. continue;
  3120. if (fg->nb_inputs != 1)
  3121. continue;
  3122. for (k = nb_input_streams-1; k >= 0 ; k--)
  3123. if (fg->inputs[0]->ist == input_streams[k])
  3124. break;
  3125. ofilter->ost->source_index = k;
  3126. }
  3127. }
  3128. /* init framerate emulation */
  3129. for (i = 0; i < nb_input_files; i++) {
  3130. InputFile *ifile = input_files[i];
  3131. if (ifile->rate_emu)
  3132. for (j = 0; j < ifile->nb_streams; j++)
  3133. input_streams[j + ifile->ist_index]->start = av_gettime_relative();
  3134. }
  3135. /* init input streams */
  3136. for (i = 0; i < nb_input_streams; i++)
  3137. if ((ret = init_input_stream(i, error, sizeof(error))) < 0) {
  3138. for (i = 0; i < nb_output_streams; i++) {
  3139. ost = output_streams[i];
  3140. avcodec_close(ost->enc_ctx);
  3141. }
  3142. goto dump_format;
  3143. }
  3144. /* open each encoder */
  3145. for (i = 0; i < nb_output_streams; i++) {
  3146. // skip streams fed from filtergraphs until we have a frame for them
  3147. if (output_streams[i]->filter)
  3148. continue;
  3149. ret = init_output_stream(output_streams[i], error, sizeof(error));
  3150. if (ret < 0)
  3151. goto dump_format;
  3152. }
  3153. /* discard unused programs */
  3154. for (i = 0; i < nb_input_files; i++) {
  3155. InputFile *ifile = input_files[i];
  3156. for (j = 0; j < ifile->ctx->nb_programs; j++) {
  3157. AVProgram *p = ifile->ctx->programs[j];
  3158. int discard = AVDISCARD_ALL;
  3159. for (k = 0; k < p->nb_stream_indexes; k++)
  3160. if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
  3161. discard = AVDISCARD_DEFAULT;
  3162. break;
  3163. }
  3164. p->discard = discard;
  3165. }
  3166. }
  3167. /* write headers for files with no streams */
  3168. for (i = 0; i < nb_output_files; i++) {
  3169. oc = output_files[i]->ctx;
  3170. if (oc->oformat->flags & AVFMT_NOSTREAMS && oc->nb_streams == 0) {
  3171. ret = check_init_output_file(output_files[i], i);
  3172. if (ret < 0)
  3173. goto dump_format;
  3174. }
  3175. }
  3176. dump_format:
  3177. /* dump the stream mapping */
  3178. av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
  3179. for (i = 0; i < nb_input_streams; i++) {
  3180. ist = input_streams[i];
  3181. for (j = 0; j < ist->nb_filters; j++) {
  3182. if (!filtergraph_is_simple(ist->filters[j]->graph)) {
  3183. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
  3184. ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
  3185. ist->filters[j]->name);
  3186. if (nb_filtergraphs > 1)
  3187. av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
  3188. av_log(NULL, AV_LOG_INFO, "\n");
  3189. }
  3190. }
  3191. }
  3192. for (i = 0; i < nb_output_streams; i++) {
  3193. ost = output_streams[i];
  3194. if (ost->attachment_filename) {
  3195. /* an attached file */
  3196. av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
  3197. ost->attachment_filename, ost->file_index, ost->index);
  3198. continue;
  3199. }
  3200. if (ost->filter && !filtergraph_is_simple(ost->filter->graph)) {
  3201. /* output from a complex graph */
  3202. av_log(NULL, AV_LOG_INFO, " %s", ost->filter->name);
  3203. if (nb_filtergraphs > 1)
  3204. av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
  3205. av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
  3206. ost->index, ost->enc ? ost->enc->name : "?");
  3207. continue;
  3208. }
  3209. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
  3210. input_streams[ost->source_index]->file_index,
  3211. input_streams[ost->source_index]->st->index,
  3212. ost->file_index,
  3213. ost->index);
  3214. if (ost->sync_ist != input_streams[ost->source_index])
  3215. av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
  3216. ost->sync_ist->file_index,
  3217. ost->sync_ist->st->index);
  3218. if (ost->stream_copy)
  3219. av_log(NULL, AV_LOG_INFO, " (copy)");
  3220. else {
  3221. const AVCodec *in_codec = input_streams[ost->source_index]->dec;
  3222. const AVCodec *out_codec = ost->enc;
  3223. const char *decoder_name = "?";
  3224. const char *in_codec_name = "?";
  3225. const char *encoder_name = "?";
  3226. const char *out_codec_name = "?";
  3227. const AVCodecDescriptor *desc;
  3228. if (in_codec) {
  3229. decoder_name = in_codec->name;
  3230. desc = avcodec_descriptor_get(in_codec->id);
  3231. if (desc)
  3232. in_codec_name = desc->name;
  3233. if (!strcmp(decoder_name, in_codec_name))
  3234. decoder_name = "native";
  3235. }
  3236. if (out_codec) {
  3237. encoder_name = out_codec->name;
  3238. desc = avcodec_descriptor_get(out_codec->id);
  3239. if (desc)
  3240. out_codec_name = desc->name;
  3241. if (!strcmp(encoder_name, out_codec_name))
  3242. encoder_name = "native";
  3243. }
  3244. av_log(NULL, AV_LOG_INFO, " (%s (%s) -> %s (%s))",
  3245. in_codec_name, decoder_name,
  3246. out_codec_name, encoder_name);
  3247. }
  3248. av_log(NULL, AV_LOG_INFO, "\n");
  3249. }
  3250. if (ret) {
  3251. av_log(NULL, AV_LOG_ERROR, "%s\n", error);
  3252. return ret;
  3253. }
  3254. atomic_store(&transcode_init_done, 1);
  3255. return 0;
  3256. }
  3257. /* Return 1 if there remain streams where more output is wanted, 0 otherwise. */
  3258. static int need_output(void)
  3259. {
  3260. int i;
  3261. for (i = 0; i < nb_output_streams; i++) {
  3262. OutputStream *ost = output_streams[i];
  3263. OutputFile *of = output_files[ost->file_index];
  3264. AVFormatContext *os = output_files[ost->file_index]->ctx;
  3265. if (ost->finished ||
  3266. (os->pb && avio_tell(os->pb) >= of->limit_filesize))
  3267. continue;
  3268. if (ost->frame_number >= ost->max_frames) {
  3269. int j;
  3270. for (j = 0; j < of->ctx->nb_streams; j++)
  3271. close_output_stream(output_streams[of->ost_index + j]);
  3272. continue;
  3273. }
  3274. return 1;
  3275. }
  3276. return 0;
  3277. }
  3278. /**
  3279. * Select the output stream to process.
  3280. *
  3281. * @return selected output stream, or NULL if none available
  3282. */
  3283. static OutputStream *choose_output(void)
  3284. {
  3285. int i;
  3286. int64_t opts_min = INT64_MAX;
  3287. OutputStream *ost_min = NULL;
  3288. for (i = 0; i < nb_output_streams; i++) {
  3289. OutputStream *ost = output_streams[i];
  3290. int64_t opts = ost->st->cur_dts == AV_NOPTS_VALUE ? INT64_MIN :
  3291. av_rescale_q(ost->st->cur_dts, ost->st->time_base,
  3292. AV_TIME_BASE_Q);
  3293. if (ost->st->cur_dts == AV_NOPTS_VALUE)
  3294. av_log(NULL, AV_LOG_DEBUG, "cur_dts is invalid (this is harmless if it occurs once at the start per stream)\n");
  3295. if (!ost->initialized && !ost->inputs_done)
  3296. return ost;
  3297. if (!ost->finished && opts < opts_min) {
  3298. opts_min = opts;
  3299. ost_min = ost->unavailable ? NULL : ost;
  3300. }
  3301. }
  3302. return ost_min;
  3303. }
  3304. static void set_tty_echo(int on)
  3305. {
  3306. #if HAVE_TERMIOS_H
  3307. struct termios tty;
  3308. if (tcgetattr(0, &tty) == 0) {
  3309. if (on) tty.c_lflag |= ECHO;
  3310. else tty.c_lflag &= ~ECHO;
  3311. tcsetattr(0, TCSANOW, &tty);
  3312. }
  3313. #endif
  3314. }
  3315. static int check_keyboard_interaction(int64_t cur_time)
  3316. {
  3317. int i, ret, key;
  3318. static int64_t last_time;
  3319. if (received_nb_signals)
  3320. return AVERROR_EXIT;
  3321. /* read_key() returns 0 on EOF */
  3322. if(cur_time - last_time >= 100000 && !run_as_daemon){
  3323. key = read_key();
  3324. last_time = cur_time;
  3325. }else
  3326. key = -1;
  3327. if (key == 'q')
  3328. return AVERROR_EXIT;
  3329. if (key == '+') av_log_set_level(av_log_get_level()+10);
  3330. if (key == '-') av_log_set_level(av_log_get_level()-10);
  3331. if (key == 's') qp_hist ^= 1;
  3332. if (key == 'h'){
  3333. if (do_hex_dump){
  3334. do_hex_dump = do_pkt_dump = 0;
  3335. } else if(do_pkt_dump){
  3336. do_hex_dump = 1;
  3337. } else
  3338. do_pkt_dump = 1;
  3339. av_log_set_level(AV_LOG_DEBUG);
  3340. }
  3341. if (key == 'c' || key == 'C'){
  3342. char buf[4096], target[64], command[256], arg[256] = {0};
  3343. double time;
  3344. int k, n = 0;
  3345. fprintf(stderr, "\nEnter command: <target>|all <time>|-1 <command>[ <argument>]\n");
  3346. i = 0;
  3347. set_tty_echo(1);
  3348. while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
  3349. if (k > 0)
  3350. buf[i++] = k;
  3351. buf[i] = 0;
  3352. set_tty_echo(0);
  3353. fprintf(stderr, "\n");
  3354. if (k > 0 &&
  3355. (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
  3356. av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
  3357. target, time, command, arg);
  3358. for (i = 0; i < nb_filtergraphs; i++) {
  3359. FilterGraph *fg = filtergraphs[i];
  3360. if (fg->graph) {
  3361. if (time < 0) {
  3362. ret = avfilter_graph_send_command(fg->graph, target, command, arg, buf, sizeof(buf),
  3363. key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
  3364. fprintf(stderr, "Command reply for stream %d: ret:%d res:\n%s", i, ret, buf);
  3365. } else if (key == 'c') {
  3366. fprintf(stderr, "Queuing commands only on filters supporting the specific command is unsupported\n");
  3367. ret = AVERROR_PATCHWELCOME;
  3368. } else {
  3369. ret = avfilter_graph_queue_command(fg->graph, target, command, arg, 0, time);
  3370. if (ret < 0)
  3371. fprintf(stderr, "Queuing command failed with error %s\n", av_err2str(ret));
  3372. }
  3373. }
  3374. }
  3375. } else {
  3376. av_log(NULL, AV_LOG_ERROR,
  3377. "Parse error, at least 3 arguments were expected, "
  3378. "only %d given in string '%s'\n", n, buf);
  3379. }
  3380. }
  3381. if (key == 'd' || key == 'D'){
  3382. int debug=0;
  3383. if(key == 'D') {
  3384. debug = input_streams[0]->st->codec->debug<<1;
  3385. if(!debug) debug = 1;
  3386. while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
  3387. debug += debug;
  3388. }else{
  3389. char buf[32];
  3390. int k = 0;
  3391. i = 0;
  3392. set_tty_echo(1);
  3393. while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
  3394. if (k > 0)
  3395. buf[i++] = k;
  3396. buf[i] = 0;
  3397. set_tty_echo(0);
  3398. fprintf(stderr, "\n");
  3399. if (k <= 0 || sscanf(buf, "%d", &debug)!=1)
  3400. fprintf(stderr,"error parsing debug value\n");
  3401. }
  3402. for(i=0;i<nb_input_streams;i++) {
  3403. input_streams[i]->st->codec->debug = debug;
  3404. }
  3405. for(i=0;i<nb_output_streams;i++) {
  3406. OutputStream *ost = output_streams[i];
  3407. ost->enc_ctx->debug = debug;
  3408. }
  3409. if(debug) av_log_set_level(AV_LOG_DEBUG);
  3410. fprintf(stderr,"debug=%d\n", debug);
  3411. }
  3412. if (key == '?'){
  3413. fprintf(stderr, "key function\n"
  3414. "? show this help\n"
  3415. "+ increase verbosity\n"
  3416. "- decrease verbosity\n"
  3417. "c Send command to first matching filter supporting it\n"
  3418. "C Send/Queue command to all matching filters\n"
  3419. "D cycle through available debug modes\n"
  3420. "h dump packets/hex press to cycle through the 3 states\n"
  3421. "q quit\n"
  3422. "s Show QP histogram\n"
  3423. );
  3424. }
  3425. return 0;
  3426. }
  3427. #if HAVE_PTHREADS
  3428. static void *input_thread(void *arg)
  3429. {
  3430. InputFile *f = arg;
  3431. unsigned flags = f->non_blocking ? AV_THREAD_MESSAGE_NONBLOCK : 0;
  3432. int ret = 0;
  3433. while (1) {
  3434. AVPacket pkt;
  3435. ret = av_read_frame(f->ctx, &pkt);
  3436. if (ret == AVERROR(EAGAIN)) {
  3437. av_usleep(10000);
  3438. continue;
  3439. }
  3440. if (ret < 0) {
  3441. av_thread_message_queue_set_err_recv(f->in_thread_queue, ret);
  3442. break;
  3443. }
  3444. ret = av_thread_message_queue_send(f->in_thread_queue, &pkt, flags);
  3445. if (flags && ret == AVERROR(EAGAIN)) {
  3446. flags = 0;
  3447. ret = av_thread_message_queue_send(f->in_thread_queue, &pkt, flags);
  3448. av_log(f->ctx, AV_LOG_WARNING,
  3449. "Thread message queue blocking; consider raising the "
  3450. "thread_queue_size option (current value: %d)\n",
  3451. f->thread_queue_size);
  3452. }
  3453. if (ret < 0) {
  3454. if (ret != AVERROR_EOF)
  3455. av_log(f->ctx, AV_LOG_ERROR,
  3456. "Unable to send packet to main thread: %s\n",
  3457. av_err2str(ret));
  3458. av_packet_unref(&pkt);
  3459. av_thread_message_queue_set_err_recv(f->in_thread_queue, ret);
  3460. break;
  3461. }
  3462. }
  3463. return NULL;
  3464. }
  3465. static void free_input_threads(void)
  3466. {
  3467. int i;
  3468. for (i = 0; i < nb_input_files; i++) {
  3469. InputFile *f = input_files[i];
  3470. AVPacket pkt;
  3471. if (!f || !f->in_thread_queue)
  3472. continue;
  3473. av_thread_message_queue_set_err_send(f->in_thread_queue, AVERROR_EOF);
  3474. while (av_thread_message_queue_recv(f->in_thread_queue, &pkt, 0) >= 0)
  3475. av_packet_unref(&pkt);
  3476. pthread_join(f->thread, NULL);
  3477. f->joined = 1;
  3478. av_thread_message_queue_free(&f->in_thread_queue);
  3479. }
  3480. }
  3481. static int init_input_threads(void)
  3482. {
  3483. int i, ret;
  3484. if (nb_input_files == 1)
  3485. return 0;
  3486. for (i = 0; i < nb_input_files; i++) {
  3487. InputFile *f = input_files[i];
  3488. if (f->ctx->pb ? !f->ctx->pb->seekable :
  3489. strcmp(f->ctx->iformat->name, "lavfi"))
  3490. f->non_blocking = 1;
  3491. ret = av_thread_message_queue_alloc(&f->in_thread_queue,
  3492. f->thread_queue_size, sizeof(AVPacket));
  3493. if (ret < 0)
  3494. return ret;
  3495. if ((ret = pthread_create(&f->thread, NULL, input_thread, f))) {
  3496. av_log(NULL, AV_LOG_ERROR, "pthread_create failed: %s. Try to increase `ulimit -v` or decrease `ulimit -s`.\n", strerror(ret));
  3497. av_thread_message_queue_free(&f->in_thread_queue);
  3498. return AVERROR(ret);
  3499. }
  3500. }
  3501. return 0;
  3502. }
  3503. static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
  3504. {
  3505. return av_thread_message_queue_recv(f->in_thread_queue, pkt,
  3506. f->non_blocking ?
  3507. AV_THREAD_MESSAGE_NONBLOCK : 0);
  3508. }
  3509. #endif
  3510. static int get_input_packet(InputFile *f, AVPacket *pkt)
  3511. {
  3512. if (f->rate_emu) {
  3513. int i;
  3514. for (i = 0; i < f->nb_streams; i++) {
  3515. InputStream *ist = input_streams[f->ist_index + i];
  3516. int64_t pts = av_rescale(ist->dts, 1000000, AV_TIME_BASE);
  3517. int64_t now = av_gettime_relative() - ist->start;
  3518. if (pts > now)
  3519. return AVERROR(EAGAIN);
  3520. }
  3521. }
  3522. #if HAVE_PTHREADS
  3523. if (nb_input_files > 1)
  3524. return get_input_packet_mt(f, pkt);
  3525. #endif
  3526. return av_read_frame(f->ctx, pkt);
  3527. }
  3528. static int got_eagain(void)
  3529. {
  3530. int i;
  3531. for (i = 0; i < nb_output_streams; i++)
  3532. if (output_streams[i]->unavailable)
  3533. return 1;
  3534. return 0;
  3535. }
  3536. static void reset_eagain(void)
  3537. {
  3538. int i;
  3539. for (i = 0; i < nb_input_files; i++)
  3540. input_files[i]->eagain = 0;
  3541. for (i = 0; i < nb_output_streams; i++)
  3542. output_streams[i]->unavailable = 0;
  3543. }
  3544. // set duration to max(tmp, duration) in a proper time base and return duration's time_base
  3545. static AVRational duration_max(int64_t tmp, int64_t *duration, AVRational tmp_time_base,
  3546. AVRational time_base)
  3547. {
  3548. int ret;
  3549. if (!*duration) {
  3550. *duration = tmp;
  3551. return tmp_time_base;
  3552. }
  3553. ret = av_compare_ts(*duration, time_base, tmp, tmp_time_base);
  3554. if (ret < 0) {
  3555. *duration = tmp;
  3556. return tmp_time_base;
  3557. }
  3558. return time_base;
  3559. }
  3560. static int seek_to_start(InputFile *ifile, AVFormatContext *is)
  3561. {
  3562. InputStream *ist;
  3563. AVCodecContext *avctx;
  3564. int i, ret, has_audio = 0;
  3565. int64_t duration = 0;
  3566. ret = av_seek_frame(is, -1, is->start_time, 0);
  3567. if (ret < 0)
  3568. return ret;
  3569. for (i = 0; i < ifile->nb_streams; i++) {
  3570. ist = input_streams[ifile->ist_index + i];
  3571. avctx = ist->dec_ctx;
  3572. // flush decoders
  3573. if (ist->decoding_needed) {
  3574. process_input_packet(ist, NULL, 1);
  3575. avcodec_flush_buffers(avctx);
  3576. }
  3577. /* duration is the length of the last frame in a stream
  3578. * when audio stream is present we don't care about
  3579. * last video frame length because it's not defined exactly */
  3580. if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && ist->nb_samples)
  3581. has_audio = 1;
  3582. }
  3583. for (i = 0; i < ifile->nb_streams; i++) {
  3584. ist = input_streams[ifile->ist_index + i];
  3585. avctx = ist->dec_ctx;
  3586. if (has_audio) {
  3587. if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && ist->nb_samples) {
  3588. AVRational sample_rate = {1, avctx->sample_rate};
  3589. duration = av_rescale_q(ist->nb_samples, sample_rate, ist->st->time_base);
  3590. } else
  3591. continue;
  3592. } else {
  3593. if (ist->framerate.num) {
  3594. duration = av_rescale_q(1, ist->framerate, ist->st->time_base);
  3595. } else if (ist->st->avg_frame_rate.num) {
  3596. duration = av_rescale_q(1, ist->st->avg_frame_rate, ist->st->time_base);
  3597. } else duration = 1;
  3598. }
  3599. if (!ifile->duration)
  3600. ifile->time_base = ist->st->time_base;
  3601. /* the total duration of the stream, max_pts - min_pts is
  3602. * the duration of the stream without the last frame */
  3603. duration += ist->max_pts - ist->min_pts;
  3604. ifile->time_base = duration_max(duration, &ifile->duration, ist->st->time_base,
  3605. ifile->time_base);
  3606. }
  3607. if (ifile->loop > 0)
  3608. ifile->loop--;
  3609. return ret;
  3610. }
  3611. /*
  3612. * Return
  3613. * - 0 -- one packet was read and processed
  3614. * - AVERROR(EAGAIN) -- no packets were available for selected file,
  3615. * this function should be called again
  3616. * - AVERROR_EOF -- this function should not be called again
  3617. */
  3618. static int process_input(int file_index)
  3619. {
  3620. InputFile *ifile = input_files[file_index];
  3621. AVFormatContext *is;
  3622. InputStream *ist;
  3623. AVPacket pkt;
  3624. int ret, i, j;
  3625. int64_t duration;
  3626. int64_t pkt_dts;
  3627. is = ifile->ctx;
  3628. ret = get_input_packet(ifile, &pkt);
  3629. if (ret == AVERROR(EAGAIN)) {
  3630. ifile->eagain = 1;
  3631. return ret;
  3632. }
  3633. if (ret < 0 && ifile->loop) {
  3634. if ((ret = seek_to_start(ifile, is)) < 0)
  3635. return ret;
  3636. ret = get_input_packet(ifile, &pkt);
  3637. if (ret == AVERROR(EAGAIN)) {
  3638. ifile->eagain = 1;
  3639. return ret;
  3640. }
  3641. }
  3642. if (ret < 0) {
  3643. if (ret != AVERROR_EOF) {
  3644. print_error(is->filename, ret);
  3645. if (exit_on_error)
  3646. exit_program(1);
  3647. }
  3648. for (i = 0; i < ifile->nb_streams; i++) {
  3649. ist = input_streams[ifile->ist_index + i];
  3650. if (ist->decoding_needed) {
  3651. ret = process_input_packet(ist, NULL, 0);
  3652. if (ret>0)
  3653. return 0;
  3654. }
  3655. /* mark all outputs that don't go through lavfi as finished */
  3656. for (j = 0; j < nb_output_streams; j++) {
  3657. OutputStream *ost = output_streams[j];
  3658. if (ost->source_index == ifile->ist_index + i &&
  3659. (ost->stream_copy || ost->enc->type == AVMEDIA_TYPE_SUBTITLE))
  3660. finish_output_stream(ost);
  3661. }
  3662. }
  3663. ifile->eof_reached = 1;
  3664. return AVERROR(EAGAIN);
  3665. }
  3666. reset_eagain();
  3667. if (do_pkt_dump) {
  3668. av_pkt_dump_log2(NULL, AV_LOG_INFO, &pkt, do_hex_dump,
  3669. is->streams[pkt.stream_index]);
  3670. }
  3671. /* the following test is needed in case new streams appear
  3672. dynamically in stream : we ignore them */
  3673. if (pkt.stream_index >= ifile->nb_streams) {
  3674. report_new_stream(file_index, &pkt);
  3675. goto discard_packet;
  3676. }
  3677. ist = input_streams[ifile->ist_index + pkt.stream_index];
  3678. ist->data_size += pkt.size;
  3679. ist->nb_packets++;
  3680. if (ist->discard)
  3681. goto discard_packet;
  3682. if (exit_on_error && (pkt.flags & AV_PKT_FLAG_CORRUPT)) {
  3683. av_log(NULL, AV_LOG_FATAL, "%s: corrupt input packet in stream %d\n", is->filename, pkt.stream_index);
  3684. exit_program(1);
  3685. }
  3686. if (debug_ts) {
  3687. av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
  3688. "next_dts:%s next_dts_time:%s next_pts:%s next_pts_time:%s pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s off:%s off_time:%s\n",
  3689. ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->dec_ctx->codec_type),
  3690. av_ts2str(ist->next_dts), av_ts2timestr(ist->next_dts, &AV_TIME_BASE_Q),
  3691. av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &AV_TIME_BASE_Q),
  3692. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
  3693. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
  3694. av_ts2str(input_files[ist->file_index]->ts_offset),
  3695. av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
  3696. }
  3697. if(!ist->wrap_correction_done && is->start_time != AV_NOPTS_VALUE && ist->st->pts_wrap_bits < 64){
  3698. int64_t stime, stime2;
  3699. // Correcting starttime based on the enabled streams
  3700. // FIXME this ideally should be done before the first use of starttime but we do not know which are the enabled streams at that point.
  3701. // so we instead do it here as part of discontinuity handling
  3702. if ( ist->next_dts == AV_NOPTS_VALUE
  3703. && ifile->ts_offset == -is->start_time
  3704. && (is->iformat->flags & AVFMT_TS_DISCONT)) {
  3705. int64_t new_start_time = INT64_MAX;
  3706. for (i=0; i<is->nb_streams; i++) {
  3707. AVStream *st = is->streams[i];
  3708. if(st->discard == AVDISCARD_ALL || st->start_time == AV_NOPTS_VALUE)
  3709. continue;
  3710. new_start_time = FFMIN(new_start_time, av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q));
  3711. }
  3712. if (new_start_time > is->start_time) {
  3713. av_log(is, AV_LOG_VERBOSE, "Correcting start time by %"PRId64"\n", new_start_time - is->start_time);
  3714. ifile->ts_offset = -new_start_time;
  3715. }
  3716. }
  3717. stime = av_rescale_q(is->start_time, AV_TIME_BASE_Q, ist->st->time_base);
  3718. stime2= stime + (1ULL<<ist->st->pts_wrap_bits);
  3719. ist->wrap_correction_done = 1;
  3720. if(stime2 > stime && pkt.dts != AV_NOPTS_VALUE && pkt.dts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
  3721. pkt.dts -= 1ULL<<ist->st->pts_wrap_bits;
  3722. ist->wrap_correction_done = 0;
  3723. }
  3724. if(stime2 > stime && pkt.pts != AV_NOPTS_VALUE && pkt.pts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
  3725. pkt.pts -= 1ULL<<ist->st->pts_wrap_bits;
  3726. ist->wrap_correction_done = 0;
  3727. }
  3728. }
  3729. /* add the stream-global side data to the first packet */
  3730. if (ist->nb_packets == 1) {
  3731. for (i = 0; i < ist->st->nb_side_data; i++) {
  3732. AVPacketSideData *src_sd = &ist->st->side_data[i];
  3733. uint8_t *dst_data;
  3734. if (src_sd->type == AV_PKT_DATA_DISPLAYMATRIX)
  3735. continue;
  3736. if (av_packet_get_side_data(&pkt, src_sd->type, NULL))
  3737. continue;
  3738. dst_data = av_packet_new_side_data(&pkt, src_sd->type, src_sd->size);
  3739. if (!dst_data)
  3740. exit_program(1);
  3741. memcpy(dst_data, src_sd->data, src_sd->size);
  3742. }
  3743. }
  3744. if (pkt.dts != AV_NOPTS_VALUE)
  3745. pkt.dts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
  3746. if (pkt.pts != AV_NOPTS_VALUE)
  3747. pkt.pts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
  3748. if (pkt.pts != AV_NOPTS_VALUE)
  3749. pkt.pts *= ist->ts_scale;
  3750. if (pkt.dts != AV_NOPTS_VALUE)
  3751. pkt.dts *= ist->ts_scale;
  3752. pkt_dts = av_rescale_q_rnd(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
  3753. if ((ist->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
  3754. ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&
  3755. pkt_dts != AV_NOPTS_VALUE && ist->next_dts == AV_NOPTS_VALUE && !copy_ts
  3756. && (is->iformat->flags & AVFMT_TS_DISCONT) && ifile->last_ts != AV_NOPTS_VALUE) {
  3757. int64_t delta = pkt_dts - ifile->last_ts;
  3758. if (delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
  3759. delta > 1LL*dts_delta_threshold*AV_TIME_BASE){
  3760. ifile->ts_offset -= delta;
  3761. av_log(NULL, AV_LOG_DEBUG,
  3762. "Inter stream timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
  3763. delta, ifile->ts_offset);
  3764. pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  3765. if (pkt.pts != AV_NOPTS_VALUE)
  3766. pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  3767. }
  3768. }
  3769. duration = av_rescale_q(ifile->duration, ifile->time_base, ist->st->time_base);
  3770. if (pkt.pts != AV_NOPTS_VALUE) {
  3771. pkt.pts += duration;
  3772. ist->max_pts = FFMAX(pkt.pts, ist->max_pts);
  3773. ist->min_pts = FFMIN(pkt.pts, ist->min_pts);
  3774. }
  3775. if (pkt.dts != AV_NOPTS_VALUE)
  3776. pkt.dts += duration;
  3777. pkt_dts = av_rescale_q_rnd(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
  3778. if ((ist->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
  3779. ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&
  3780. pkt_dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE &&
  3781. !copy_ts) {
  3782. int64_t delta = pkt_dts - ist->next_dts;
  3783. if (is->iformat->flags & AVFMT_TS_DISCONT) {
  3784. if (delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
  3785. delta > 1LL*dts_delta_threshold*AV_TIME_BASE ||
  3786. pkt_dts + AV_TIME_BASE/10 < FFMAX(ist->pts, ist->dts)) {
  3787. ifile->ts_offset -= delta;
  3788. av_log(NULL, AV_LOG_DEBUG,
  3789. "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
  3790. delta, ifile->ts_offset);
  3791. pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  3792. if (pkt.pts != AV_NOPTS_VALUE)
  3793. pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  3794. }
  3795. } else {
  3796. if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
  3797. delta > 1LL*dts_error_threshold*AV_TIME_BASE) {
  3798. av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);
  3799. pkt.dts = AV_NOPTS_VALUE;
  3800. }
  3801. if (pkt.pts != AV_NOPTS_VALUE){
  3802. int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);
  3803. delta = pkt_pts - ist->next_dts;
  3804. if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
  3805. delta > 1LL*dts_error_threshold*AV_TIME_BASE) {
  3806. av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);
  3807. pkt.pts = AV_NOPTS_VALUE;
  3808. }
  3809. }
  3810. }
  3811. }
  3812. if (pkt.dts != AV_NOPTS_VALUE)
  3813. ifile->last_ts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
  3814. if (debug_ts) {
  3815. av_log(NULL, AV_LOG_INFO, "demuxer+ffmpeg -> ist_index:%d type:%s pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s off:%s off_time:%s\n",
  3816. ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->dec_ctx->codec_type),
  3817. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
  3818. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
  3819. av_ts2str(input_files[ist->file_index]->ts_offset),
  3820. av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
  3821. }
  3822. sub2video_heartbeat(ist, pkt.pts);
  3823. process_input_packet(ist, &pkt, 0);
  3824. discard_packet:
  3825. av_packet_unref(&pkt);
  3826. return 0;
  3827. }
  3828. /**
  3829. * Perform a step of transcoding for the specified filter graph.
  3830. *
  3831. * @param[in] graph filter graph to consider
  3832. * @param[out] best_ist input stream where a frame would allow to continue
  3833. * @return 0 for success, <0 for error
  3834. */
  3835. static int transcode_from_filter(FilterGraph *graph, InputStream **best_ist)
  3836. {
  3837. int i, ret;
  3838. int nb_requests, nb_requests_max = 0;
  3839. InputFilter *ifilter;
  3840. InputStream *ist;
  3841. *best_ist = NULL;
  3842. ret = avfilter_graph_request_oldest(graph->graph);
  3843. if (ret >= 0)
  3844. return reap_filters(0);
  3845. if (ret == AVERROR_EOF) {
  3846. ret = reap_filters(1);
  3847. for (i = 0; i < graph->nb_outputs; i++)
  3848. close_output_stream(graph->outputs[i]->ost);
  3849. return ret;
  3850. }
  3851. if (ret != AVERROR(EAGAIN))
  3852. return ret;
  3853. for (i = 0; i < graph->nb_inputs; i++) {
  3854. ifilter = graph->inputs[i];
  3855. ist = ifilter->ist;
  3856. if (input_files[ist->file_index]->eagain ||
  3857. input_files[ist->file_index]->eof_reached)
  3858. continue;
  3859. nb_requests = av_buffersrc_get_nb_failed_requests(ifilter->filter);
  3860. if (nb_requests > nb_requests_max) {
  3861. nb_requests_max = nb_requests;
  3862. *best_ist = ist;
  3863. }
  3864. }
  3865. if (!*best_ist)
  3866. for (i = 0; i < graph->nb_outputs; i++)
  3867. graph->outputs[i]->ost->unavailable = 1;
  3868. return 0;
  3869. }
  3870. /**
  3871. * Run a single step of transcoding.
  3872. *
  3873. * @return 0 for success, <0 for error
  3874. */
  3875. static int transcode_step(void)
  3876. {
  3877. OutputStream *ost;
  3878. InputStream *ist = NULL;
  3879. int ret;
  3880. ost = choose_output();
  3881. if (!ost) {
  3882. if (got_eagain()) {
  3883. reset_eagain();
  3884. av_usleep(10000);
  3885. return 0;
  3886. }
  3887. av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from, finishing.\n");
  3888. return AVERROR_EOF;
  3889. }
  3890. if (ost->filter && !ost->filter->graph->graph) {
  3891. if (ifilter_has_all_input_formats(ost->filter->graph)) {
  3892. ret = configure_filtergraph(ost->filter->graph);
  3893. if (ret < 0) {
  3894. av_log(NULL, AV_LOG_ERROR, "Error reinitializing filters!\n");
  3895. return ret;
  3896. }
  3897. }
  3898. }
  3899. if (ost->filter && ost->filter->graph->graph) {
  3900. if ((ret = transcode_from_filter(ost->filter->graph, &ist)) < 0)
  3901. return ret;
  3902. if (!ist)
  3903. return 0;
  3904. } else if (ost->filter) {
  3905. int i;
  3906. for (i = 0; i < ost->filter->graph->nb_inputs; i++) {
  3907. InputFilter *ifilter = ost->filter->graph->inputs[i];
  3908. if (!ifilter->ist->got_output && !input_files[ifilter->ist->file_index]->eof_reached) {
  3909. ist = ifilter->ist;
  3910. break;
  3911. }
  3912. }
  3913. if (!ist) {
  3914. ost->inputs_done = 1;
  3915. return 0;
  3916. }
  3917. } else {
  3918. av_assert0(ost->source_index >= 0);
  3919. ist = input_streams[ost->source_index];
  3920. }
  3921. ret = process_input(ist->file_index);
  3922. if (ret == AVERROR(EAGAIN)) {
  3923. if (input_files[ist->file_index]->eagain)
  3924. ost->unavailable = 1;
  3925. return 0;
  3926. }
  3927. if (ret < 0)
  3928. return ret == AVERROR_EOF ? 0 : ret;
  3929. return reap_filters(0);
  3930. }
  3931. /*
  3932. * The following code is the main loop of the file converter
  3933. */
  3934. static int transcode(void)
  3935. {
  3936. int ret, i;
  3937. AVFormatContext *os;
  3938. OutputStream *ost;
  3939. InputStream *ist;
  3940. int64_t timer_start;
  3941. int64_t total_packets_written = 0;
  3942. ret = transcode_init();
  3943. if (ret < 0)
  3944. goto fail;
  3945. if (stdin_interaction) {
  3946. av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
  3947. }
  3948. timer_start = av_gettime_relative();
  3949. #if HAVE_PTHREADS
  3950. if ((ret = init_input_threads()) < 0)
  3951. goto fail;
  3952. #endif
  3953. while (!received_sigterm) {
  3954. int64_t cur_time= av_gettime_relative();
  3955. /* if 'q' pressed, exits */
  3956. if (stdin_interaction)
  3957. if (check_keyboard_interaction(cur_time) < 0)
  3958. break;
  3959. /* check if there's any stream where output is still needed */
  3960. if (!need_output()) {
  3961. av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
  3962. break;
  3963. }
  3964. ret = transcode_step();
  3965. if (ret < 0 && ret != AVERROR_EOF) {
  3966. char errbuf[128];
  3967. av_strerror(ret, errbuf, sizeof(errbuf));
  3968. av_log(NULL, AV_LOG_ERROR, "Error while filtering: %s\n", errbuf);
  3969. break;
  3970. }
  3971. /* dump report by using the output first video and audio streams */
  3972. print_report(0, timer_start, cur_time);
  3973. }
  3974. #if HAVE_PTHREADS
  3975. free_input_threads();
  3976. #endif
  3977. /* at the end of stream, we must flush the decoder buffers */
  3978. for (i = 0; i < nb_input_streams; i++) {
  3979. ist = input_streams[i];
  3980. if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
  3981. process_input_packet(ist, NULL, 0);
  3982. }
  3983. }
  3984. flush_encoders();
  3985. term_exit();
  3986. /* write the trailer if needed and close file */
  3987. for (i = 0; i < nb_output_files; i++) {
  3988. os = output_files[i]->ctx;
  3989. if (!output_files[i]->header_written) {
  3990. av_log(NULL, AV_LOG_ERROR,
  3991. "Nothing was written into output file %d (%s), because "
  3992. "at least one of its streams received no packets.\n",
  3993. i, os->filename);
  3994. continue;
  3995. }
  3996. if ((ret = av_write_trailer(os)) < 0) {
  3997. av_log(NULL, AV_LOG_ERROR, "Error writing trailer of %s: %s\n", os->filename, av_err2str(ret));
  3998. if (exit_on_error)
  3999. exit_program(1);
  4000. }
  4001. }
  4002. /* dump report by using the first video and audio streams */
  4003. print_report(1, timer_start, av_gettime_relative());
  4004. /* close each encoder */
  4005. for (i = 0; i < nb_output_streams; i++) {
  4006. ost = output_streams[i];
  4007. if (ost->encoding_needed) {
  4008. av_freep(&ost->enc_ctx->stats_in);
  4009. }
  4010. total_packets_written += ost->packets_written;
  4011. }
  4012. if (!total_packets_written && (abort_on_flags & ABORT_ON_FLAG_EMPTY_OUTPUT)) {
  4013. av_log(NULL, AV_LOG_FATAL, "Empty output\n");
  4014. exit_program(1);
  4015. }
  4016. /* close each decoder */
  4017. for (i = 0; i < nb_input_streams; i++) {
  4018. ist = input_streams[i];
  4019. if (ist->decoding_needed) {
  4020. avcodec_close(ist->dec_ctx);
  4021. if (ist->hwaccel_uninit)
  4022. ist->hwaccel_uninit(ist->dec_ctx);
  4023. }
  4024. }
  4025. av_buffer_unref(&hw_device_ctx);
  4026. /* finished ! */
  4027. ret = 0;
  4028. fail:
  4029. #if HAVE_PTHREADS
  4030. free_input_threads();
  4031. #endif
  4032. if (output_streams) {
  4033. for (i = 0; i < nb_output_streams; i++) {
  4034. ost = output_streams[i];
  4035. if (ost) {
  4036. if (ost->logfile) {
  4037. if (fclose(ost->logfile))
  4038. av_log(NULL, AV_LOG_ERROR,
  4039. "Error closing logfile, loss of information possible: %s\n",
  4040. av_err2str(AVERROR(errno)));
  4041. ost->logfile = NULL;
  4042. }
  4043. av_freep(&ost->forced_kf_pts);
  4044. av_freep(&ost->apad);
  4045. av_freep(&ost->disposition);
  4046. av_dict_free(&ost->encoder_opts);
  4047. av_dict_free(&ost->sws_dict);
  4048. av_dict_free(&ost->swr_opts);
  4049. av_dict_free(&ost->resample_opts);
  4050. }
  4051. }
  4052. }
  4053. return ret;
  4054. }
  4055. static int64_t getutime(void)
  4056. {
  4057. #if HAVE_GETRUSAGE
  4058. struct rusage rusage;
  4059. getrusage(RUSAGE_SELF, &rusage);
  4060. return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
  4061. #elif HAVE_GETPROCESSTIMES
  4062. HANDLE proc;
  4063. FILETIME c, e, k, u;
  4064. proc = GetCurrentProcess();
  4065. GetProcessTimes(proc, &c, &e, &k, &u);
  4066. return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
  4067. #else
  4068. return av_gettime_relative();
  4069. #endif
  4070. }
  4071. static int64_t getmaxrss(void)
  4072. {
  4073. #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
  4074. struct rusage rusage;
  4075. getrusage(RUSAGE_SELF, &rusage);
  4076. return (int64_t)rusage.ru_maxrss * 1024;
  4077. #elif HAVE_GETPROCESSMEMORYINFO
  4078. HANDLE proc;
  4079. PROCESS_MEMORY_COUNTERS memcounters;
  4080. proc = GetCurrentProcess();
  4081. memcounters.cb = sizeof(memcounters);
  4082. GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
  4083. return memcounters.PeakPagefileUsage;
  4084. #else
  4085. return 0;
  4086. #endif
  4087. }
  4088. static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
  4089. {
  4090. }
  4091. int main(int argc, char **argv)
  4092. {
  4093. int i, ret;
  4094. int64_t ti;
  4095. init_dynload();
  4096. register_exit(ffmpeg_cleanup);
  4097. setvbuf(stderr,NULL,_IONBF,0); /* win32 runtime needs this */
  4098. av_log_set_flags(AV_LOG_SKIP_REPEATED);
  4099. parse_loglevel(argc, argv, options);
  4100. if(argc>1 && !strcmp(argv[1], "-d")){
  4101. run_as_daemon=1;
  4102. av_log_set_callback(log_callback_null);
  4103. argc--;
  4104. argv++;
  4105. }
  4106. avcodec_register_all();
  4107. #if CONFIG_AVDEVICE
  4108. avdevice_register_all();
  4109. #endif
  4110. avfilter_register_all();
  4111. av_register_all();
  4112. avformat_network_init();
  4113. show_banner(argc, argv, options);
  4114. /* parse options and open all input/output files */
  4115. ret = ffmpeg_parse_options(argc, argv);
  4116. if (ret < 0)
  4117. exit_program(1);
  4118. if (nb_output_files <= 0 && nb_input_files == 0) {
  4119. show_usage();
  4120. av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
  4121. exit_program(1);
  4122. }
  4123. /* file converter / grab */
  4124. if (nb_output_files <= 0) {
  4125. av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
  4126. exit_program(1);
  4127. }
  4128. // if (nb_input_files == 0) {
  4129. // av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
  4130. // exit_program(1);
  4131. // }
  4132. for (i = 0; i < nb_output_files; i++) {
  4133. if (strcmp(output_files[i]->ctx->oformat->name, "rtp"))
  4134. want_sdp = 0;
  4135. }
  4136. current_time = ti = getutime();
  4137. if (transcode() < 0)
  4138. exit_program(1);
  4139. ti = getutime() - ti;
  4140. if (do_benchmark) {
  4141. av_log(NULL, AV_LOG_INFO, "bench: utime=%0.3fs\n", ti / 1000000.0);
  4142. }
  4143. av_log(NULL, AV_LOG_DEBUG, "%"PRIu64" frames successfully decoded, %"PRIu64" decoding errors\n",
  4144. decode_error_stat[0], decode_error_stat[1]);
  4145. if ((decode_error_stat[0] + decode_error_stat[1]) * max_error_rate < decode_error_stat[1])
  4146. exit_program(69);
  4147. exit_program(received_nb_signals ? 255 : main_return_code);
  4148. return main_return_code;
  4149. }