ffmpeg.c 120 KB

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