ffmpeg.c 156 KB

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