ffmpeg.c 111 KB

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