ffmpeg.c 148 KB

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