ffmpeg.c 108 KB

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