ffmpeg.c 119 KB

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