ffmpeg.c 123 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467
  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;
  656. if (output_files[ost->file_index]->start_time != AV_NOPTS_VALUE)
  657. pts -= output_files[ost->file_index]->start_time;
  658. for (i = 0; i < nb; i++) {
  659. ost->sync_opts = av_rescale_q(pts, AV_TIME_BASE_Q, enc->time_base);
  660. if (!check_recording_time(ost))
  661. return;
  662. sub->pts = pts;
  663. // start_display_time is required to be 0
  664. sub->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
  665. sub->end_display_time -= sub->start_display_time;
  666. sub->start_display_time = 0;
  667. if (i == 1)
  668. sub->num_rects = 0;
  669. subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
  670. subtitle_out_max_size, sub);
  671. if (subtitle_out_size < 0) {
  672. av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
  673. exit_program(1);
  674. }
  675. av_init_packet(&pkt);
  676. pkt.data = subtitle_out;
  677. pkt.size = subtitle_out_size;
  678. pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
  679. pkt.duration = av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, ost->st->time_base);
  680. if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
  681. /* XXX: the pts correction is handled here. Maybe handling
  682. it in the codec would be better */
  683. if (i == 0)
  684. pkt.pts += 90 * sub->start_display_time;
  685. else
  686. pkt.pts += 90 * sub->end_display_time;
  687. }
  688. subtitle_size += pkt.size;
  689. write_frame(s, &pkt, ost);
  690. }
  691. }
  692. static void do_video_out(AVFormatContext *s,
  693. OutputStream *ost,
  694. AVFrame *in_picture)
  695. {
  696. int ret, format_video_sync;
  697. AVPacket pkt;
  698. AVCodecContext *enc = ost->st->codec;
  699. int nb_frames, i;
  700. double sync_ipts, delta;
  701. double duration = 0;
  702. int frame_size = 0;
  703. InputStream *ist = NULL;
  704. if (ost->source_index >= 0)
  705. ist = input_streams[ost->source_index];
  706. if(ist && ist->st->start_time != AV_NOPTS_VALUE && ist->st->first_dts != AV_NOPTS_VALUE && ost->frame_rate.num)
  707. duration = 1/(av_q2d(ost->frame_rate) * av_q2d(enc->time_base));
  708. sync_ipts = in_picture->pts;
  709. delta = sync_ipts - ost->sync_opts + duration;
  710. /* by default, we output a single frame */
  711. nb_frames = 1;
  712. format_video_sync = video_sync_method;
  713. if (format_video_sync == VSYNC_AUTO) {
  714. format_video_sync = (s->oformat->flags & AVFMT_VARIABLE_FPS) ? ((s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH : VSYNC_VFR) : VSYNC_CFR;
  715. if ( ist
  716. && format_video_sync == VSYNC_CFR
  717. && input_files[ist->file_index]->ctx->nb_streams == 1
  718. && input_files[ist->file_index]->input_ts_offset == 0) {
  719. format_video_sync = VSYNC_VSCFR;
  720. }
  721. if (format_video_sync == VSYNC_CFR && copy_ts) {
  722. format_video_sync = VSYNC_VSCFR;
  723. }
  724. }
  725. switch (format_video_sync) {
  726. case VSYNC_VSCFR:
  727. if (ost->frame_number == 0 && delta - duration >= 0.5) {
  728. av_log(NULL, AV_LOG_DEBUG, "Not duplicating %d initial frames\n", (int)lrintf(delta - duration));
  729. delta = duration;
  730. ost->sync_opts = lrint(sync_ipts);
  731. }
  732. case VSYNC_CFR:
  733. // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
  734. if (delta < -1.1)
  735. nb_frames = 0;
  736. else if (delta > 1.1)
  737. nb_frames = lrintf(delta);
  738. break;
  739. case VSYNC_VFR:
  740. if (delta <= -0.6)
  741. nb_frames = 0;
  742. else if (delta > 0.6)
  743. ost->sync_opts = lrint(sync_ipts);
  744. break;
  745. case VSYNC_DROP:
  746. case VSYNC_PASSTHROUGH:
  747. ost->sync_opts = lrint(sync_ipts);
  748. break;
  749. default:
  750. av_assert0(0);
  751. }
  752. nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
  753. if (nb_frames == 0) {
  754. nb_frames_drop++;
  755. av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");
  756. return;
  757. } else if (nb_frames > 1) {
  758. if (nb_frames > dts_error_threshold * 30) {
  759. av_log(NULL, AV_LOG_ERROR, "%d frame duplication too large, skipping\n", nb_frames - 1);
  760. nb_frames_drop++;
  761. return;
  762. }
  763. nb_frames_dup += nb_frames - 1;
  764. av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);
  765. }
  766. /* duplicates frame if needed */
  767. for (i = 0; i < nb_frames; i++) {
  768. av_init_packet(&pkt);
  769. pkt.data = NULL;
  770. pkt.size = 0;
  771. in_picture->pts = ost->sync_opts;
  772. #if 1
  773. if (!check_recording_time(ost))
  774. #else
  775. if (ost->frame_number >= ost->max_frames)
  776. #endif
  777. return;
  778. if (s->oformat->flags & AVFMT_RAWPICTURE &&
  779. enc->codec->id == AV_CODEC_ID_RAWVIDEO) {
  780. /* raw pictures are written as AVPicture structure to
  781. avoid any copies. We support temporarily the older
  782. method. */
  783. enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
  784. enc->coded_frame->top_field_first = in_picture->top_field_first;
  785. if (enc->coded_frame->interlaced_frame)
  786. enc->field_order = enc->coded_frame->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
  787. else
  788. enc->field_order = AV_FIELD_PROGRESSIVE;
  789. pkt.data = (uint8_t *)in_picture;
  790. pkt.size = sizeof(AVPicture);
  791. pkt.pts = av_rescale_q(in_picture->pts, enc->time_base, ost->st->time_base);
  792. pkt.flags |= AV_PKT_FLAG_KEY;
  793. video_size += pkt.size;
  794. write_frame(s, &pkt, ost);
  795. } else {
  796. int got_packet, forced_keyframe = 0;
  797. double pts_time;
  798. if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME) &&
  799. ost->top_field_first >= 0)
  800. in_picture->top_field_first = !!ost->top_field_first;
  801. if (in_picture->interlaced_frame) {
  802. if (enc->codec->id == AV_CODEC_ID_MJPEG)
  803. enc->field_order = in_picture->top_field_first ? AV_FIELD_TT:AV_FIELD_BB;
  804. else
  805. enc->field_order = in_picture->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
  806. } else
  807. enc->field_order = AV_FIELD_PROGRESSIVE;
  808. in_picture->quality = ost->st->codec->global_quality;
  809. if (!enc->me_threshold)
  810. in_picture->pict_type = 0;
  811. pts_time = in_picture->pts != AV_NOPTS_VALUE ?
  812. in_picture->pts * av_q2d(enc->time_base) : NAN;
  813. if (ost->forced_kf_index < ost->forced_kf_count &&
  814. in_picture->pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
  815. ost->forced_kf_index++;
  816. forced_keyframe = 1;
  817. } else if (ost->forced_keyframes_pexpr) {
  818. double res;
  819. ost->forced_keyframes_expr_const_values[FKF_T] = pts_time;
  820. res = av_expr_eval(ost->forced_keyframes_pexpr,
  821. ost->forced_keyframes_expr_const_values, NULL);
  822. av_dlog(NULL, "force_key_frame: n:%f n_forced:%f prev_forced_n:%f t:%f prev_forced_t:%f -> res:%f\n",
  823. ost->forced_keyframes_expr_const_values[FKF_N],
  824. ost->forced_keyframes_expr_const_values[FKF_N_FORCED],
  825. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N],
  826. ost->forced_keyframes_expr_const_values[FKF_T],
  827. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T],
  828. res);
  829. if (res) {
  830. forced_keyframe = 1;
  831. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] =
  832. ost->forced_keyframes_expr_const_values[FKF_N];
  833. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] =
  834. ost->forced_keyframes_expr_const_values[FKF_T];
  835. ost->forced_keyframes_expr_const_values[FKF_N_FORCED] += 1;
  836. }
  837. ost->forced_keyframes_expr_const_values[FKF_N] += 1;
  838. }
  839. if (forced_keyframe) {
  840. in_picture->pict_type = AV_PICTURE_TYPE_I;
  841. av_log(NULL, AV_LOG_DEBUG, "Forced keyframe at time %f\n", pts_time);
  842. }
  843. update_benchmark(NULL);
  844. ret = avcodec_encode_video2(enc, &pkt, in_picture, &got_packet);
  845. update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
  846. if (ret < 0) {
  847. av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
  848. exit_program(1);
  849. }
  850. if (got_packet) {
  851. if (pkt.pts == AV_NOPTS_VALUE && !(enc->codec->capabilities & CODEC_CAP_DELAY))
  852. pkt.pts = ost->sync_opts;
  853. if (pkt.pts != AV_NOPTS_VALUE)
  854. pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
  855. if (pkt.dts != AV_NOPTS_VALUE)
  856. pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
  857. if (debug_ts) {
  858. av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
  859. "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
  860. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
  861. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
  862. }
  863. frame_size = pkt.size;
  864. video_size += pkt.size;
  865. write_frame(s, &pkt, ost);
  866. av_free_packet(&pkt);
  867. /* if two pass, output log */
  868. if (ost->logfile && enc->stats_out) {
  869. fprintf(ost->logfile, "%s", enc->stats_out);
  870. }
  871. }
  872. }
  873. ost->sync_opts++;
  874. /*
  875. * For video, number of frames in == number of packets out.
  876. * But there may be reordering, so we can't throw away frames on encoder
  877. * flush, we need to limit them here, before they go into encoder.
  878. */
  879. ost->frame_number++;
  880. if (vstats_filename && frame_size)
  881. do_video_stats(ost, frame_size);
  882. }
  883. }
  884. static double psnr(double d)
  885. {
  886. return -10.0 * log(d) / log(10.0);
  887. }
  888. static void do_video_stats(OutputStream *ost, int frame_size)
  889. {
  890. AVCodecContext *enc;
  891. int frame_number;
  892. double ti1, bitrate, avg_bitrate;
  893. /* this is executed just the first time do_video_stats is called */
  894. if (!vstats_file) {
  895. vstats_file = fopen(vstats_filename, "w");
  896. if (!vstats_file) {
  897. perror("fopen");
  898. exit_program(1);
  899. }
  900. }
  901. enc = ost->st->codec;
  902. if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  903. frame_number = ost->st->nb_frames;
  904. fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality / (float)FF_QP2LAMBDA);
  905. if (enc->flags&CODEC_FLAG_PSNR)
  906. fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
  907. fprintf(vstats_file,"f_size= %6d ", frame_size);
  908. /* compute pts value */
  909. ti1 = ost->st->pts.val * av_q2d(enc->time_base);
  910. if (ti1 < 0.01)
  911. ti1 = 0.01;
  912. bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
  913. avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
  914. fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
  915. (double)video_size / 1024, ti1, bitrate, avg_bitrate);
  916. fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
  917. }
  918. }
  919. /**
  920. * Get and encode new output from any of the filtergraphs, without causing
  921. * activity.
  922. *
  923. * @return 0 for success, <0 for severe errors
  924. */
  925. static int reap_filters(void)
  926. {
  927. AVFrame *filtered_frame = NULL;
  928. int i;
  929. int64_t frame_pts;
  930. /* Reap all buffers present in the buffer sinks */
  931. for (i = 0; i < nb_output_streams; i++) {
  932. OutputStream *ost = output_streams[i];
  933. OutputFile *of = output_files[ost->file_index];
  934. int ret = 0;
  935. if (!ost->filter)
  936. continue;
  937. if (!ost->filtered_frame && !(ost->filtered_frame = avcodec_alloc_frame())) {
  938. return AVERROR(ENOMEM);
  939. } else
  940. avcodec_get_frame_defaults(ost->filtered_frame);
  941. filtered_frame = ost->filtered_frame;
  942. while (1) {
  943. ret = av_buffersink_get_frame_flags(ost->filter->filter, filtered_frame,
  944. AV_BUFFERSINK_FLAG_NO_REQUEST);
  945. if (ret < 0) {
  946. if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) {
  947. av_log(NULL, AV_LOG_WARNING,
  948. "Error in av_buffersink_get_frame_flags(): %s\n", av_err2str(ret));
  949. }
  950. break;
  951. }
  952. frame_pts = AV_NOPTS_VALUE;
  953. if (filtered_frame->pts != AV_NOPTS_VALUE) {
  954. int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
  955. filtered_frame->pts = frame_pts = av_rescale_q(filtered_frame->pts,
  956. ost->filter->filter->inputs[0]->time_base,
  957. ost->st->codec->time_base) -
  958. av_rescale_q(start_time,
  959. AV_TIME_BASE_Q,
  960. ost->st->codec->time_base);
  961. }
  962. //if (ost->source_index >= 0)
  963. // *filtered_frame= *input_streams[ost->source_index]->decoded_frame; //for me_threshold
  964. switch (ost->filter->filter->inputs[0]->type) {
  965. case AVMEDIA_TYPE_VIDEO:
  966. filtered_frame->pts = frame_pts;
  967. if (!ost->frame_aspect_ratio.num)
  968. ost->st->codec->sample_aspect_ratio = filtered_frame->sample_aspect_ratio;
  969. do_video_out(of->ctx, ost, filtered_frame);
  970. break;
  971. case AVMEDIA_TYPE_AUDIO:
  972. filtered_frame->pts = frame_pts;
  973. if (!(ost->st->codec->codec->capabilities & CODEC_CAP_PARAM_CHANGE) &&
  974. ost->st->codec->channels != av_frame_get_channels(filtered_frame)) {
  975. av_log(NULL, AV_LOG_ERROR,
  976. "Audio filter graph output is not normalized and encoder does not support parameter changes\n");
  977. break;
  978. }
  979. do_audio_out(of->ctx, ost, filtered_frame);
  980. break;
  981. default:
  982. // TODO support subtitle filters
  983. av_assert0(0);
  984. }
  985. av_frame_unref(filtered_frame);
  986. }
  987. }
  988. return 0;
  989. }
  990. static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
  991. {
  992. char buf[1024];
  993. AVBPrint buf_script;
  994. OutputStream *ost;
  995. AVFormatContext *oc;
  996. int64_t total_size;
  997. AVCodecContext *enc;
  998. int frame_number, vid, i;
  999. double bitrate;
  1000. int64_t pts = INT64_MIN;
  1001. static int64_t last_time = -1;
  1002. static int qp_histogram[52];
  1003. int hours, mins, secs, us;
  1004. if (!print_stats && !is_last_report && !progress_avio)
  1005. return;
  1006. if (!is_last_report) {
  1007. if (last_time == -1) {
  1008. last_time = cur_time;
  1009. return;
  1010. }
  1011. if ((cur_time - last_time) < 500000)
  1012. return;
  1013. last_time = cur_time;
  1014. }
  1015. oc = output_files[0]->ctx;
  1016. total_size = avio_size(oc->pb);
  1017. if (total_size <= 0) // FIXME improve avio_size() so it works with non seekable output too
  1018. total_size = avio_tell(oc->pb);
  1019. buf[0] = '\0';
  1020. vid = 0;
  1021. av_bprint_init(&buf_script, 0, 1);
  1022. for (i = 0; i < nb_output_streams; i++) {
  1023. float q = -1;
  1024. ost = output_streams[i];
  1025. enc = ost->st->codec;
  1026. if (!ost->stream_copy && enc->coded_frame)
  1027. q = enc->coded_frame->quality / (float)FF_QP2LAMBDA;
  1028. if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  1029. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
  1030. av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
  1031. ost->file_index, ost->index, q);
  1032. }
  1033. if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  1034. float fps, t = (cur_time-timer_start) / 1000000.0;
  1035. frame_number = ost->frame_number;
  1036. fps = t > 1 ? frame_number / t : 0;
  1037. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3.*f q=%3.1f ",
  1038. frame_number, fps < 9.95, fps, q);
  1039. av_bprintf(&buf_script, "frame=%d\n", frame_number);
  1040. av_bprintf(&buf_script, "fps=%.1f\n", fps);
  1041. av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
  1042. ost->file_index, ost->index, q);
  1043. if (is_last_report)
  1044. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
  1045. if (qp_hist) {
  1046. int j;
  1047. int qp = lrintf(q);
  1048. if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
  1049. qp_histogram[qp]++;
  1050. for (j = 0; j < 32; j++)
  1051. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log2(qp_histogram[j] + 1)));
  1052. }
  1053. if ((enc->flags&CODEC_FLAG_PSNR) && (enc->coded_frame || is_last_report)) {
  1054. int j;
  1055. double error, error_sum = 0;
  1056. double scale, scale_sum = 0;
  1057. double p;
  1058. char type[3] = { 'Y','U','V' };
  1059. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
  1060. for (j = 0; j < 3; j++) {
  1061. if (is_last_report) {
  1062. error = enc->error[j];
  1063. scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
  1064. } else {
  1065. error = enc->coded_frame->error[j];
  1066. scale = enc->width * enc->height * 255.0 * 255.0;
  1067. }
  1068. if (j)
  1069. scale /= 4;
  1070. error_sum += error;
  1071. scale_sum += scale;
  1072. p = psnr(error / scale);
  1073. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], p);
  1074. av_bprintf(&buf_script, "stream_%d_%d_psnr_%c=%2.2f\n",
  1075. ost->file_index, ost->index, type[j] | 32, p);
  1076. }
  1077. p = psnr(error_sum / scale_sum);
  1078. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
  1079. av_bprintf(&buf_script, "stream_%d_%d_psnr_all=%2.2f\n",
  1080. ost->file_index, ost->index, p);
  1081. }
  1082. vid = 1;
  1083. }
  1084. /* compute min output value */
  1085. if ((is_last_report || !ost->finished) && ost->st->pts.val != AV_NOPTS_VALUE)
  1086. pts = FFMAX(pts, av_rescale_q(ost->st->pts.val,
  1087. ost->st->time_base, AV_TIME_BASE_Q));
  1088. }
  1089. secs = pts / AV_TIME_BASE;
  1090. us = pts % AV_TIME_BASE;
  1091. mins = secs / 60;
  1092. secs %= 60;
  1093. hours = mins / 60;
  1094. mins %= 60;
  1095. bitrate = pts && total_size >= 0 ? total_size * 8 / (pts / 1000.0) : -1;
  1096. if (total_size < 0) snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  1097. "size=N/A time=");
  1098. else snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  1099. "size=%8.0fkB time=", total_size / 1024.0);
  1100. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  1101. "%02d:%02d:%02d.%02d ", hours, mins, secs,
  1102. (100 * us) / AV_TIME_BASE);
  1103. if (bitrate < 0) snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  1104. "bitrate=N/A");
  1105. else snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  1106. "bitrate=%6.1fkbits/s", bitrate);
  1107. if (total_size < 0) av_bprintf(&buf_script, "total_size=N/A\n");
  1108. else av_bprintf(&buf_script, "total_size=%"PRId64"\n", total_size);
  1109. av_bprintf(&buf_script, "out_time_ms=%"PRId64"\n", pts);
  1110. av_bprintf(&buf_script, "out_time=%02d:%02d:%02d.%06d\n",
  1111. hours, mins, secs, us);
  1112. if (nb_frames_dup || nb_frames_drop)
  1113. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
  1114. nb_frames_dup, nb_frames_drop);
  1115. av_bprintf(&buf_script, "dup_frames=%d\n", nb_frames_dup);
  1116. av_bprintf(&buf_script, "drop_frames=%d\n", nb_frames_drop);
  1117. if (print_stats || is_last_report) {
  1118. if (print_stats==1 && AV_LOG_INFO > av_log_get_level()) {
  1119. fprintf(stderr, "%s \r", buf);
  1120. } else
  1121. av_log(NULL, AV_LOG_INFO, "%s \r", buf);
  1122. fflush(stderr);
  1123. }
  1124. if (progress_avio) {
  1125. av_bprintf(&buf_script, "progress=%s\n",
  1126. is_last_report ? "end" : "continue");
  1127. avio_write(progress_avio, buf_script.str,
  1128. FFMIN(buf_script.len, buf_script.size - 1));
  1129. avio_flush(progress_avio);
  1130. av_bprint_finalize(&buf_script, NULL);
  1131. if (is_last_report) {
  1132. avio_close(progress_avio);
  1133. progress_avio = NULL;
  1134. }
  1135. }
  1136. if (is_last_report) {
  1137. int64_t raw= audio_size + video_size + subtitle_size + extra_size;
  1138. av_log(NULL, AV_LOG_INFO, "\n");
  1139. av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB subtitle:%1.0f global headers:%1.0fkB muxing overhead %f%%\n",
  1140. video_size / 1024.0,
  1141. audio_size / 1024.0,
  1142. subtitle_size / 1024.0,
  1143. extra_size / 1024.0,
  1144. 100.0 * (total_size - raw) / raw
  1145. );
  1146. if(video_size + audio_size + subtitle_size + extra_size == 0){
  1147. av_log(NULL, AV_LOG_WARNING, "Output file is empty, nothing was encoded (check -ss / -t / -frames parameters if used)\n");
  1148. }
  1149. }
  1150. }
  1151. static void flush_encoders(void)
  1152. {
  1153. int i, ret;
  1154. for (i = 0; i < nb_output_streams; i++) {
  1155. OutputStream *ost = output_streams[i];
  1156. AVCodecContext *enc = ost->st->codec;
  1157. AVFormatContext *os = output_files[ost->file_index]->ctx;
  1158. int stop_encoding = 0;
  1159. if (!ost->encoding_needed)
  1160. continue;
  1161. if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
  1162. continue;
  1163. if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == AV_CODEC_ID_RAWVIDEO)
  1164. continue;
  1165. for (;;) {
  1166. int (*encode)(AVCodecContext*, AVPacket*, const AVFrame*, int*) = NULL;
  1167. const char *desc;
  1168. int64_t *size;
  1169. switch (ost->st->codec->codec_type) {
  1170. case AVMEDIA_TYPE_AUDIO:
  1171. encode = avcodec_encode_audio2;
  1172. desc = "Audio";
  1173. size = &audio_size;
  1174. break;
  1175. case AVMEDIA_TYPE_VIDEO:
  1176. encode = avcodec_encode_video2;
  1177. desc = "Video";
  1178. size = &video_size;
  1179. break;
  1180. default:
  1181. stop_encoding = 1;
  1182. }
  1183. if (encode) {
  1184. AVPacket pkt;
  1185. int got_packet;
  1186. av_init_packet(&pkt);
  1187. pkt.data = NULL;
  1188. pkt.size = 0;
  1189. update_benchmark(NULL);
  1190. ret = encode(enc, &pkt, NULL, &got_packet);
  1191. update_benchmark("flush %s %d.%d", desc, ost->file_index, ost->index);
  1192. if (ret < 0) {
  1193. av_log(NULL, AV_LOG_FATAL, "%s encoding failed\n", desc);
  1194. exit_program(1);
  1195. }
  1196. *size += pkt.size;
  1197. if (ost->logfile && enc->stats_out) {
  1198. fprintf(ost->logfile, "%s", enc->stats_out);
  1199. }
  1200. if (!got_packet) {
  1201. stop_encoding = 1;
  1202. break;
  1203. }
  1204. if (pkt.pts != AV_NOPTS_VALUE)
  1205. pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
  1206. if (pkt.dts != AV_NOPTS_VALUE)
  1207. pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
  1208. if (pkt.duration > 0)
  1209. pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
  1210. write_frame(os, &pkt, ost);
  1211. if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && vstats_filename) {
  1212. do_video_stats(ost, pkt.size);
  1213. }
  1214. }
  1215. if (stop_encoding)
  1216. break;
  1217. }
  1218. }
  1219. }
  1220. /*
  1221. * Check whether a packet from ist should be written into ost at this time
  1222. */
  1223. static int check_output_constraints(InputStream *ist, OutputStream *ost)
  1224. {
  1225. OutputFile *of = output_files[ost->file_index];
  1226. int ist_index = input_files[ist->file_index]->ist_index + ist->st->index;
  1227. if (ost->source_index != ist_index)
  1228. return 0;
  1229. if (of->start_time != AV_NOPTS_VALUE && ist->pts < of->start_time)
  1230. return 0;
  1231. return 1;
  1232. }
  1233. static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
  1234. {
  1235. OutputFile *of = output_files[ost->file_index];
  1236. InputFile *f = input_files [ist->file_index];
  1237. int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
  1238. int64_t ost_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q, ost->st->time_base);
  1239. int64_t ist_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q, ist->st->time_base);
  1240. AVPicture pict;
  1241. AVPacket opkt;
  1242. av_init_packet(&opkt);
  1243. if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
  1244. !ost->copy_initial_nonkeyframes)
  1245. return;
  1246. if (pkt->pts == AV_NOPTS_VALUE) {
  1247. if (!ost->frame_number && ist->pts < start_time &&
  1248. !ost->copy_prior_start)
  1249. return;
  1250. } else {
  1251. if (!ost->frame_number && pkt->pts < ist_tb_start_time &&
  1252. !ost->copy_prior_start)
  1253. return;
  1254. }
  1255. if (of->recording_time != INT64_MAX &&
  1256. ist->pts >= of->recording_time + start_time) {
  1257. close_output_stream(ost);
  1258. return;
  1259. }
  1260. if (f->recording_time != INT64_MAX) {
  1261. start_time = f->ctx->start_time;
  1262. if (f->start_time != AV_NOPTS_VALUE)
  1263. start_time += f->start_time;
  1264. if (ist->pts >= f->recording_time + start_time) {
  1265. close_output_stream(ost);
  1266. return;
  1267. }
  1268. }
  1269. /* force the input stream PTS */
  1270. if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
  1271. audio_size += pkt->size;
  1272. else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  1273. video_size += pkt->size;
  1274. ost->sync_opts++;
  1275. } else if (ost->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  1276. subtitle_size += pkt->size;
  1277. }
  1278. if (pkt->pts != AV_NOPTS_VALUE)
  1279. opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
  1280. else
  1281. opkt.pts = AV_NOPTS_VALUE;
  1282. if (pkt->dts == AV_NOPTS_VALUE)
  1283. opkt.dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ost->st->time_base);
  1284. else
  1285. opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
  1286. opkt.dts -= ost_tb_start_time;
  1287. if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->dts != AV_NOPTS_VALUE) {
  1288. int duration = av_get_audio_frame_duration(ist->st->codec, pkt->size);
  1289. if(!duration)
  1290. duration = ist->st->codec->frame_size;
  1291. opkt.dts = opkt.pts = av_rescale_delta(ist->st->time_base, pkt->dts,
  1292. (AVRational){1, ist->st->codec->sample_rate}, duration, &ist->filter_in_rescale_delta_last,
  1293. ost->st->time_base) - ost_tb_start_time;
  1294. }
  1295. opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
  1296. opkt.flags = pkt->flags;
  1297. // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
  1298. if ( ost->st->codec->codec_id != AV_CODEC_ID_H264
  1299. && ost->st->codec->codec_id != AV_CODEC_ID_MPEG1VIDEO
  1300. && ost->st->codec->codec_id != AV_CODEC_ID_MPEG2VIDEO
  1301. && ost->st->codec->codec_id != AV_CODEC_ID_VC1
  1302. ) {
  1303. 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)) {
  1304. opkt.buf = av_buffer_create(opkt.data, opkt.size, av_buffer_default_free, NULL, 0);
  1305. if (!opkt.buf)
  1306. exit_program(1);
  1307. }
  1308. } else {
  1309. opkt.data = pkt->data;
  1310. opkt.size = pkt->size;
  1311. }
  1312. if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (of->ctx->oformat->flags & AVFMT_RAWPICTURE)) {
  1313. /* store AVPicture in AVPacket, as expected by the output format */
  1314. avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
  1315. opkt.data = (uint8_t *)&pict;
  1316. opkt.size = sizeof(AVPicture);
  1317. opkt.flags |= AV_PKT_FLAG_KEY;
  1318. }
  1319. write_frame(of->ctx, &opkt, ost);
  1320. ost->st->codec->frame_number++;
  1321. }
  1322. int guess_input_channel_layout(InputStream *ist)
  1323. {
  1324. AVCodecContext *dec = ist->st->codec;
  1325. if (!dec->channel_layout) {
  1326. char layout_name[256];
  1327. if (dec->channels > ist->guess_layout_max)
  1328. return 0;
  1329. dec->channel_layout = av_get_default_channel_layout(dec->channels);
  1330. if (!dec->channel_layout)
  1331. return 0;
  1332. av_get_channel_layout_string(layout_name, sizeof(layout_name),
  1333. dec->channels, dec->channel_layout);
  1334. av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Input Stream "
  1335. "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
  1336. }
  1337. return 1;
  1338. }
  1339. static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
  1340. {
  1341. AVFrame *decoded_frame, *f;
  1342. AVCodecContext *avctx = ist->st->codec;
  1343. int i, ret, err = 0, resample_changed;
  1344. AVRational decoded_frame_tb;
  1345. if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
  1346. return AVERROR(ENOMEM);
  1347. if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
  1348. return AVERROR(ENOMEM);
  1349. decoded_frame = ist->decoded_frame;
  1350. update_benchmark(NULL);
  1351. ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
  1352. update_benchmark("decode_audio %d.%d", ist->file_index, ist->st->index);
  1353. if (ret >= 0 && avctx->sample_rate <= 0) {
  1354. av_log(avctx, AV_LOG_ERROR, "Sample rate %d invalid\n", avctx->sample_rate);
  1355. ret = AVERROR_INVALIDDATA;
  1356. }
  1357. if (*got_output || ret<0 || pkt->size)
  1358. decode_error_stat[ret<0] ++;
  1359. if (!*got_output || ret < 0) {
  1360. if (!pkt->size) {
  1361. for (i = 0; i < ist->nb_filters; i++)
  1362. #if 1
  1363. av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
  1364. #else
  1365. av_buffersrc_add_frame(ist->filters[i]->filter, NULL);
  1366. #endif
  1367. }
  1368. return ret;
  1369. }
  1370. #if 1
  1371. /* increment next_dts to use for the case where the input stream does not
  1372. have timestamps or there are multiple frames in the packet */
  1373. ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
  1374. avctx->sample_rate;
  1375. ist->next_dts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
  1376. avctx->sample_rate;
  1377. #endif
  1378. resample_changed = ist->resample_sample_fmt != decoded_frame->format ||
  1379. ist->resample_channels != avctx->channels ||
  1380. ist->resample_channel_layout != decoded_frame->channel_layout ||
  1381. ist->resample_sample_rate != decoded_frame->sample_rate;
  1382. if (resample_changed) {
  1383. char layout1[64], layout2[64];
  1384. if (!guess_input_channel_layout(ist)) {
  1385. av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
  1386. "layout for Input Stream #%d.%d\n", ist->file_index,
  1387. ist->st->index);
  1388. exit_program(1);
  1389. }
  1390. decoded_frame->channel_layout = avctx->channel_layout;
  1391. av_get_channel_layout_string(layout1, sizeof(layout1), ist->resample_channels,
  1392. ist->resample_channel_layout);
  1393. av_get_channel_layout_string(layout2, sizeof(layout2), avctx->channels,
  1394. decoded_frame->channel_layout);
  1395. av_log(NULL, AV_LOG_INFO,
  1396. "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",
  1397. ist->file_index, ist->st->index,
  1398. ist->resample_sample_rate, av_get_sample_fmt_name(ist->resample_sample_fmt),
  1399. ist->resample_channels, layout1,
  1400. decoded_frame->sample_rate, av_get_sample_fmt_name(decoded_frame->format),
  1401. avctx->channels, layout2);
  1402. ist->resample_sample_fmt = decoded_frame->format;
  1403. ist->resample_sample_rate = decoded_frame->sample_rate;
  1404. ist->resample_channel_layout = decoded_frame->channel_layout;
  1405. ist->resample_channels = avctx->channels;
  1406. for (i = 0; i < nb_filtergraphs; i++)
  1407. if (ist_in_filtergraph(filtergraphs[i], ist)) {
  1408. FilterGraph *fg = filtergraphs[i];
  1409. int j;
  1410. if (configure_filtergraph(fg) < 0) {
  1411. av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
  1412. exit_program(1);
  1413. }
  1414. for (j = 0; j < fg->nb_outputs; j++) {
  1415. OutputStream *ost = fg->outputs[j]->ost;
  1416. if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
  1417. !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
  1418. av_buffersink_set_frame_size(ost->filter->filter,
  1419. ost->st->codec->frame_size);
  1420. }
  1421. }
  1422. }
  1423. /* if the decoder provides a pts, use it instead of the last packet pts.
  1424. the decoder could be delaying output by a packet or more. */
  1425. if (decoded_frame->pts != AV_NOPTS_VALUE) {
  1426. ist->dts = ist->next_dts = ist->pts = ist->next_pts = av_rescale_q(decoded_frame->pts, avctx->time_base, AV_TIME_BASE_Q);
  1427. decoded_frame_tb = avctx->time_base;
  1428. } else if (decoded_frame->pkt_pts != AV_NOPTS_VALUE) {
  1429. decoded_frame->pts = decoded_frame->pkt_pts;
  1430. pkt->pts = AV_NOPTS_VALUE;
  1431. decoded_frame_tb = ist->st->time_base;
  1432. } else if (pkt->pts != AV_NOPTS_VALUE) {
  1433. decoded_frame->pts = pkt->pts;
  1434. pkt->pts = AV_NOPTS_VALUE;
  1435. decoded_frame_tb = ist->st->time_base;
  1436. }else {
  1437. decoded_frame->pts = ist->dts;
  1438. decoded_frame_tb = AV_TIME_BASE_Q;
  1439. }
  1440. if (decoded_frame->pts != AV_NOPTS_VALUE)
  1441. decoded_frame->pts = av_rescale_delta(decoded_frame_tb, decoded_frame->pts,
  1442. (AVRational){1, ist->st->codec->sample_rate}, decoded_frame->nb_samples, &ist->filter_in_rescale_delta_last,
  1443. (AVRational){1, ist->st->codec->sample_rate});
  1444. for (i = 0; i < ist->nb_filters; i++) {
  1445. if (i < ist->nb_filters - 1) {
  1446. f = ist->filter_frame;
  1447. err = av_frame_ref(f, decoded_frame);
  1448. if (err < 0)
  1449. break;
  1450. } else
  1451. f = decoded_frame;
  1452. err = av_buffersrc_add_frame_flags(ist->filters[i]->filter, f,
  1453. AV_BUFFERSRC_FLAG_PUSH);
  1454. if (err == AVERROR_EOF)
  1455. err = 0; /* ignore */
  1456. if (err < 0)
  1457. break;
  1458. }
  1459. decoded_frame->pts = AV_NOPTS_VALUE;
  1460. av_frame_unref(ist->filter_frame);
  1461. av_frame_unref(decoded_frame);
  1462. return err < 0 ? err : ret;
  1463. }
  1464. static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output)
  1465. {
  1466. AVFrame *decoded_frame, *f;
  1467. void *buffer_to_free = NULL;
  1468. int i, ret = 0, err = 0, resample_changed;
  1469. int64_t best_effort_timestamp;
  1470. AVRational *frame_sample_aspect;
  1471. if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
  1472. return AVERROR(ENOMEM);
  1473. if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
  1474. return AVERROR(ENOMEM);
  1475. decoded_frame = ist->decoded_frame;
  1476. pkt->dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ist->st->time_base);
  1477. update_benchmark(NULL);
  1478. ret = avcodec_decode_video2(ist->st->codec,
  1479. decoded_frame, got_output, pkt);
  1480. update_benchmark("decode_video %d.%d", ist->file_index, ist->st->index);
  1481. if (*got_output || ret<0 || pkt->size)
  1482. decode_error_stat[ret<0] ++;
  1483. if (!*got_output || ret < 0) {
  1484. if (!pkt->size) {
  1485. for (i = 0; i < ist->nb_filters; i++)
  1486. #if 1
  1487. av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
  1488. #else
  1489. av_buffersrc_add_frame(ist->filters[i]->filter, NULL);
  1490. #endif
  1491. }
  1492. return ret;
  1493. }
  1494. if(ist->top_field_first>=0)
  1495. decoded_frame->top_field_first = ist->top_field_first;
  1496. best_effort_timestamp= av_frame_get_best_effort_timestamp(decoded_frame);
  1497. if(best_effort_timestamp != AV_NOPTS_VALUE)
  1498. ist->next_pts = ist->pts = av_rescale_q(decoded_frame->pts = best_effort_timestamp, ist->st->time_base, AV_TIME_BASE_Q);
  1499. if (debug_ts) {
  1500. av_log(NULL, AV_LOG_INFO, "decoder -> ist_index:%d type:video "
  1501. "frame_pts:%s frame_pts_time:%s best_effort_ts:%"PRId64" best_effort_ts_time:%s keyframe:%d frame_type:%d \n",
  1502. ist->st->index, av_ts2str(decoded_frame->pts),
  1503. av_ts2timestr(decoded_frame->pts, &ist->st->time_base),
  1504. best_effort_timestamp,
  1505. av_ts2timestr(best_effort_timestamp, &ist->st->time_base),
  1506. decoded_frame->key_frame, decoded_frame->pict_type);
  1507. }
  1508. pkt->size = 0;
  1509. if (ist->st->sample_aspect_ratio.num)
  1510. decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
  1511. resample_changed = ist->resample_width != decoded_frame->width ||
  1512. ist->resample_height != decoded_frame->height ||
  1513. ist->resample_pix_fmt != decoded_frame->format;
  1514. if (resample_changed) {
  1515. av_log(NULL, AV_LOG_INFO,
  1516. "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
  1517. ist->file_index, ist->st->index,
  1518. ist->resample_width, ist->resample_height, av_get_pix_fmt_name(ist->resample_pix_fmt),
  1519. decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
  1520. ist->resample_width = decoded_frame->width;
  1521. ist->resample_height = decoded_frame->height;
  1522. ist->resample_pix_fmt = decoded_frame->format;
  1523. for (i = 0; i < nb_filtergraphs; i++) {
  1524. if (ist_in_filtergraph(filtergraphs[i], ist) && ist->reinit_filters &&
  1525. configure_filtergraph(filtergraphs[i]) < 0) {
  1526. av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
  1527. exit_program(1);
  1528. }
  1529. }
  1530. }
  1531. frame_sample_aspect= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "sample_aspect_ratio");
  1532. for (i = 0; i < ist->nb_filters; i++) {
  1533. if (!frame_sample_aspect->num)
  1534. *frame_sample_aspect = ist->st->sample_aspect_ratio;
  1535. if (i < ist->nb_filters - 1) {
  1536. f = ist->filter_frame;
  1537. err = av_frame_ref(f, decoded_frame);
  1538. if (err < 0)
  1539. break;
  1540. } else
  1541. f = decoded_frame;
  1542. ret = av_buffersrc_add_frame_flags(ist->filters[i]->filter, f, AV_BUFFERSRC_FLAG_PUSH);
  1543. if (ret == AVERROR_EOF) {
  1544. ret = 0; /* ignore */
  1545. } else if (ret < 0) {
  1546. av_log(NULL, AV_LOG_FATAL,
  1547. "Failed to inject frame into filter network: %s\n", av_err2str(ret));
  1548. exit_program(1);
  1549. }
  1550. }
  1551. av_frame_unref(ist->filter_frame);
  1552. av_frame_unref(decoded_frame);
  1553. av_free(buffer_to_free);
  1554. return err < 0 ? err : ret;
  1555. }
  1556. static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
  1557. {
  1558. AVSubtitle subtitle;
  1559. int i, ret = avcodec_decode_subtitle2(ist->st->codec,
  1560. &subtitle, got_output, pkt);
  1561. if (*got_output || ret<0 || pkt->size)
  1562. decode_error_stat[ret<0] ++;
  1563. if (ret < 0 || !*got_output) {
  1564. if (!pkt->size)
  1565. sub2video_flush(ist);
  1566. return ret;
  1567. }
  1568. if (ist->fix_sub_duration) {
  1569. if (ist->prev_sub.got_output) {
  1570. int end = av_rescale(subtitle.pts - ist->prev_sub.subtitle.pts,
  1571. 1000, AV_TIME_BASE);
  1572. if (end < ist->prev_sub.subtitle.end_display_time) {
  1573. av_log(ist->st->codec, AV_LOG_DEBUG,
  1574. "Subtitle duration reduced from %d to %d\n",
  1575. ist->prev_sub.subtitle.end_display_time, end);
  1576. ist->prev_sub.subtitle.end_display_time = end;
  1577. }
  1578. }
  1579. FFSWAP(int, *got_output, ist->prev_sub.got_output);
  1580. FFSWAP(int, ret, ist->prev_sub.ret);
  1581. FFSWAP(AVSubtitle, subtitle, ist->prev_sub.subtitle);
  1582. }
  1583. sub2video_update(ist, &subtitle);
  1584. if (!*got_output || !subtitle.num_rects)
  1585. return ret;
  1586. for (i = 0; i < nb_output_streams; i++) {
  1587. OutputStream *ost = output_streams[i];
  1588. if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
  1589. continue;
  1590. do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle);
  1591. }
  1592. avsubtitle_free(&subtitle);
  1593. return ret;
  1594. }
  1595. /* pkt = NULL means EOF (needed to flush decoder buffers) */
  1596. static int output_packet(InputStream *ist, const AVPacket *pkt)
  1597. {
  1598. int ret = 0, i;
  1599. int got_output = 0;
  1600. AVPacket avpkt;
  1601. if (!ist->saw_first_ts) {
  1602. 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;
  1603. ist->pts = 0;
  1604. if (pkt != NULL && pkt->pts != AV_NOPTS_VALUE && !ist->decoding_needed) {
  1605. ist->dts += av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
  1606. ist->pts = ist->dts; //unused but better to set it to a value thats not totally wrong
  1607. }
  1608. ist->saw_first_ts = 1;
  1609. }
  1610. if (ist->next_dts == AV_NOPTS_VALUE)
  1611. ist->next_dts = ist->dts;
  1612. if (ist->next_pts == AV_NOPTS_VALUE)
  1613. ist->next_pts = ist->pts;
  1614. if (pkt == NULL) {
  1615. /* EOF handling */
  1616. av_init_packet(&avpkt);
  1617. avpkt.data = NULL;
  1618. avpkt.size = 0;
  1619. goto handle_eof;
  1620. } else {
  1621. avpkt = *pkt;
  1622. }
  1623. if (pkt->dts != AV_NOPTS_VALUE) {
  1624. ist->next_dts = ist->dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
  1625. if (ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)
  1626. ist->next_pts = ist->pts = ist->dts;
  1627. }
  1628. // while we have more to decode or while the decoder did output something on EOF
  1629. while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
  1630. int duration;
  1631. handle_eof:
  1632. ist->pts = ist->next_pts;
  1633. ist->dts = ist->next_dts;
  1634. if (avpkt.size && avpkt.size != pkt->size) {
  1635. av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
  1636. "Multiple frames in a packet from stream %d\n", pkt->stream_index);
  1637. ist->showed_multi_packet_warning = 1;
  1638. }
  1639. switch (ist->st->codec->codec_type) {
  1640. case AVMEDIA_TYPE_AUDIO:
  1641. ret = decode_audio (ist, &avpkt, &got_output);
  1642. break;
  1643. case AVMEDIA_TYPE_VIDEO:
  1644. ret = decode_video (ist, &avpkt, &got_output);
  1645. if (avpkt.duration) {
  1646. duration = av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
  1647. } else if(ist->st->codec->time_base.num != 0 && ist->st->codec->time_base.den != 0) {
  1648. int ticks= av_stream_get_parser(ist->st) ? av_stream_get_parser(ist->st)->repeat_pict+1 : ist->st->codec->ticks_per_frame;
  1649. duration = ((int64_t)AV_TIME_BASE *
  1650. ist->st->codec->time_base.num * ticks) /
  1651. ist->st->codec->time_base.den;
  1652. } else
  1653. duration = 0;
  1654. if(ist->dts != AV_NOPTS_VALUE && duration) {
  1655. ist->next_dts += duration;
  1656. }else
  1657. ist->next_dts = AV_NOPTS_VALUE;
  1658. if (got_output)
  1659. ist->next_pts += duration; //FIXME the duration is not correct in some cases
  1660. break;
  1661. case AVMEDIA_TYPE_SUBTITLE:
  1662. ret = transcode_subtitles(ist, &avpkt, &got_output);
  1663. break;
  1664. default:
  1665. return -1;
  1666. }
  1667. if (ret < 0)
  1668. return ret;
  1669. avpkt.dts=
  1670. avpkt.pts= AV_NOPTS_VALUE;
  1671. // touch data and size only if not EOF
  1672. if (pkt) {
  1673. if(ist->st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
  1674. ret = avpkt.size;
  1675. avpkt.data += ret;
  1676. avpkt.size -= ret;
  1677. }
  1678. if (!got_output) {
  1679. continue;
  1680. }
  1681. }
  1682. /* handle stream copy */
  1683. if (!ist->decoding_needed) {
  1684. ist->dts = ist->next_dts;
  1685. switch (ist->st->codec->codec_type) {
  1686. case AVMEDIA_TYPE_AUDIO:
  1687. ist->next_dts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
  1688. ist->st->codec->sample_rate;
  1689. break;
  1690. case AVMEDIA_TYPE_VIDEO:
  1691. if (ist->framerate.num) {
  1692. // TODO: Remove work-around for c99-to-c89 issue 7
  1693. AVRational time_base_q = AV_TIME_BASE_Q;
  1694. int64_t next_dts = av_rescale_q(ist->next_dts, time_base_q, av_inv_q(ist->framerate));
  1695. ist->next_dts = av_rescale_q(next_dts + 1, av_inv_q(ist->framerate), time_base_q);
  1696. } else if (pkt->duration) {
  1697. ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
  1698. } else if(ist->st->codec->time_base.num != 0) {
  1699. int ticks= av_stream_get_parser(ist->st) ? av_stream_get_parser(ist->st)->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
  1700. ist->next_dts += ((int64_t)AV_TIME_BASE *
  1701. ist->st->codec->time_base.num * ticks) /
  1702. ist->st->codec->time_base.den;
  1703. }
  1704. break;
  1705. }
  1706. ist->pts = ist->dts;
  1707. ist->next_pts = ist->next_dts;
  1708. }
  1709. for (i = 0; pkt && i < nb_output_streams; i++) {
  1710. OutputStream *ost = output_streams[i];
  1711. if (!check_output_constraints(ist, ost) || ost->encoding_needed)
  1712. continue;
  1713. do_streamcopy(ist, ost, pkt);
  1714. }
  1715. return 0;
  1716. }
  1717. static void print_sdp(void)
  1718. {
  1719. char sdp[16384];
  1720. int i;
  1721. AVFormatContext **avc = av_malloc(sizeof(*avc) * nb_output_files);
  1722. if (!avc)
  1723. exit_program(1);
  1724. for (i = 0; i < nb_output_files; i++)
  1725. avc[i] = output_files[i]->ctx;
  1726. av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
  1727. printf("SDP:\n%s\n", sdp);
  1728. fflush(stdout);
  1729. av_freep(&avc);
  1730. }
  1731. static int init_input_stream(int ist_index, char *error, int error_len)
  1732. {
  1733. int ret;
  1734. InputStream *ist = input_streams[ist_index];
  1735. if (ist->decoding_needed) {
  1736. AVCodec *codec = ist->dec;
  1737. if (!codec) {
  1738. snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
  1739. avcodec_get_name(ist->st->codec->codec_id), ist->file_index, ist->st->index);
  1740. return AVERROR(EINVAL);
  1741. }
  1742. av_opt_set_int(ist->st->codec, "refcounted_frames", 1, 0);
  1743. if (!av_dict_get(ist->opts, "threads", NULL, 0))
  1744. av_dict_set(&ist->opts, "threads", "auto", 0);
  1745. if ((ret = avcodec_open2(ist->st->codec, codec, &ist->opts)) < 0) {
  1746. char errbuf[128];
  1747. if (ret == AVERROR_EXPERIMENTAL)
  1748. abort_codec_experimental(codec, 0);
  1749. av_strerror(ret, errbuf, sizeof(errbuf));
  1750. snprintf(error, error_len,
  1751. "Error while opening decoder for input stream "
  1752. "#%d:%d : %s",
  1753. ist->file_index, ist->st->index, errbuf);
  1754. return ret;
  1755. }
  1756. assert_avoptions(ist->opts);
  1757. }
  1758. ist->next_pts = AV_NOPTS_VALUE;
  1759. ist->next_dts = AV_NOPTS_VALUE;
  1760. ist->is_start = 1;
  1761. return 0;
  1762. }
  1763. static InputStream *get_input_stream(OutputStream *ost)
  1764. {
  1765. if (ost->source_index >= 0)
  1766. return input_streams[ost->source_index];
  1767. return NULL;
  1768. }
  1769. static int compare_int64(const void *a, const void *b)
  1770. {
  1771. int64_t va = *(int64_t *)a, vb = *(int64_t *)b;
  1772. return va < vb ? -1 : va > vb ? +1 : 0;
  1773. }
  1774. static void parse_forced_key_frames(char *kf, OutputStream *ost,
  1775. AVCodecContext *avctx)
  1776. {
  1777. char *p;
  1778. int n = 1, i, size, index = 0;
  1779. int64_t t, *pts;
  1780. for (p = kf; *p; p++)
  1781. if (*p == ',')
  1782. n++;
  1783. size = n;
  1784. pts = av_malloc(sizeof(*pts) * size);
  1785. if (!pts) {
  1786. av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
  1787. exit_program(1);
  1788. }
  1789. p = kf;
  1790. for (i = 0; i < n; i++) {
  1791. char *next = strchr(p, ',');
  1792. if (next)
  1793. *next++ = 0;
  1794. if (!memcmp(p, "chapters", 8)) {
  1795. AVFormatContext *avf = output_files[ost->file_index]->ctx;
  1796. int j;
  1797. if (avf->nb_chapters > INT_MAX - size ||
  1798. !(pts = av_realloc_f(pts, size += avf->nb_chapters - 1,
  1799. sizeof(*pts)))) {
  1800. av_log(NULL, AV_LOG_FATAL,
  1801. "Could not allocate forced key frames array.\n");
  1802. exit_program(1);
  1803. }
  1804. t = p[8] ? parse_time_or_die("force_key_frames", p + 8, 1) : 0;
  1805. t = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
  1806. for (j = 0; j < avf->nb_chapters; j++) {
  1807. AVChapter *c = avf->chapters[j];
  1808. av_assert1(index < size);
  1809. pts[index++] = av_rescale_q(c->start, c->time_base,
  1810. avctx->time_base) + t;
  1811. }
  1812. } else {
  1813. t = parse_time_or_die("force_key_frames", p, 1);
  1814. av_assert1(index < size);
  1815. pts[index++] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
  1816. }
  1817. p = next;
  1818. }
  1819. av_assert0(index == size);
  1820. qsort(pts, size, sizeof(*pts), compare_int64);
  1821. ost->forced_kf_count = size;
  1822. ost->forced_kf_pts = pts;
  1823. }
  1824. static void report_new_stream(int input_index, AVPacket *pkt)
  1825. {
  1826. InputFile *file = input_files[input_index];
  1827. AVStream *st = file->ctx->streams[pkt->stream_index];
  1828. if (pkt->stream_index < file->nb_streams_warn)
  1829. return;
  1830. av_log(file->ctx, AV_LOG_WARNING,
  1831. "New %s stream %d:%d at pos:%"PRId64" and DTS:%ss\n",
  1832. av_get_media_type_string(st->codec->codec_type),
  1833. input_index, pkt->stream_index,
  1834. pkt->pos, av_ts2timestr(pkt->dts, &st->time_base));
  1835. file->nb_streams_warn = pkt->stream_index + 1;
  1836. }
  1837. static int transcode_init(void)
  1838. {
  1839. int ret = 0, i, j, k;
  1840. AVFormatContext *oc;
  1841. AVCodecContext *codec;
  1842. OutputStream *ost;
  1843. InputStream *ist;
  1844. char error[1024] = {0};
  1845. int want_sdp = 1;
  1846. for (i = 0; i < nb_filtergraphs; i++) {
  1847. FilterGraph *fg = filtergraphs[i];
  1848. for (j = 0; j < fg->nb_outputs; j++) {
  1849. OutputFilter *ofilter = fg->outputs[j];
  1850. if (!ofilter->ost || ofilter->ost->source_index >= 0)
  1851. continue;
  1852. if (fg->nb_inputs != 1)
  1853. continue;
  1854. for (k = nb_input_streams-1; k >= 0 ; k--)
  1855. if (fg->inputs[0]->ist == input_streams[k])
  1856. break;
  1857. ofilter->ost->source_index = k;
  1858. }
  1859. }
  1860. /* init framerate emulation */
  1861. for (i = 0; i < nb_input_files; i++) {
  1862. InputFile *ifile = input_files[i];
  1863. if (ifile->rate_emu)
  1864. for (j = 0; j < ifile->nb_streams; j++)
  1865. input_streams[j + ifile->ist_index]->start = av_gettime();
  1866. }
  1867. /* output stream init */
  1868. for (i = 0; i < nb_output_files; i++) {
  1869. oc = output_files[i]->ctx;
  1870. if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
  1871. av_dump_format(oc, i, oc->filename, 1);
  1872. av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
  1873. return AVERROR(EINVAL);
  1874. }
  1875. }
  1876. /* init complex filtergraphs */
  1877. for (i = 0; i < nb_filtergraphs; i++)
  1878. if ((ret = avfilter_graph_config(filtergraphs[i]->graph, NULL)) < 0)
  1879. return ret;
  1880. /* for each output stream, we compute the right encoding parameters */
  1881. for (i = 0; i < nb_output_streams; i++) {
  1882. AVCodecContext *icodec = NULL;
  1883. ost = output_streams[i];
  1884. oc = output_files[ost->file_index]->ctx;
  1885. ist = get_input_stream(ost);
  1886. if (ost->attachment_filename)
  1887. continue;
  1888. codec = ost->st->codec;
  1889. if (ist) {
  1890. icodec = ist->st->codec;
  1891. ost->st->disposition = ist->st->disposition;
  1892. codec->bits_per_raw_sample = icodec->bits_per_raw_sample;
  1893. codec->chroma_sample_location = icodec->chroma_sample_location;
  1894. } else {
  1895. for (j=0; j<oc->nb_streams; j++) {
  1896. AVStream *st = oc->streams[j];
  1897. if (st != ost->st && st->codec->codec_type == codec->codec_type)
  1898. break;
  1899. }
  1900. if (j == oc->nb_streams)
  1901. if (codec->codec_type == AVMEDIA_TYPE_AUDIO || codec->codec_type == AVMEDIA_TYPE_VIDEO)
  1902. ost->st->disposition = AV_DISPOSITION_DEFAULT;
  1903. }
  1904. if (ost->stream_copy) {
  1905. AVRational sar;
  1906. uint64_t extra_size;
  1907. av_assert0(ist && !ost->filter);
  1908. extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
  1909. if (extra_size > INT_MAX) {
  1910. return AVERROR(EINVAL);
  1911. }
  1912. /* if stream_copy is selected, no need to decode or encode */
  1913. codec->codec_id = icodec->codec_id;
  1914. codec->codec_type = icodec->codec_type;
  1915. if (!codec->codec_tag) {
  1916. unsigned int codec_tag;
  1917. if (!oc->oformat->codec_tag ||
  1918. av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
  1919. !av_codec_get_tag2(oc->oformat->codec_tag, icodec->codec_id, &codec_tag))
  1920. codec->codec_tag = icodec->codec_tag;
  1921. }
  1922. codec->bit_rate = icodec->bit_rate;
  1923. codec->rc_max_rate = icodec->rc_max_rate;
  1924. codec->rc_buffer_size = icodec->rc_buffer_size;
  1925. codec->field_order = icodec->field_order;
  1926. codec->extradata = av_mallocz(extra_size);
  1927. if (!codec->extradata) {
  1928. return AVERROR(ENOMEM);
  1929. }
  1930. memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
  1931. codec->extradata_size= icodec->extradata_size;
  1932. codec->bits_per_coded_sample = icodec->bits_per_coded_sample;
  1933. codec->time_base = ist->st->time_base;
  1934. /*
  1935. * Avi is a special case here because it supports variable fps but
  1936. * having the fps and timebase differe significantly adds quite some
  1937. * overhead
  1938. */
  1939. if(!strcmp(oc->oformat->name, "avi")) {
  1940. if ( copy_tb<0 && av_q2d(ist->st->r_frame_rate) >= av_q2d(ist->st->avg_frame_rate)
  1941. && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(ist->st->time_base)
  1942. && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(icodec->time_base)
  1943. && av_q2d(ist->st->time_base) < 1.0/500 && av_q2d(icodec->time_base) < 1.0/500
  1944. || copy_tb==2){
  1945. codec->time_base.num = ist->st->r_frame_rate.den;
  1946. codec->time_base.den = 2*ist->st->r_frame_rate.num;
  1947. codec->ticks_per_frame = 2;
  1948. } else if ( copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > 2*av_q2d(ist->st->time_base)
  1949. && av_q2d(ist->st->time_base) < 1.0/500
  1950. || copy_tb==0){
  1951. codec->time_base = icodec->time_base;
  1952. codec->time_base.num *= icodec->ticks_per_frame;
  1953. codec->time_base.den *= 2;
  1954. codec->ticks_per_frame = 2;
  1955. }
  1956. } else if(!(oc->oformat->flags & AVFMT_VARIABLE_FPS)
  1957. && strcmp(oc->oformat->name, "mov") && strcmp(oc->oformat->name, "mp4") && strcmp(oc->oformat->name, "3gp")
  1958. && strcmp(oc->oformat->name, "3g2") && strcmp(oc->oformat->name, "psp") && strcmp(oc->oformat->name, "ipod")
  1959. && strcmp(oc->oformat->name, "f4v")
  1960. ) {
  1961. if( copy_tb<0 && icodec->time_base.den
  1962. && av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base)
  1963. && av_q2d(ist->st->time_base) < 1.0/500
  1964. || copy_tb==0){
  1965. codec->time_base = icodec->time_base;
  1966. codec->time_base.num *= icodec->ticks_per_frame;
  1967. }
  1968. }
  1969. if ( codec->codec_tag == AV_RL32("tmcd")
  1970. && icodec->time_base.num < icodec->time_base.den
  1971. && icodec->time_base.num > 0
  1972. && 121LL*icodec->time_base.num > icodec->time_base.den) {
  1973. codec->time_base = icodec->time_base;
  1974. }
  1975. if (ist && !ost->frame_rate.num)
  1976. ost->frame_rate = ist->framerate;
  1977. if(ost->frame_rate.num)
  1978. codec->time_base = av_inv_q(ost->frame_rate);
  1979. av_reduce(&codec->time_base.num, &codec->time_base.den,
  1980. codec->time_base.num, codec->time_base.den, INT_MAX);
  1981. switch (codec->codec_type) {
  1982. case AVMEDIA_TYPE_AUDIO:
  1983. if (audio_volume != 256) {
  1984. av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
  1985. exit_program(1);
  1986. }
  1987. codec->channel_layout = icodec->channel_layout;
  1988. codec->sample_rate = icodec->sample_rate;
  1989. codec->channels = icodec->channels;
  1990. codec->frame_size = icodec->frame_size;
  1991. codec->audio_service_type = icodec->audio_service_type;
  1992. codec->block_align = icodec->block_align;
  1993. if((codec->block_align == 1 || codec->block_align == 1152 || codec->block_align == 576) && codec->codec_id == AV_CODEC_ID_MP3)
  1994. codec->block_align= 0;
  1995. if(codec->codec_id == AV_CODEC_ID_AC3)
  1996. codec->block_align= 0;
  1997. break;
  1998. case AVMEDIA_TYPE_VIDEO:
  1999. codec->pix_fmt = icodec->pix_fmt;
  2000. codec->width = icodec->width;
  2001. codec->height = icodec->height;
  2002. codec->has_b_frames = icodec->has_b_frames;
  2003. if (ost->frame_aspect_ratio.num) { // overridden by the -aspect cli option
  2004. sar =
  2005. av_mul_q(ost->frame_aspect_ratio,
  2006. (AVRational){ codec->height, codec->width });
  2007. av_log(NULL, AV_LOG_WARNING, "Overriding aspect ratio "
  2008. "with stream copy may produce invalid files\n");
  2009. }
  2010. else if (ist->st->sample_aspect_ratio.num)
  2011. sar = ist->st->sample_aspect_ratio;
  2012. else
  2013. sar = icodec->sample_aspect_ratio;
  2014. ost->st->sample_aspect_ratio = codec->sample_aspect_ratio = sar;
  2015. ost->st->avg_frame_rate = ist->st->avg_frame_rate;
  2016. break;
  2017. case AVMEDIA_TYPE_SUBTITLE:
  2018. codec->width = icodec->width;
  2019. codec->height = icodec->height;
  2020. break;
  2021. case AVMEDIA_TYPE_DATA:
  2022. case AVMEDIA_TYPE_ATTACHMENT:
  2023. break;
  2024. default:
  2025. abort();
  2026. }
  2027. } else {
  2028. if (!ost->enc)
  2029. ost->enc = avcodec_find_encoder(codec->codec_id);
  2030. if (!ost->enc) {
  2031. /* should only happen when a default codec is not present. */
  2032. snprintf(error, sizeof(error), "Encoder (codec %s) not found for output stream #%d:%d",
  2033. avcodec_get_name(ost->st->codec->codec_id), ost->file_index, ost->index);
  2034. ret = AVERROR(EINVAL);
  2035. goto dump_format;
  2036. }
  2037. if (ist)
  2038. ist->decoding_needed++;
  2039. ost->encoding_needed = 1;
  2040. if (!ost->filter &&
  2041. (codec->codec_type == AVMEDIA_TYPE_VIDEO ||
  2042. codec->codec_type == AVMEDIA_TYPE_AUDIO)) {
  2043. FilterGraph *fg;
  2044. fg = init_simple_filtergraph(ist, ost);
  2045. if (configure_filtergraph(fg)) {
  2046. av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
  2047. exit_program(1);
  2048. }
  2049. }
  2050. if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  2051. if (ost->filter && !ost->frame_rate.num)
  2052. ost->frame_rate = av_buffersink_get_frame_rate(ost->filter->filter);
  2053. if (ist && !ost->frame_rate.num)
  2054. ost->frame_rate = ist->framerate;
  2055. if (ist && !ost->frame_rate.num)
  2056. ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational){25, 1};
  2057. // ost->frame_rate = ist->st->avg_frame_rate.num ? ist->st->avg_frame_rate : (AVRational){25, 1};
  2058. if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
  2059. int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
  2060. ost->frame_rate = ost->enc->supported_framerates[idx];
  2061. }
  2062. }
  2063. switch (codec->codec_type) {
  2064. case AVMEDIA_TYPE_AUDIO:
  2065. codec->sample_fmt = ost->filter->filter->inputs[0]->format;
  2066. codec->sample_rate = ost->filter->filter->inputs[0]->sample_rate;
  2067. codec->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
  2068. codec->channels = avfilter_link_get_channels(ost->filter->filter->inputs[0]);
  2069. codec->time_base = (AVRational){ 1, codec->sample_rate };
  2070. break;
  2071. case AVMEDIA_TYPE_VIDEO:
  2072. codec->time_base = av_inv_q(ost->frame_rate);
  2073. if (ost->filter && !(codec->time_base.num && codec->time_base.den))
  2074. codec->time_base = ost->filter->filter->inputs[0]->time_base;
  2075. if ( av_q2d(codec->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH
  2076. && (video_sync_method == VSYNC_CFR || video_sync_method == VSYNC_VSCFR || (video_sync_method == VSYNC_AUTO && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
  2077. av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"
  2078. "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
  2079. }
  2080. for (j = 0; j < ost->forced_kf_count; j++)
  2081. ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
  2082. AV_TIME_BASE_Q,
  2083. codec->time_base);
  2084. codec->width = ost->filter->filter->inputs[0]->w;
  2085. codec->height = ost->filter->filter->inputs[0]->h;
  2086. codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
  2087. ost->frame_aspect_ratio.num ? // overridden by the -aspect cli option
  2088. av_mul_q(ost->frame_aspect_ratio, (AVRational){ codec->height, codec->width }) :
  2089. ost->filter->filter->inputs[0]->sample_aspect_ratio;
  2090. if (!strncmp(ost->enc->name, "libx264", 7) &&
  2091. codec->pix_fmt == AV_PIX_FMT_NONE &&
  2092. ost->filter->filter->inputs[0]->format != AV_PIX_FMT_YUV420P)
  2093. av_log(NULL, AV_LOG_WARNING,
  2094. "No pixel format specified, %s for H.264 encoding chosen.\n"
  2095. "Use -pix_fmt yuv420p for compatibility with outdated media players.\n",
  2096. av_get_pix_fmt_name(ost->filter->filter->inputs[0]->format));
  2097. if (!strncmp(ost->enc->name, "mpeg2video", 10) &&
  2098. codec->pix_fmt == AV_PIX_FMT_NONE &&
  2099. ost->filter->filter->inputs[0]->format != AV_PIX_FMT_YUV420P)
  2100. av_log(NULL, AV_LOG_WARNING,
  2101. "No pixel format specified, %s for MPEG-2 encoding chosen.\n"
  2102. "Use -pix_fmt yuv420p for compatibility with outdated media players.\n",
  2103. av_get_pix_fmt_name(ost->filter->filter->inputs[0]->format));
  2104. codec->pix_fmt = ost->filter->filter->inputs[0]->format;
  2105. if (!icodec ||
  2106. codec->width != icodec->width ||
  2107. codec->height != icodec->height ||
  2108. codec->pix_fmt != icodec->pix_fmt) {
  2109. codec->bits_per_raw_sample = frame_bits_per_raw_sample;
  2110. }
  2111. if (ost->forced_keyframes) {
  2112. if (!strncmp(ost->forced_keyframes, "expr:", 5)) {
  2113. ret = av_expr_parse(&ost->forced_keyframes_pexpr, ost->forced_keyframes+5,
  2114. forced_keyframes_const_names, NULL, NULL, NULL, NULL, 0, NULL);
  2115. if (ret < 0) {
  2116. av_log(NULL, AV_LOG_ERROR,
  2117. "Invalid force_key_frames expression '%s'\n", ost->forced_keyframes+5);
  2118. return ret;
  2119. }
  2120. ost->forced_keyframes_expr_const_values[FKF_N] = 0;
  2121. ost->forced_keyframes_expr_const_values[FKF_N_FORCED] = 0;
  2122. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] = NAN;
  2123. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] = NAN;
  2124. } else {
  2125. parse_forced_key_frames(ost->forced_keyframes, ost, ost->st->codec);
  2126. }
  2127. }
  2128. break;
  2129. case AVMEDIA_TYPE_SUBTITLE:
  2130. codec->time_base = (AVRational){1, 1000};
  2131. if (!codec->width) {
  2132. codec->width = input_streams[ost->source_index]->st->codec->width;
  2133. codec->height = input_streams[ost->source_index]->st->codec->height;
  2134. }
  2135. break;
  2136. default:
  2137. abort();
  2138. break;
  2139. }
  2140. /* two pass mode */
  2141. if (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2)) {
  2142. char logfilename[1024];
  2143. FILE *f;
  2144. snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
  2145. ost->logfile_prefix ? ost->logfile_prefix :
  2146. DEFAULT_PASS_LOGFILENAME_PREFIX,
  2147. i);
  2148. if (!strcmp(ost->enc->name, "libx264")) {
  2149. av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
  2150. } else {
  2151. if (codec->flags & CODEC_FLAG_PASS2) {
  2152. char *logbuffer;
  2153. size_t logbuffer_size;
  2154. if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
  2155. av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
  2156. logfilename);
  2157. exit_program(1);
  2158. }
  2159. codec->stats_in = logbuffer;
  2160. }
  2161. if (codec->flags & CODEC_FLAG_PASS1) {
  2162. f = fopen(logfilename, "wb");
  2163. if (!f) {
  2164. av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
  2165. logfilename, strerror(errno));
  2166. exit_program(1);
  2167. }
  2168. ost->logfile = f;
  2169. }
  2170. }
  2171. }
  2172. }
  2173. }
  2174. /* open each encoder */
  2175. for (i = 0; i < nb_output_streams; i++) {
  2176. ost = output_streams[i];
  2177. if (ost->encoding_needed) {
  2178. AVCodec *codec = ost->enc;
  2179. AVCodecContext *dec = NULL;
  2180. if ((ist = get_input_stream(ost)))
  2181. dec = ist->st->codec;
  2182. if (dec && dec->subtitle_header) {
  2183. /* ASS code assumes this buffer is null terminated so add extra byte. */
  2184. ost->st->codec->subtitle_header = av_mallocz(dec->subtitle_header_size + 1);
  2185. if (!ost->st->codec->subtitle_header) {
  2186. ret = AVERROR(ENOMEM);
  2187. goto dump_format;
  2188. }
  2189. memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
  2190. ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
  2191. }
  2192. if (!av_dict_get(ost->opts, "threads", NULL, 0))
  2193. av_dict_set(&ost->opts, "threads", "auto", 0);
  2194. if ((ret = avcodec_open2(ost->st->codec, codec, &ost->opts)) < 0) {
  2195. if (ret == AVERROR_EXPERIMENTAL)
  2196. abort_codec_experimental(codec, 1);
  2197. snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
  2198. ost->file_index, ost->index);
  2199. goto dump_format;
  2200. }
  2201. if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
  2202. !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
  2203. av_buffersink_set_frame_size(ost->filter->filter,
  2204. ost->st->codec->frame_size);
  2205. assert_avoptions(ost->opts);
  2206. if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
  2207. av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
  2208. " It takes bits/s as argument, not kbits/s\n");
  2209. extra_size += ost->st->codec->extradata_size;
  2210. if (ost->st->codec->me_threshold)
  2211. input_streams[ost->source_index]->st->codec->debug |= FF_DEBUG_MV;
  2212. } else {
  2213. av_opt_set_dict(ost->st->codec, &ost->opts);
  2214. }
  2215. }
  2216. /* init input streams */
  2217. for (i = 0; i < nb_input_streams; i++)
  2218. if ((ret = init_input_stream(i, error, sizeof(error))) < 0) {
  2219. for (i = 0; i < nb_output_streams; i++) {
  2220. ost = output_streams[i];
  2221. avcodec_close(ost->st->codec);
  2222. }
  2223. goto dump_format;
  2224. }
  2225. /* discard unused programs */
  2226. for (i = 0; i < nb_input_files; i++) {
  2227. InputFile *ifile = input_files[i];
  2228. for (j = 0; j < ifile->ctx->nb_programs; j++) {
  2229. AVProgram *p = ifile->ctx->programs[j];
  2230. int discard = AVDISCARD_ALL;
  2231. for (k = 0; k < p->nb_stream_indexes; k++)
  2232. if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
  2233. discard = AVDISCARD_DEFAULT;
  2234. break;
  2235. }
  2236. p->discard = discard;
  2237. }
  2238. }
  2239. /* open files and write file headers */
  2240. for (i = 0; i < nb_output_files; i++) {
  2241. oc = output_files[i]->ctx;
  2242. oc->interrupt_callback = int_cb;
  2243. if ((ret = avformat_write_header(oc, &output_files[i]->opts)) < 0) {
  2244. char errbuf[128];
  2245. av_strerror(ret, errbuf, sizeof(errbuf));
  2246. snprintf(error, sizeof(error),
  2247. "Could not write header for output file #%d "
  2248. "(incorrect codec parameters ?): %s",
  2249. i, errbuf);
  2250. ret = AVERROR(EINVAL);
  2251. goto dump_format;
  2252. }
  2253. // assert_avoptions(output_files[i]->opts);
  2254. if (strcmp(oc->oformat->name, "rtp")) {
  2255. want_sdp = 0;
  2256. }
  2257. }
  2258. dump_format:
  2259. /* dump the file output parameters - cannot be done before in case
  2260. of stream copy */
  2261. for (i = 0; i < nb_output_files; i++) {
  2262. av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
  2263. }
  2264. /* dump the stream mapping */
  2265. av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
  2266. for (i = 0; i < nb_input_streams; i++) {
  2267. ist = input_streams[i];
  2268. for (j = 0; j < ist->nb_filters; j++) {
  2269. if (ist->filters[j]->graph->graph_desc) {
  2270. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
  2271. ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
  2272. ist->filters[j]->name);
  2273. if (nb_filtergraphs > 1)
  2274. av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
  2275. av_log(NULL, AV_LOG_INFO, "\n");
  2276. }
  2277. }
  2278. }
  2279. for (i = 0; i < nb_output_streams; i++) {
  2280. ost = output_streams[i];
  2281. if (ost->attachment_filename) {
  2282. /* an attached file */
  2283. av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
  2284. ost->attachment_filename, ost->file_index, ost->index);
  2285. continue;
  2286. }
  2287. if (ost->filter && ost->filter->graph->graph_desc) {
  2288. /* output from a complex graph */
  2289. av_log(NULL, AV_LOG_INFO, " %s", ost->filter->name);
  2290. if (nb_filtergraphs > 1)
  2291. av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
  2292. av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
  2293. ost->index, ost->enc ? ost->enc->name : "?");
  2294. continue;
  2295. }
  2296. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
  2297. input_streams[ost->source_index]->file_index,
  2298. input_streams[ost->source_index]->st->index,
  2299. ost->file_index,
  2300. ost->index);
  2301. if (ost->sync_ist != input_streams[ost->source_index])
  2302. av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
  2303. ost->sync_ist->file_index,
  2304. ost->sync_ist->st->index);
  2305. if (ost->stream_copy)
  2306. av_log(NULL, AV_LOG_INFO, " (copy)");
  2307. else
  2308. av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index]->dec ?
  2309. input_streams[ost->source_index]->dec->name : "?",
  2310. ost->enc ? ost->enc->name : "?");
  2311. av_log(NULL, AV_LOG_INFO, "\n");
  2312. }
  2313. if (ret) {
  2314. av_log(NULL, AV_LOG_ERROR, "%s\n", error);
  2315. return ret;
  2316. }
  2317. if (want_sdp) {
  2318. print_sdp();
  2319. }
  2320. return 0;
  2321. }
  2322. /* Return 1 if there remain streams where more output is wanted, 0 otherwise. */
  2323. static int need_output(void)
  2324. {
  2325. int i;
  2326. for (i = 0; i < nb_output_streams; i++) {
  2327. OutputStream *ost = output_streams[i];
  2328. OutputFile *of = output_files[ost->file_index];
  2329. AVFormatContext *os = output_files[ost->file_index]->ctx;
  2330. if (ost->finished ||
  2331. (os->pb && avio_tell(os->pb) >= of->limit_filesize))
  2332. continue;
  2333. if (ost->frame_number >= ost->max_frames) {
  2334. int j;
  2335. for (j = 0; j < of->ctx->nb_streams; j++)
  2336. close_output_stream(output_streams[of->ost_index + j]);
  2337. continue;
  2338. }
  2339. return 1;
  2340. }
  2341. return 0;
  2342. }
  2343. /**
  2344. * Select the output stream to process.
  2345. *
  2346. * @return selected output stream, or NULL if none available
  2347. */
  2348. static OutputStream *choose_output(void)
  2349. {
  2350. int i;
  2351. int64_t opts_min = INT64_MAX;
  2352. OutputStream *ost_min = NULL;
  2353. for (i = 0; i < nb_output_streams; i++) {
  2354. OutputStream *ost = output_streams[i];
  2355. int64_t opts = av_rescale_q(ost->st->cur_dts, ost->st->time_base,
  2356. AV_TIME_BASE_Q);
  2357. if (!ost->unavailable && !ost->finished && opts < opts_min) {
  2358. opts_min = opts;
  2359. ost_min = ost;
  2360. }
  2361. }
  2362. return ost_min;
  2363. }
  2364. static int check_keyboard_interaction(int64_t cur_time)
  2365. {
  2366. int i, ret, key;
  2367. static int64_t last_time;
  2368. if (received_nb_signals)
  2369. return AVERROR_EXIT;
  2370. /* read_key() returns 0 on EOF */
  2371. if(cur_time - last_time >= 100000 && !run_as_daemon){
  2372. key = read_key();
  2373. last_time = cur_time;
  2374. }else
  2375. key = -1;
  2376. if (key == 'q')
  2377. return AVERROR_EXIT;
  2378. if (key == '+') av_log_set_level(av_log_get_level()+10);
  2379. if (key == '-') av_log_set_level(av_log_get_level()-10);
  2380. if (key == 's') qp_hist ^= 1;
  2381. if (key == 'h'){
  2382. if (do_hex_dump){
  2383. do_hex_dump = do_pkt_dump = 0;
  2384. } else if(do_pkt_dump){
  2385. do_hex_dump = 1;
  2386. } else
  2387. do_pkt_dump = 1;
  2388. av_log_set_level(AV_LOG_DEBUG);
  2389. }
  2390. if (key == 'c' || key == 'C'){
  2391. char buf[4096], target[64], command[256], arg[256] = {0};
  2392. double time;
  2393. int k, n = 0;
  2394. fprintf(stderr, "\nEnter command: <target>|all <time>|-1 <command>[ <argument>]\n");
  2395. i = 0;
  2396. while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
  2397. if (k > 0)
  2398. buf[i++] = k;
  2399. buf[i] = 0;
  2400. if (k > 0 &&
  2401. (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
  2402. av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
  2403. target, time, command, arg);
  2404. for (i = 0; i < nb_filtergraphs; i++) {
  2405. FilterGraph *fg = filtergraphs[i];
  2406. if (fg->graph) {
  2407. if (time < 0) {
  2408. ret = avfilter_graph_send_command(fg->graph, target, command, arg, buf, sizeof(buf),
  2409. key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
  2410. fprintf(stderr, "Command reply for stream %d: ret:%d res:\n%s", i, ret, buf);
  2411. } else if (key == 'c') {
  2412. fprintf(stderr, "Queing commands only on filters supporting the specific command is unsupported\n");
  2413. ret = AVERROR_PATCHWELCOME;
  2414. } else {
  2415. ret = avfilter_graph_queue_command(fg->graph, target, command, arg, 0, time);
  2416. }
  2417. }
  2418. }
  2419. } else {
  2420. av_log(NULL, AV_LOG_ERROR,
  2421. "Parse error, at least 3 arguments were expected, "
  2422. "only %d given in string '%s'\n", n, buf);
  2423. }
  2424. }
  2425. if (key == 'd' || key == 'D'){
  2426. int debug=0;
  2427. if(key == 'D') {
  2428. debug = input_streams[0]->st->codec->debug<<1;
  2429. if(!debug) debug = 1;
  2430. while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
  2431. debug += debug;
  2432. }else
  2433. if(scanf("%d", &debug)!=1)
  2434. fprintf(stderr,"error parsing debug value\n");
  2435. for(i=0;i<nb_input_streams;i++) {
  2436. input_streams[i]->st->codec->debug = debug;
  2437. }
  2438. for(i=0;i<nb_output_streams;i++) {
  2439. OutputStream *ost = output_streams[i];
  2440. ost->st->codec->debug = debug;
  2441. }
  2442. if(debug) av_log_set_level(AV_LOG_DEBUG);
  2443. fprintf(stderr,"debug=%d\n", debug);
  2444. }
  2445. if (key == '?'){
  2446. fprintf(stderr, "key function\n"
  2447. "? show this help\n"
  2448. "+ increase verbosity\n"
  2449. "- decrease verbosity\n"
  2450. "c Send command to first matching filter supporting it\n"
  2451. "C Send/Que command to all matching filters\n"
  2452. "D cycle through available debug modes\n"
  2453. "h dump packets/hex press to cycle through the 3 states\n"
  2454. "q quit\n"
  2455. "s Show QP histogram\n"
  2456. );
  2457. }
  2458. return 0;
  2459. }
  2460. #if HAVE_PTHREADS
  2461. static void *input_thread(void *arg)
  2462. {
  2463. InputFile *f = arg;
  2464. int ret = 0;
  2465. while (!transcoding_finished && ret >= 0) {
  2466. AVPacket pkt;
  2467. ret = av_read_frame(f->ctx, &pkt);
  2468. if (ret == AVERROR(EAGAIN)) {
  2469. av_usleep(10000);
  2470. ret = 0;
  2471. continue;
  2472. } else if (ret < 0)
  2473. break;
  2474. pthread_mutex_lock(&f->fifo_lock);
  2475. while (!av_fifo_space(f->fifo))
  2476. pthread_cond_wait(&f->fifo_cond, &f->fifo_lock);
  2477. av_dup_packet(&pkt);
  2478. av_fifo_generic_write(f->fifo, &pkt, sizeof(pkt), NULL);
  2479. pthread_mutex_unlock(&f->fifo_lock);
  2480. }
  2481. f->finished = 1;
  2482. return NULL;
  2483. }
  2484. static void free_input_threads(void)
  2485. {
  2486. int i;
  2487. if (nb_input_files == 1)
  2488. return;
  2489. transcoding_finished = 1;
  2490. for (i = 0; i < nb_input_files; i++) {
  2491. InputFile *f = input_files[i];
  2492. AVPacket pkt;
  2493. if (!f->fifo || f->joined)
  2494. continue;
  2495. pthread_mutex_lock(&f->fifo_lock);
  2496. while (av_fifo_size(f->fifo)) {
  2497. av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
  2498. av_free_packet(&pkt);
  2499. }
  2500. pthread_cond_signal(&f->fifo_cond);
  2501. pthread_mutex_unlock(&f->fifo_lock);
  2502. pthread_join(f->thread, NULL);
  2503. f->joined = 1;
  2504. while (av_fifo_size(f->fifo)) {
  2505. av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
  2506. av_free_packet(&pkt);
  2507. }
  2508. av_fifo_free(f->fifo);
  2509. }
  2510. }
  2511. static int init_input_threads(void)
  2512. {
  2513. int i, ret;
  2514. if (nb_input_files == 1)
  2515. return 0;
  2516. for (i = 0; i < nb_input_files; i++) {
  2517. InputFile *f = input_files[i];
  2518. if (!(f->fifo = av_fifo_alloc(8*sizeof(AVPacket))))
  2519. return AVERROR(ENOMEM);
  2520. pthread_mutex_init(&f->fifo_lock, NULL);
  2521. pthread_cond_init (&f->fifo_cond, NULL);
  2522. if ((ret = pthread_create(&f->thread, NULL, input_thread, f)))
  2523. return AVERROR(ret);
  2524. }
  2525. return 0;
  2526. }
  2527. static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
  2528. {
  2529. int ret = 0;
  2530. pthread_mutex_lock(&f->fifo_lock);
  2531. if (av_fifo_size(f->fifo)) {
  2532. av_fifo_generic_read(f->fifo, pkt, sizeof(*pkt), NULL);
  2533. pthread_cond_signal(&f->fifo_cond);
  2534. } else {
  2535. if (f->finished)
  2536. ret = AVERROR_EOF;
  2537. else
  2538. ret = AVERROR(EAGAIN);
  2539. }
  2540. pthread_mutex_unlock(&f->fifo_lock);
  2541. return ret;
  2542. }
  2543. #endif
  2544. static int get_input_packet(InputFile *f, AVPacket *pkt)
  2545. {
  2546. if (f->rate_emu) {
  2547. int i;
  2548. for (i = 0; i < f->nb_streams; i++) {
  2549. InputStream *ist = input_streams[f->ist_index + i];
  2550. int64_t pts = av_rescale(ist->dts, 1000000, AV_TIME_BASE);
  2551. int64_t now = av_gettime() - ist->start;
  2552. if (pts > now)
  2553. return AVERROR(EAGAIN);
  2554. }
  2555. }
  2556. #if HAVE_PTHREADS
  2557. if (nb_input_files > 1)
  2558. return get_input_packet_mt(f, pkt);
  2559. #endif
  2560. return av_read_frame(f->ctx, pkt);
  2561. }
  2562. static int got_eagain(void)
  2563. {
  2564. int i;
  2565. for (i = 0; i < nb_output_streams; i++)
  2566. if (output_streams[i]->unavailable)
  2567. return 1;
  2568. return 0;
  2569. }
  2570. static void reset_eagain(void)
  2571. {
  2572. int i;
  2573. for (i = 0; i < nb_input_files; i++)
  2574. input_files[i]->eagain = 0;
  2575. for (i = 0; i < nb_output_streams; i++)
  2576. output_streams[i]->unavailable = 0;
  2577. }
  2578. /*
  2579. * Return
  2580. * - 0 -- one packet was read and processed
  2581. * - AVERROR(EAGAIN) -- no packets were available for selected file,
  2582. * this function should be called again
  2583. * - AVERROR_EOF -- this function should not be called again
  2584. */
  2585. static int process_input(int file_index)
  2586. {
  2587. InputFile *ifile = input_files[file_index];
  2588. AVFormatContext *is;
  2589. InputStream *ist;
  2590. AVPacket pkt;
  2591. int ret, i, j;
  2592. is = ifile->ctx;
  2593. ret = get_input_packet(ifile, &pkt);
  2594. if (ret == AVERROR(EAGAIN)) {
  2595. ifile->eagain = 1;
  2596. return ret;
  2597. }
  2598. if (ret < 0) {
  2599. if (ret != AVERROR_EOF) {
  2600. print_error(is->filename, ret);
  2601. if (exit_on_error)
  2602. exit_program(1);
  2603. }
  2604. ifile->eof_reached = 1;
  2605. for (i = 0; i < ifile->nb_streams; i++) {
  2606. ist = input_streams[ifile->ist_index + i];
  2607. if (ist->decoding_needed)
  2608. output_packet(ist, NULL);
  2609. /* mark all outputs that don't go through lavfi as finished */
  2610. for (j = 0; j < nb_output_streams; j++) {
  2611. OutputStream *ost = output_streams[j];
  2612. if (ost->source_index == ifile->ist_index + i &&
  2613. (ost->stream_copy || ost->enc->type == AVMEDIA_TYPE_SUBTITLE))
  2614. close_output_stream(ost);
  2615. }
  2616. }
  2617. return AVERROR(EAGAIN);
  2618. }
  2619. reset_eagain();
  2620. if (do_pkt_dump) {
  2621. av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
  2622. is->streams[pkt.stream_index]);
  2623. }
  2624. /* the following test is needed in case new streams appear
  2625. dynamically in stream : we ignore them */
  2626. if (pkt.stream_index >= ifile->nb_streams) {
  2627. report_new_stream(file_index, &pkt);
  2628. goto discard_packet;
  2629. }
  2630. ist = input_streams[ifile->ist_index + pkt.stream_index];
  2631. if (ist->discard)
  2632. goto discard_packet;
  2633. if (debug_ts) {
  2634. av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
  2635. "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",
  2636. ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->st->codec->codec_type),
  2637. av_ts2str(ist->next_dts), av_ts2timestr(ist->next_dts, &AV_TIME_BASE_Q),
  2638. av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &AV_TIME_BASE_Q),
  2639. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
  2640. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
  2641. av_ts2str(input_files[ist->file_index]->ts_offset),
  2642. av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
  2643. }
  2644. if(!ist->wrap_correction_done && is->start_time != AV_NOPTS_VALUE && ist->st->pts_wrap_bits < 64){
  2645. int64_t stime, stime2;
  2646. // Correcting starttime based on the enabled streams
  2647. // 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.
  2648. // so we instead do it here as part of discontinuity handling
  2649. if ( ist->next_dts == AV_NOPTS_VALUE
  2650. && ifile->ts_offset == -is->start_time
  2651. && (is->iformat->flags & AVFMT_TS_DISCONT)) {
  2652. int64_t new_start_time = INT64_MAX;
  2653. for (i=0; i<is->nb_streams; i++) {
  2654. AVStream *st = is->streams[i];
  2655. if(st->discard == AVDISCARD_ALL || st->start_time == AV_NOPTS_VALUE)
  2656. continue;
  2657. new_start_time = FFMIN(new_start_time, av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q));
  2658. }
  2659. if (new_start_time > is->start_time) {
  2660. av_log(is, AV_LOG_VERBOSE, "Correcting start time by %"PRId64"\n", new_start_time - is->start_time);
  2661. ifile->ts_offset = -new_start_time;
  2662. }
  2663. }
  2664. stime = av_rescale_q(is->start_time, AV_TIME_BASE_Q, ist->st->time_base);
  2665. stime2= stime + (1ULL<<ist->st->pts_wrap_bits);
  2666. ist->wrap_correction_done = 1;
  2667. if(stime2 > stime && pkt.dts != AV_NOPTS_VALUE && pkt.dts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
  2668. pkt.dts -= 1ULL<<ist->st->pts_wrap_bits;
  2669. ist->wrap_correction_done = 0;
  2670. }
  2671. if(stime2 > stime && pkt.pts != AV_NOPTS_VALUE && pkt.pts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
  2672. pkt.pts -= 1ULL<<ist->st->pts_wrap_bits;
  2673. ist->wrap_correction_done = 0;
  2674. }
  2675. }
  2676. if (pkt.dts != AV_NOPTS_VALUE)
  2677. pkt.dts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
  2678. if (pkt.pts != AV_NOPTS_VALUE)
  2679. pkt.pts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
  2680. if (pkt.pts != AV_NOPTS_VALUE)
  2681. pkt.pts *= ist->ts_scale;
  2682. if (pkt.dts != AV_NOPTS_VALUE)
  2683. pkt.dts *= ist->ts_scale;
  2684. if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts == AV_NOPTS_VALUE && !copy_ts
  2685. && (is->iformat->flags & AVFMT_TS_DISCONT) && ifile->last_ts != AV_NOPTS_VALUE) {
  2686. int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
  2687. int64_t delta = pkt_dts - ifile->last_ts;
  2688. if(delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
  2689. (delta > 1LL*dts_delta_threshold*AV_TIME_BASE &&
  2690. ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)){
  2691. ifile->ts_offset -= delta;
  2692. av_log(NULL, AV_LOG_DEBUG,
  2693. "Inter stream timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
  2694. delta, ifile->ts_offset);
  2695. pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  2696. if (pkt.pts != AV_NOPTS_VALUE)
  2697. pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  2698. }
  2699. }
  2700. if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE &&
  2701. !copy_ts) {
  2702. int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
  2703. int64_t delta = pkt_dts - ist->next_dts;
  2704. if (is->iformat->flags & AVFMT_TS_DISCONT) {
  2705. if(delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
  2706. (delta > 1LL*dts_delta_threshold*AV_TIME_BASE &&
  2707. ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
  2708. pkt_dts + AV_TIME_BASE/10 < ist->pts){
  2709. ifile->ts_offset -= delta;
  2710. av_log(NULL, AV_LOG_DEBUG,
  2711. "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
  2712. delta, ifile->ts_offset);
  2713. pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  2714. if (pkt.pts != AV_NOPTS_VALUE)
  2715. pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  2716. }
  2717. } else {
  2718. if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
  2719. (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)
  2720. ) {
  2721. av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);
  2722. pkt.dts = AV_NOPTS_VALUE;
  2723. }
  2724. if (pkt.pts != AV_NOPTS_VALUE){
  2725. int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);
  2726. delta = pkt_pts - ist->next_dts;
  2727. if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
  2728. (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)
  2729. ) {
  2730. av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);
  2731. pkt.pts = AV_NOPTS_VALUE;
  2732. }
  2733. }
  2734. }
  2735. }
  2736. if (pkt.dts != AV_NOPTS_VALUE)
  2737. ifile->last_ts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
  2738. if (debug_ts) {
  2739. 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",
  2740. ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->st->codec->codec_type),
  2741. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
  2742. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
  2743. av_ts2str(input_files[ist->file_index]->ts_offset),
  2744. av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
  2745. }
  2746. sub2video_heartbeat(ist, pkt.pts);
  2747. ret = output_packet(ist, &pkt);
  2748. if (ret < 0) {
  2749. char buf[128];
  2750. av_strerror(ret, buf, sizeof(buf));
  2751. av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d: %s\n",
  2752. ist->file_index, ist->st->index, buf);
  2753. if (exit_on_error)
  2754. exit_program(1);
  2755. }
  2756. discard_packet:
  2757. av_free_packet(&pkt);
  2758. return 0;
  2759. }
  2760. /**
  2761. * Perform a step of transcoding for the specified filter graph.
  2762. *
  2763. * @param[in] graph filter graph to consider
  2764. * @param[out] best_ist input stream where a frame would allow to continue
  2765. * @return 0 for success, <0 for error
  2766. */
  2767. static int transcode_from_filter(FilterGraph *graph, InputStream **best_ist)
  2768. {
  2769. int i, ret;
  2770. int nb_requests, nb_requests_max = 0;
  2771. InputFilter *ifilter;
  2772. InputStream *ist;
  2773. *best_ist = NULL;
  2774. ret = avfilter_graph_request_oldest(graph->graph);
  2775. if (ret >= 0)
  2776. return reap_filters();
  2777. if (ret == AVERROR_EOF) {
  2778. ret = reap_filters();
  2779. for (i = 0; i < graph->nb_outputs; i++)
  2780. close_output_stream(graph->outputs[i]->ost);
  2781. return ret;
  2782. }
  2783. if (ret != AVERROR(EAGAIN))
  2784. return ret;
  2785. for (i = 0; i < graph->nb_inputs; i++) {
  2786. ifilter = graph->inputs[i];
  2787. ist = ifilter->ist;
  2788. if (input_files[ist->file_index]->eagain ||
  2789. input_files[ist->file_index]->eof_reached)
  2790. continue;
  2791. nb_requests = av_buffersrc_get_nb_failed_requests(ifilter->filter);
  2792. if (nb_requests > nb_requests_max) {
  2793. nb_requests_max = nb_requests;
  2794. *best_ist = ist;
  2795. }
  2796. }
  2797. if (!*best_ist)
  2798. for (i = 0; i < graph->nb_outputs; i++)
  2799. graph->outputs[i]->ost->unavailable = 1;
  2800. return 0;
  2801. }
  2802. /**
  2803. * Run a single step of transcoding.
  2804. *
  2805. * @return 0 for success, <0 for error
  2806. */
  2807. static int transcode_step(void)
  2808. {
  2809. OutputStream *ost;
  2810. InputStream *ist;
  2811. int ret;
  2812. ost = choose_output();
  2813. if (!ost) {
  2814. if (got_eagain()) {
  2815. reset_eagain();
  2816. av_usleep(10000);
  2817. return 0;
  2818. }
  2819. av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from, finishing.\n");
  2820. return AVERROR_EOF;
  2821. }
  2822. if (ost->filter) {
  2823. if ((ret = transcode_from_filter(ost->filter->graph, &ist)) < 0)
  2824. return ret;
  2825. if (!ist)
  2826. return 0;
  2827. } else {
  2828. av_assert0(ost->source_index >= 0);
  2829. ist = input_streams[ost->source_index];
  2830. }
  2831. ret = process_input(ist->file_index);
  2832. if (ret == AVERROR(EAGAIN)) {
  2833. if (input_files[ist->file_index]->eagain)
  2834. ost->unavailable = 1;
  2835. return 0;
  2836. }
  2837. if (ret < 0)
  2838. return ret == AVERROR_EOF ? 0 : ret;
  2839. return reap_filters();
  2840. }
  2841. /*
  2842. * The following code is the main loop of the file converter
  2843. */
  2844. static int transcode(void)
  2845. {
  2846. int ret, i;
  2847. AVFormatContext *os;
  2848. OutputStream *ost;
  2849. InputStream *ist;
  2850. int64_t timer_start;
  2851. ret = transcode_init();
  2852. if (ret < 0)
  2853. goto fail;
  2854. if (stdin_interaction) {
  2855. av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
  2856. }
  2857. timer_start = av_gettime();
  2858. #if HAVE_PTHREADS
  2859. if ((ret = init_input_threads()) < 0)
  2860. goto fail;
  2861. #endif
  2862. while (!received_sigterm) {
  2863. int64_t cur_time= av_gettime();
  2864. /* if 'q' pressed, exits */
  2865. if (stdin_interaction)
  2866. if (check_keyboard_interaction(cur_time) < 0)
  2867. break;
  2868. /* check if there's any stream where output is still needed */
  2869. if (!need_output()) {
  2870. av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
  2871. break;
  2872. }
  2873. ret = transcode_step();
  2874. if (ret < 0) {
  2875. if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
  2876. continue;
  2877. av_log(NULL, AV_LOG_ERROR, "Error while filtering.\n");
  2878. break;
  2879. }
  2880. /* dump report by using the output first video and audio streams */
  2881. print_report(0, timer_start, cur_time);
  2882. }
  2883. #if HAVE_PTHREADS
  2884. free_input_threads();
  2885. #endif
  2886. /* at the end of stream, we must flush the decoder buffers */
  2887. for (i = 0; i < nb_input_streams; i++) {
  2888. ist = input_streams[i];
  2889. if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
  2890. output_packet(ist, NULL);
  2891. }
  2892. }
  2893. flush_encoders();
  2894. term_exit();
  2895. /* write the trailer if needed and close file */
  2896. for (i = 0; i < nb_output_files; i++) {
  2897. os = output_files[i]->ctx;
  2898. av_write_trailer(os);
  2899. }
  2900. /* dump report by using the first video and audio streams */
  2901. print_report(1, timer_start, av_gettime());
  2902. /* close each encoder */
  2903. for (i = 0; i < nb_output_streams; i++) {
  2904. ost = output_streams[i];
  2905. if (ost->encoding_needed) {
  2906. av_freep(&ost->st->codec->stats_in);
  2907. avcodec_close(ost->st->codec);
  2908. }
  2909. }
  2910. /* close each decoder */
  2911. for (i = 0; i < nb_input_streams; i++) {
  2912. ist = input_streams[i];
  2913. if (ist->decoding_needed) {
  2914. avcodec_close(ist->st->codec);
  2915. }
  2916. }
  2917. /* finished ! */
  2918. ret = 0;
  2919. fail:
  2920. #if HAVE_PTHREADS
  2921. free_input_threads();
  2922. #endif
  2923. if (output_streams) {
  2924. for (i = 0; i < nb_output_streams; i++) {
  2925. ost = output_streams[i];
  2926. if (ost) {
  2927. if (ost->stream_copy)
  2928. av_freep(&ost->st->codec->extradata);
  2929. if (ost->logfile) {
  2930. fclose(ost->logfile);
  2931. ost->logfile = NULL;
  2932. }
  2933. av_freep(&ost->st->codec->subtitle_header);
  2934. av_freep(&ost->forced_kf_pts);
  2935. av_freep(&ost->apad);
  2936. av_dict_free(&ost->opts);
  2937. av_dict_free(&ost->swr_opts);
  2938. av_dict_free(&ost->resample_opts);
  2939. }
  2940. }
  2941. }
  2942. return ret;
  2943. }
  2944. static int64_t getutime(void)
  2945. {
  2946. #if HAVE_GETRUSAGE
  2947. struct rusage rusage;
  2948. getrusage(RUSAGE_SELF, &rusage);
  2949. return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
  2950. #elif HAVE_GETPROCESSTIMES
  2951. HANDLE proc;
  2952. FILETIME c, e, k, u;
  2953. proc = GetCurrentProcess();
  2954. GetProcessTimes(proc, &c, &e, &k, &u);
  2955. return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
  2956. #else
  2957. return av_gettime();
  2958. #endif
  2959. }
  2960. static int64_t getmaxrss(void)
  2961. {
  2962. #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
  2963. struct rusage rusage;
  2964. getrusage(RUSAGE_SELF, &rusage);
  2965. return (int64_t)rusage.ru_maxrss * 1024;
  2966. #elif HAVE_GETPROCESSMEMORYINFO
  2967. HANDLE proc;
  2968. PROCESS_MEMORY_COUNTERS memcounters;
  2969. proc = GetCurrentProcess();
  2970. memcounters.cb = sizeof(memcounters);
  2971. GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
  2972. return memcounters.PeakPagefileUsage;
  2973. #else
  2974. return 0;
  2975. #endif
  2976. }
  2977. static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
  2978. {
  2979. }
  2980. int main(int argc, char **argv)
  2981. {
  2982. int ret;
  2983. int64_t ti;
  2984. register_exit(ffmpeg_cleanup);
  2985. setvbuf(stderr,NULL,_IONBF,0); /* win32 runtime needs this */
  2986. av_log_set_flags(AV_LOG_SKIP_REPEATED);
  2987. parse_loglevel(argc, argv, options);
  2988. if(argc>1 && !strcmp(argv[1], "-d")){
  2989. run_as_daemon=1;
  2990. av_log_set_callback(log_callback_null);
  2991. argc--;
  2992. argv++;
  2993. }
  2994. avcodec_register_all();
  2995. #if CONFIG_AVDEVICE
  2996. avdevice_register_all();
  2997. #endif
  2998. avfilter_register_all();
  2999. av_register_all();
  3000. avformat_network_init();
  3001. show_banner(argc, argv, options);
  3002. term_init();
  3003. /* parse options and open all input/output files */
  3004. ret = ffmpeg_parse_options(argc, argv);
  3005. if (ret < 0)
  3006. exit_program(1);
  3007. if (nb_output_files <= 0 && nb_input_files == 0) {
  3008. show_usage();
  3009. av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
  3010. exit_program(1);
  3011. }
  3012. /* file converter / grab */
  3013. if (nb_output_files <= 0) {
  3014. av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
  3015. exit_program(1);
  3016. }
  3017. // if (nb_input_files == 0) {
  3018. // av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
  3019. // exit_program(1);
  3020. // }
  3021. current_time = ti = getutime();
  3022. if (transcode() < 0)
  3023. exit_program(1);
  3024. ti = getutime() - ti;
  3025. if (do_benchmark) {
  3026. printf("bench: utime=%0.3fs\n", ti / 1000000.0);
  3027. }
  3028. av_log(NULL, AV_LOG_DEBUG, "%"PRIu64" frames successfully decoded, %"PRIu64" decoding errors\n",
  3029. decode_error_stat[0], decode_error_stat[1]);
  3030. if ((decode_error_stat[0] + decode_error_stat[1]) * max_error_rate < decode_error_stat[1])
  3031. exit_program(69);
  3032. exit_program(received_nb_signals ? 255 : 0);
  3033. return 0;
  3034. }