ffmpeg.c 113 KB

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