ffmpeg.c 144 KB

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