ffmpeg.c 109 KB

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