ffmpeg.c 160 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598
  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. #include <stdint.h>
  32. #if HAVE_IO_H
  33. #include <io.h>
  34. #endif
  35. #if HAVE_UNISTD_H
  36. #include <unistd.h>
  37. #endif
  38. #include "libavformat/avformat.h"
  39. #include "libavdevice/avdevice.h"
  40. #include "libswresample/swresample.h"
  41. #include "libavutil/opt.h"
  42. #include "libavutil/channel_layout.h"
  43. #include "libavutil/parseutils.h"
  44. #include "libavutil/samplefmt.h"
  45. #include "libavutil/fifo.h"
  46. #include "libavutil/internal.h"
  47. #include "libavutil/intreadwrite.h"
  48. #include "libavutil/dict.h"
  49. #include "libavutil/mathematics.h"
  50. #include "libavutil/pixdesc.h"
  51. #include "libavutil/avstring.h"
  52. #include "libavutil/libm.h"
  53. #include "libavutil/imgutils.h"
  54. #include "libavutil/timestamp.h"
  55. #include "libavutil/bprint.h"
  56. #include "libavutil/time.h"
  57. #include "libavutil/threadmessage.h"
  58. #include "libavcodec/mathops.h"
  59. #include "libavformat/os_support.h"
  60. # include "libavfilter/avfilter.h"
  61. # include "libavfilter/buffersrc.h"
  62. # include "libavfilter/buffersink.h"
  63. #if HAVE_SYS_RESOURCE_H
  64. #include <sys/time.h>
  65. #include <sys/types.h>
  66. #include <sys/resource.h>
  67. #elif HAVE_GETPROCESSTIMES
  68. #include <windows.h>
  69. #endif
  70. #if HAVE_GETPROCESSMEMORYINFO
  71. #include <windows.h>
  72. #include <psapi.h>
  73. #endif
  74. #if HAVE_SETCONSOLECTRLHANDLER
  75. #include <windows.h>
  76. #endif
  77. #if HAVE_SYS_SELECT_H
  78. #include <sys/select.h>
  79. #endif
  80. #if HAVE_TERMIOS_H
  81. #include <fcntl.h>
  82. #include <sys/ioctl.h>
  83. #include <sys/time.h>
  84. #include <termios.h>
  85. #elif HAVE_KBHIT
  86. #include <conio.h>
  87. #endif
  88. #if HAVE_PTHREADS
  89. #include <pthread.h>
  90. #endif
  91. #include <time.h>
  92. #include "ffmpeg.h"
  93. #include "cmdutils.h"
  94. #include "libavutil/avassert.h"
  95. const char program_name[] = "ffmpeg";
  96. const int program_birth_year = 2000;
  97. static FILE *vstats_file;
  98. const char *const forced_keyframes_const_names[] = {
  99. "n",
  100. "n_forced",
  101. "prev_forced_n",
  102. "prev_forced_t",
  103. "t",
  104. NULL
  105. };
  106. static void do_video_stats(OutputStream *ost, int frame_size);
  107. static int64_t getutime(void);
  108. static int64_t getmaxrss(void);
  109. static int run_as_daemon = 0;
  110. static int nb_frames_dup = 0;
  111. static unsigned dup_warning = 1000;
  112. static int nb_frames_drop = 0;
  113. static int64_t decode_error_stat[2];
  114. static int want_sdp = 1;
  115. static int current_time;
  116. AVIOContext *progress_avio = NULL;
  117. static uint8_t *subtitle_out;
  118. InputStream **input_streams = NULL;
  119. int nb_input_streams = 0;
  120. InputFile **input_files = NULL;
  121. int nb_input_files = 0;
  122. OutputStream **output_streams = NULL;
  123. int nb_output_streams = 0;
  124. OutputFile **output_files = NULL;
  125. int nb_output_files = 0;
  126. FilterGraph **filtergraphs;
  127. int nb_filtergraphs;
  128. #if HAVE_TERMIOS_H
  129. /* init terminal so that we can grab keys */
  130. static struct termios oldtty;
  131. static int restore_tty;
  132. #endif
  133. #if HAVE_PTHREADS
  134. static void free_input_threads(void);
  135. #endif
  136. /* sub2video hack:
  137. Convert subtitles to video with alpha to insert them in filter graphs.
  138. This is a temporary solution until libavfilter gets real subtitles support.
  139. */
  140. static int sub2video_get_blank_frame(InputStream *ist)
  141. {
  142. int ret;
  143. AVFrame *frame = ist->sub2video.frame;
  144. av_frame_unref(frame);
  145. ist->sub2video.frame->width = ist->dec_ctx->width ? ist->dec_ctx->width : ist->sub2video.w;
  146. ist->sub2video.frame->height = ist->dec_ctx->height ? ist->dec_ctx->height : ist->sub2video.h;
  147. ist->sub2video.frame->format = AV_PIX_FMT_RGB32;
  148. if ((ret = av_frame_get_buffer(frame, 32)) < 0)
  149. return ret;
  150. memset(frame->data[0], 0, frame->height * frame->linesize[0]);
  151. return 0;
  152. }
  153. static void sub2video_copy_rect(uint8_t *dst, int dst_linesize, int w, int h,
  154. AVSubtitleRect *r)
  155. {
  156. uint32_t *pal, *dst2;
  157. uint8_t *src, *src2;
  158. int x, y;
  159. if (r->type != SUBTITLE_BITMAP) {
  160. av_log(NULL, AV_LOG_WARNING, "sub2video: non-bitmap subtitle\n");
  161. return;
  162. }
  163. if (r->x < 0 || r->x + r->w > w || r->y < 0 || r->y + r->h > h) {
  164. av_log(NULL, AV_LOG_WARNING, "sub2video: rectangle (%d %d %d %d) overflowing %d %d\n",
  165. r->x, r->y, r->w, r->h, w, h
  166. );
  167. return;
  168. }
  169. dst += r->y * dst_linesize + r->x * 4;
  170. src = r->data[0];
  171. pal = (uint32_t *)r->data[1];
  172. for (y = 0; y < r->h; y++) {
  173. dst2 = (uint32_t *)dst;
  174. src2 = src;
  175. for (x = 0; x < r->w; x++)
  176. *(dst2++) = pal[*(src2++)];
  177. dst += dst_linesize;
  178. src += r->linesize[0];
  179. }
  180. }
  181. static void sub2video_push_ref(InputStream *ist, int64_t pts)
  182. {
  183. AVFrame *frame = ist->sub2video.frame;
  184. int i;
  185. av_assert1(frame->data[0]);
  186. ist->sub2video.last_pts = frame->pts = pts;
  187. for (i = 0; i < ist->nb_filters; i++)
  188. av_buffersrc_add_frame_flags(ist->filters[i]->filter, frame,
  189. AV_BUFFERSRC_FLAG_KEEP_REF |
  190. AV_BUFFERSRC_FLAG_PUSH);
  191. }
  192. static void sub2video_update(InputStream *ist, AVSubtitle *sub)
  193. {
  194. AVFrame *frame = ist->sub2video.frame;
  195. int8_t *dst;
  196. int dst_linesize;
  197. int num_rects, i;
  198. int64_t pts, end_pts;
  199. if (!frame)
  200. return;
  201. if (sub) {
  202. pts = av_rescale_q(sub->pts + sub->start_display_time * 1000LL,
  203. AV_TIME_BASE_Q, ist->st->time_base);
  204. end_pts = av_rescale_q(sub->pts + sub->end_display_time * 1000LL,
  205. AV_TIME_BASE_Q, ist->st->time_base);
  206. num_rects = sub->num_rects;
  207. } else {
  208. pts = ist->sub2video.end_pts;
  209. end_pts = INT64_MAX;
  210. num_rects = 0;
  211. }
  212. if (sub2video_get_blank_frame(ist) < 0) {
  213. av_log(ist->dec_ctx, AV_LOG_ERROR,
  214. "Impossible to get a blank canvas.\n");
  215. return;
  216. }
  217. dst = frame->data [0];
  218. dst_linesize = frame->linesize[0];
  219. for (i = 0; i < num_rects; i++)
  220. sub2video_copy_rect(dst, dst_linesize, frame->width, frame->height, sub->rects[i]);
  221. sub2video_push_ref(ist, pts);
  222. ist->sub2video.end_pts = end_pts;
  223. }
  224. static void sub2video_heartbeat(InputStream *ist, int64_t pts)
  225. {
  226. InputFile *infile = input_files[ist->file_index];
  227. int i, j, nb_reqs;
  228. int64_t pts2;
  229. /* When a frame is read from a file, examine all sub2video streams in
  230. the same file and send the sub2video frame again. Otherwise, decoded
  231. video frames could be accumulating in the filter graph while a filter
  232. (possibly overlay) is desperately waiting for a subtitle frame. */
  233. for (i = 0; i < infile->nb_streams; i++) {
  234. InputStream *ist2 = input_streams[infile->ist_index + i];
  235. if (!ist2->sub2video.frame)
  236. continue;
  237. /* subtitles seem to be usually muxed ahead of other streams;
  238. if not, subtracting a larger time here is necessary */
  239. pts2 = av_rescale_q(pts, ist->st->time_base, ist2->st->time_base) - 1;
  240. /* do not send the heartbeat frame if the subtitle is already ahead */
  241. if (pts2 <= ist2->sub2video.last_pts)
  242. continue;
  243. if (pts2 >= ist2->sub2video.end_pts || !ist2->sub2video.frame->data[0])
  244. sub2video_update(ist2, NULL);
  245. for (j = 0, nb_reqs = 0; j < ist2->nb_filters; j++)
  246. nb_reqs += av_buffersrc_get_nb_failed_requests(ist2->filters[j]->filter);
  247. if (nb_reqs)
  248. sub2video_push_ref(ist2, pts2);
  249. }
  250. }
  251. static void sub2video_flush(InputStream *ist)
  252. {
  253. int i;
  254. if (ist->sub2video.end_pts < INT64_MAX)
  255. sub2video_update(ist, NULL);
  256. for (i = 0; i < ist->nb_filters; i++)
  257. av_buffersrc_add_frame(ist->filters[i]->filter, NULL);
  258. }
  259. /* end of sub2video hack */
  260. static void term_exit_sigsafe(void)
  261. {
  262. #if HAVE_TERMIOS_H
  263. if(restore_tty)
  264. tcsetattr (0, TCSANOW, &oldtty);
  265. #endif
  266. }
  267. void term_exit(void)
  268. {
  269. av_log(NULL, AV_LOG_QUIET, "%s", "");
  270. term_exit_sigsafe();
  271. }
  272. static volatile int received_sigterm = 0;
  273. static volatile int received_nb_signals = 0;
  274. static volatile int transcode_init_done = 0;
  275. static volatile int ffmpeg_exited = 0;
  276. static int main_return_code = 0;
  277. static void
  278. sigterm_handler(int sig)
  279. {
  280. received_sigterm = sig;
  281. received_nb_signals++;
  282. term_exit_sigsafe();
  283. if(received_nb_signals > 3) {
  284. write(2/*STDERR_FILENO*/, "Received > 3 system signals, hard exiting\n",
  285. strlen("Received > 3 system signals, hard exiting\n"));
  286. exit(123);
  287. }
  288. }
  289. #if HAVE_SETCONSOLECTRLHANDLER
  290. static BOOL WINAPI CtrlHandler(DWORD fdwCtrlType)
  291. {
  292. av_log(NULL, AV_LOG_DEBUG, "\nReceived windows signal %ld\n", fdwCtrlType);
  293. switch (fdwCtrlType)
  294. {
  295. case CTRL_C_EVENT:
  296. case CTRL_BREAK_EVENT:
  297. sigterm_handler(SIGINT);
  298. return TRUE;
  299. case CTRL_CLOSE_EVENT:
  300. case CTRL_LOGOFF_EVENT:
  301. case CTRL_SHUTDOWN_EVENT:
  302. sigterm_handler(SIGTERM);
  303. /* Basically, with these 3 events, when we return from this method the
  304. process is hard terminated, so stall as long as we need to
  305. to try and let the main thread(s) clean up and gracefully terminate
  306. (we have at most 5 seconds, but should be done far before that). */
  307. while (!ffmpeg_exited) {
  308. Sleep(0);
  309. }
  310. return TRUE;
  311. default:
  312. av_log(NULL, AV_LOG_ERROR, "Received unknown windows signal %ld\n", fdwCtrlType);
  313. return FALSE;
  314. }
  315. }
  316. #endif
  317. void term_init(void)
  318. {
  319. #if HAVE_TERMIOS_H
  320. if (!run_as_daemon && stdin_interaction) {
  321. struct termios tty;
  322. if (tcgetattr (0, &tty) == 0) {
  323. oldtty = tty;
  324. restore_tty = 1;
  325. tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
  326. |INLCR|IGNCR|ICRNL|IXON);
  327. tty.c_oflag |= OPOST;
  328. tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
  329. tty.c_cflag &= ~(CSIZE|PARENB);
  330. tty.c_cflag |= CS8;
  331. tty.c_cc[VMIN] = 1;
  332. tty.c_cc[VTIME] = 0;
  333. tcsetattr (0, TCSANOW, &tty);
  334. }
  335. signal(SIGQUIT, sigterm_handler); /* Quit (POSIX). */
  336. }
  337. #endif
  338. signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
  339. signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
  340. #ifdef SIGXCPU
  341. signal(SIGXCPU, sigterm_handler);
  342. #endif
  343. #if HAVE_SETCONSOLECTRLHANDLER
  344. SetConsoleCtrlHandler((PHANDLER_ROUTINE) CtrlHandler, TRUE);
  345. #endif
  346. }
  347. /* read a key without blocking */
  348. static int read_key(void)
  349. {
  350. unsigned char ch;
  351. #if HAVE_TERMIOS_H
  352. int n = 1;
  353. struct timeval tv;
  354. fd_set rfds;
  355. FD_ZERO(&rfds);
  356. FD_SET(0, &rfds);
  357. tv.tv_sec = 0;
  358. tv.tv_usec = 0;
  359. n = select(1, &rfds, NULL, NULL, &tv);
  360. if (n > 0) {
  361. n = read(0, &ch, 1);
  362. if (n == 1)
  363. return ch;
  364. return n;
  365. }
  366. #elif HAVE_KBHIT
  367. # if HAVE_PEEKNAMEDPIPE
  368. static int is_pipe;
  369. static HANDLE input_handle;
  370. DWORD dw, nchars;
  371. if(!input_handle){
  372. input_handle = GetStdHandle(STD_INPUT_HANDLE);
  373. is_pipe = !GetConsoleMode(input_handle, &dw);
  374. }
  375. if (is_pipe) {
  376. /* When running under a GUI, you will end here. */
  377. if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL)) {
  378. // input pipe may have been closed by the program that ran ffmpeg
  379. return -1;
  380. }
  381. //Read it
  382. if(nchars != 0) {
  383. read(0, &ch, 1);
  384. return ch;
  385. }else{
  386. return -1;
  387. }
  388. }
  389. # endif
  390. if(kbhit())
  391. return(getch());
  392. #endif
  393. return -1;
  394. }
  395. static int decode_interrupt_cb(void *ctx)
  396. {
  397. return received_nb_signals > transcode_init_done;
  398. }
  399. const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
  400. static void ffmpeg_cleanup(int ret)
  401. {
  402. int i, j;
  403. if (do_benchmark) {
  404. int maxrss = getmaxrss() / 1024;
  405. av_log(NULL, AV_LOG_INFO, "bench: maxrss=%ikB\n", maxrss);
  406. }
  407. for (i = 0; i < nb_filtergraphs; i++) {
  408. FilterGraph *fg = filtergraphs[i];
  409. avfilter_graph_free(&fg->graph);
  410. for (j = 0; j < fg->nb_inputs; j++) {
  411. av_buffer_unref(&fg->inputs[j]->hw_frames_ctx);
  412. av_freep(&fg->inputs[j]->name);
  413. av_freep(&fg->inputs[j]);
  414. }
  415. av_freep(&fg->inputs);
  416. for (j = 0; j < fg->nb_outputs; j++) {
  417. av_freep(&fg->outputs[j]->name);
  418. av_freep(&fg->outputs[j]->formats);
  419. av_freep(&fg->outputs[j]->channel_layouts);
  420. av_freep(&fg->outputs[j]->sample_rates);
  421. av_freep(&fg->outputs[j]);
  422. }
  423. av_freep(&fg->outputs);
  424. av_freep(&fg->graph_desc);
  425. av_freep(&filtergraphs[i]);
  426. }
  427. av_freep(&filtergraphs);
  428. av_freep(&subtitle_out);
  429. /* close files */
  430. for (i = 0; i < nb_output_files; i++) {
  431. OutputFile *of = output_files[i];
  432. AVFormatContext *s;
  433. if (!of)
  434. continue;
  435. s = of->ctx;
  436. if (s && s->oformat && !(s->oformat->flags & AVFMT_NOFILE))
  437. avio_closep(&s->pb);
  438. avformat_free_context(s);
  439. av_dict_free(&of->opts);
  440. av_freep(&output_files[i]);
  441. }
  442. for (i = 0; i < nb_output_streams; i++) {
  443. OutputStream *ost = output_streams[i];
  444. if (!ost)
  445. continue;
  446. for (j = 0; j < ost->nb_bitstream_filters; j++)
  447. av_bsf_free(&ost->bsf_ctx[j]);
  448. av_freep(&ost->bsf_ctx);
  449. av_freep(&ost->bsf_extradata_updated);
  450. av_frame_free(&ost->filtered_frame);
  451. av_frame_free(&ost->last_frame);
  452. av_dict_free(&ost->encoder_opts);
  453. av_parser_close(ost->parser);
  454. avcodec_free_context(&ost->parser_avctx);
  455. av_freep(&ost->forced_keyframes);
  456. av_expr_free(ost->forced_keyframes_pexpr);
  457. av_freep(&ost->avfilter);
  458. av_freep(&ost->logfile_prefix);
  459. av_freep(&ost->audio_channels_map);
  460. ost->audio_channels_mapped = 0;
  461. av_dict_free(&ost->sws_dict);
  462. avcodec_free_context(&ost->enc_ctx);
  463. avcodec_parameters_free(&ost->ref_par);
  464. while (ost->muxing_queue && av_fifo_size(ost->muxing_queue)) {
  465. AVPacket pkt;
  466. av_fifo_generic_read(ost->muxing_queue, &pkt, sizeof(pkt), NULL);
  467. av_packet_unref(&pkt);
  468. }
  469. av_fifo_freep(&ost->muxing_queue);
  470. av_freep(&output_streams[i]);
  471. }
  472. #if HAVE_PTHREADS
  473. free_input_threads();
  474. #endif
  475. for (i = 0; i < nb_input_files; i++) {
  476. avformat_close_input(&input_files[i]->ctx);
  477. av_freep(&input_files[i]);
  478. }
  479. for (i = 0; i < nb_input_streams; i++) {
  480. InputStream *ist = input_streams[i];
  481. av_frame_free(&ist->decoded_frame);
  482. av_frame_free(&ist->filter_frame);
  483. av_dict_free(&ist->decoder_opts);
  484. avsubtitle_free(&ist->prev_sub.subtitle);
  485. av_frame_free(&ist->sub2video.frame);
  486. av_freep(&ist->filters);
  487. av_freep(&ist->hwaccel_device);
  488. av_freep(&ist->dts_buffer);
  489. avcodec_free_context(&ist->dec_ctx);
  490. av_freep(&input_streams[i]);
  491. }
  492. if (vstats_file) {
  493. if (fclose(vstats_file))
  494. av_log(NULL, AV_LOG_ERROR,
  495. "Error closing vstats file, loss of information possible: %s\n",
  496. av_err2str(AVERROR(errno)));
  497. }
  498. av_freep(&vstats_filename);
  499. av_freep(&input_streams);
  500. av_freep(&input_files);
  501. av_freep(&output_streams);
  502. av_freep(&output_files);
  503. uninit_opts();
  504. avformat_network_deinit();
  505. if (received_sigterm) {
  506. av_log(NULL, AV_LOG_INFO, "Exiting normally, received signal %d.\n",
  507. (int) received_sigterm);
  508. } else if (ret && transcode_init_done) {
  509. av_log(NULL, AV_LOG_INFO, "Conversion failed!\n");
  510. }
  511. term_exit();
  512. ffmpeg_exited = 1;
  513. }
  514. void remove_avoptions(AVDictionary **a, AVDictionary *b)
  515. {
  516. AVDictionaryEntry *t = NULL;
  517. while ((t = av_dict_get(b, "", t, AV_DICT_IGNORE_SUFFIX))) {
  518. av_dict_set(a, t->key, NULL, AV_DICT_MATCH_CASE);
  519. }
  520. }
  521. void assert_avoptions(AVDictionary *m)
  522. {
  523. AVDictionaryEntry *t;
  524. if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
  525. av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
  526. exit_program(1);
  527. }
  528. }
  529. static void abort_codec_experimental(AVCodec *c, int encoder)
  530. {
  531. exit_program(1);
  532. }
  533. static void update_benchmark(const char *fmt, ...)
  534. {
  535. if (do_benchmark_all) {
  536. int64_t t = getutime();
  537. va_list va;
  538. char buf[1024];
  539. if (fmt) {
  540. va_start(va, fmt);
  541. vsnprintf(buf, sizeof(buf), fmt, va);
  542. va_end(va);
  543. av_log(NULL, AV_LOG_INFO, "bench: %8"PRIu64" %s \n", t - current_time, buf);
  544. }
  545. current_time = t;
  546. }
  547. }
  548. static void close_all_output_streams(OutputStream *ost, OSTFinished this_stream, OSTFinished others)
  549. {
  550. int i;
  551. for (i = 0; i < nb_output_streams; i++) {
  552. OutputStream *ost2 = output_streams[i];
  553. ost2->finished |= ost == ost2 ? this_stream : others;
  554. }
  555. }
  556. static void write_packet(OutputFile *of, AVPacket *pkt, OutputStream *ost)
  557. {
  558. AVFormatContext *s = of->ctx;
  559. AVStream *st = ost->st;
  560. int ret;
  561. if (!of->header_written) {
  562. AVPacket tmp_pkt;
  563. /* the muxer is not initialized yet, buffer the packet */
  564. if (!av_fifo_space(ost->muxing_queue)) {
  565. int new_size = FFMIN(2 * av_fifo_size(ost->muxing_queue),
  566. ost->max_muxing_queue_size);
  567. if (new_size <= av_fifo_size(ost->muxing_queue)) {
  568. av_log(NULL, AV_LOG_ERROR,
  569. "Too many packets buffered for output stream %d:%d.\n",
  570. ost->file_index, ost->st->index);
  571. exit_program(1);
  572. }
  573. ret = av_fifo_realloc2(ost->muxing_queue, new_size);
  574. if (ret < 0)
  575. exit_program(1);
  576. }
  577. av_packet_move_ref(&tmp_pkt, pkt);
  578. av_fifo_generic_write(ost->muxing_queue, &tmp_pkt, sizeof(tmp_pkt), NULL);
  579. return;
  580. }
  581. if ((st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && video_sync_method == VSYNC_DROP) ||
  582. (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && audio_sync_method < 0))
  583. pkt->pts = pkt->dts = AV_NOPTS_VALUE;
  584. /*
  585. * Audio encoders may split the packets -- #frames in != #packets out.
  586. * But there is no reordering, so we can limit the number of output packets
  587. * by simply dropping them here.
  588. * Counting encoded video frames needs to be done separately because of
  589. * reordering, see do_video_out()
  590. */
  591. if (!(st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && ost->encoding_needed)) {
  592. if (ost->frame_number >= ost->max_frames) {
  593. av_packet_unref(pkt);
  594. return;
  595. }
  596. ost->frame_number++;
  597. }
  598. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  599. int i;
  600. uint8_t *sd = av_packet_get_side_data(pkt, AV_PKT_DATA_QUALITY_STATS,
  601. NULL);
  602. ost->quality = sd ? AV_RL32(sd) : -1;
  603. ost->pict_type = sd ? sd[4] : AV_PICTURE_TYPE_NONE;
  604. for (i = 0; i<FF_ARRAY_ELEMS(ost->error); i++) {
  605. if (sd && i < sd[5])
  606. ost->error[i] = AV_RL64(sd + 8 + 8*i);
  607. else
  608. ost->error[i] = -1;
  609. }
  610. if (ost->frame_rate.num && ost->is_cfr) {
  611. if (pkt->duration > 0)
  612. av_log(NULL, AV_LOG_WARNING, "Overriding packet duration by frame rate, this should not happen\n");
  613. pkt->duration = av_rescale_q(1, av_inv_q(ost->frame_rate),
  614. ost->st->time_base);
  615. }
  616. }
  617. if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
  618. if (pkt->dts != AV_NOPTS_VALUE &&
  619. pkt->pts != AV_NOPTS_VALUE &&
  620. pkt->dts > pkt->pts) {
  621. av_log(s, AV_LOG_WARNING, "Invalid DTS: %"PRId64" PTS: %"PRId64" in output stream %d:%d, replacing by guess\n",
  622. pkt->dts, pkt->pts,
  623. ost->file_index, ost->st->index);
  624. pkt->pts =
  625. pkt->dts = pkt->pts + pkt->dts + ost->last_mux_dts + 1
  626. - FFMIN3(pkt->pts, pkt->dts, ost->last_mux_dts + 1)
  627. - FFMAX3(pkt->pts, pkt->dts, ost->last_mux_dts + 1);
  628. }
  629. if ((st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) &&
  630. pkt->dts != AV_NOPTS_VALUE &&
  631. !(st->codecpar->codec_id == AV_CODEC_ID_VP9 && ost->stream_copy) &&
  632. ost->last_mux_dts != AV_NOPTS_VALUE) {
  633. int64_t max = ost->last_mux_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);
  634. if (pkt->dts < max) {
  635. int loglevel = max - pkt->dts > 2 || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ? AV_LOG_WARNING : AV_LOG_DEBUG;
  636. av_log(s, loglevel, "Non-monotonous DTS in output stream "
  637. "%d:%d; previous: %"PRId64", current: %"PRId64"; ",
  638. ost->file_index, ost->st->index, ost->last_mux_dts, pkt->dts);
  639. if (exit_on_error) {
  640. av_log(NULL, AV_LOG_FATAL, "aborting.\n");
  641. exit_program(1);
  642. }
  643. av_log(s, loglevel, "changing to %"PRId64". This may result "
  644. "in incorrect timestamps in the output file.\n",
  645. max);
  646. if (pkt->pts >= pkt->dts)
  647. pkt->pts = FFMAX(pkt->pts, max);
  648. pkt->dts = max;
  649. }
  650. }
  651. }
  652. ost->last_mux_dts = pkt->dts;
  653. ost->data_size += pkt->size;
  654. ost->packets_written++;
  655. pkt->stream_index = ost->index;
  656. if (debug_ts) {
  657. av_log(NULL, AV_LOG_INFO, "muxer <- type:%s "
  658. "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s size:%d\n",
  659. av_get_media_type_string(ost->enc_ctx->codec_type),
  660. av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &ost->st->time_base),
  661. av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &ost->st->time_base),
  662. pkt->size
  663. );
  664. }
  665. ret = av_interleaved_write_frame(s, pkt);
  666. if (ret < 0) {
  667. print_error("av_interleaved_write_frame()", ret);
  668. main_return_code = 1;
  669. close_all_output_streams(ost, MUXER_FINISHED | ENCODER_FINISHED, ENCODER_FINISHED);
  670. }
  671. av_packet_unref(pkt);
  672. }
  673. static void close_output_stream(OutputStream *ost)
  674. {
  675. OutputFile *of = output_files[ost->file_index];
  676. ost->finished |= ENCODER_FINISHED;
  677. if (of->shortest) {
  678. int64_t end = av_rescale_q(ost->sync_opts - ost->first_pts, ost->enc_ctx->time_base, AV_TIME_BASE_Q);
  679. of->recording_time = FFMIN(of->recording_time, end);
  680. }
  681. }
  682. static void output_packet(OutputFile *of, AVPacket *pkt, OutputStream *ost)
  683. {
  684. int ret = 0;
  685. /* apply the output bitstream filters, if any */
  686. if (ost->nb_bitstream_filters) {
  687. int idx;
  688. av_packet_split_side_data(pkt);
  689. ret = av_bsf_send_packet(ost->bsf_ctx[0], pkt);
  690. if (ret < 0)
  691. goto finish;
  692. idx = 1;
  693. while (idx) {
  694. /* get a packet from the previous filter up the chain */
  695. ret = av_bsf_receive_packet(ost->bsf_ctx[idx - 1], pkt);
  696. if (ret == AVERROR(EAGAIN)) {
  697. ret = 0;
  698. idx--;
  699. continue;
  700. } else if (ret < 0)
  701. goto finish;
  702. /* HACK! - aac_adtstoasc updates extradata after filtering the first frame when
  703. * the api states this shouldn't happen after init(). Propagate it here to the
  704. * muxer and to the next filters in the chain to workaround this.
  705. * TODO/FIXME - Make aac_adtstoasc use new packet side data instead of changing
  706. * par_out->extradata and adapt muxers accordingly to get rid of this. */
  707. if (!(ost->bsf_extradata_updated[idx - 1] & 1)) {
  708. ret = avcodec_parameters_copy(ost->st->codecpar, ost->bsf_ctx[idx - 1]->par_out);
  709. if (ret < 0)
  710. goto finish;
  711. ost->bsf_extradata_updated[idx - 1] |= 1;
  712. }
  713. /* send it to the next filter down the chain or to the muxer */
  714. if (idx < ost->nb_bitstream_filters) {
  715. /* HACK/FIXME! - See above */
  716. if (!(ost->bsf_extradata_updated[idx] & 2)) {
  717. ret = avcodec_parameters_copy(ost->bsf_ctx[idx]->par_out, ost->bsf_ctx[idx - 1]->par_out);
  718. if (ret < 0)
  719. goto finish;
  720. ost->bsf_extradata_updated[idx] |= 2;
  721. }
  722. ret = av_bsf_send_packet(ost->bsf_ctx[idx], pkt);
  723. if (ret < 0)
  724. goto finish;
  725. idx++;
  726. } else
  727. write_packet(of, pkt, ost);
  728. }
  729. } else
  730. write_packet(of, pkt, ost);
  731. finish:
  732. if (ret < 0 && ret != AVERROR_EOF) {
  733. av_log(NULL, AV_LOG_ERROR, "Error applying bitstream filters to an output "
  734. "packet for stream #%d:%d.\n", ost->file_index, ost->index);
  735. if(exit_on_error)
  736. exit_program(1);
  737. }
  738. }
  739. static int check_recording_time(OutputStream *ost)
  740. {
  741. OutputFile *of = output_files[ost->file_index];
  742. if (of->recording_time != INT64_MAX &&
  743. av_compare_ts(ost->sync_opts - ost->first_pts, ost->enc_ctx->time_base, of->recording_time,
  744. AV_TIME_BASE_Q) >= 0) {
  745. close_output_stream(ost);
  746. return 0;
  747. }
  748. return 1;
  749. }
  750. static void do_audio_out(OutputFile *of, OutputStream *ost,
  751. AVFrame *frame)
  752. {
  753. AVCodecContext *enc = ost->enc_ctx;
  754. AVPacket pkt;
  755. int ret;
  756. av_init_packet(&pkt);
  757. pkt.data = NULL;
  758. pkt.size = 0;
  759. if (!check_recording_time(ost))
  760. return;
  761. if (frame->pts == AV_NOPTS_VALUE || audio_sync_method < 0)
  762. frame->pts = ost->sync_opts;
  763. ost->sync_opts = frame->pts + frame->nb_samples;
  764. ost->samples_encoded += frame->nb_samples;
  765. ost->frames_encoded++;
  766. av_assert0(pkt.size || !pkt.data);
  767. update_benchmark(NULL);
  768. if (debug_ts) {
  769. av_log(NULL, AV_LOG_INFO, "encoder <- type:audio "
  770. "frame_pts:%s frame_pts_time:%s time_base:%d/%d\n",
  771. av_ts2str(frame->pts), av_ts2timestr(frame->pts, &enc->time_base),
  772. enc->time_base.num, enc->time_base.den);
  773. }
  774. ret = avcodec_send_frame(enc, frame);
  775. if (ret < 0)
  776. goto error;
  777. while (1) {
  778. ret = avcodec_receive_packet(enc, &pkt);
  779. if (ret == AVERROR(EAGAIN))
  780. break;
  781. if (ret < 0)
  782. goto error;
  783. update_benchmark("encode_audio %d.%d", ost->file_index, ost->index);
  784. av_packet_rescale_ts(&pkt, enc->time_base, ost->st->time_base);
  785. if (debug_ts) {
  786. av_log(NULL, AV_LOG_INFO, "encoder -> type:audio "
  787. "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
  788. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
  789. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
  790. }
  791. output_packet(of, &pkt, ost);
  792. }
  793. return;
  794. error:
  795. av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
  796. exit_program(1);
  797. }
  798. static void do_subtitle_out(OutputFile *of,
  799. OutputStream *ost,
  800. AVSubtitle *sub)
  801. {
  802. int subtitle_out_max_size = 1024 * 1024;
  803. int subtitle_out_size, nb, i;
  804. AVCodecContext *enc;
  805. AVPacket pkt;
  806. int64_t pts;
  807. if (sub->pts == AV_NOPTS_VALUE) {
  808. av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
  809. if (exit_on_error)
  810. exit_program(1);
  811. return;
  812. }
  813. enc = ost->enc_ctx;
  814. if (!subtitle_out) {
  815. subtitle_out = av_malloc(subtitle_out_max_size);
  816. if (!subtitle_out) {
  817. av_log(NULL, AV_LOG_FATAL, "Failed to allocate subtitle_out\n");
  818. exit_program(1);
  819. }
  820. }
  821. /* Note: DVB subtitle need one packet to draw them and one other
  822. packet to clear them */
  823. /* XXX: signal it in the codec context ? */
  824. if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
  825. nb = 2;
  826. else
  827. nb = 1;
  828. /* shift timestamp to honor -ss and make check_recording_time() work with -t */
  829. pts = sub->pts;
  830. if (output_files[ost->file_index]->start_time != AV_NOPTS_VALUE)
  831. pts -= output_files[ost->file_index]->start_time;
  832. for (i = 0; i < nb; i++) {
  833. unsigned save_num_rects = sub->num_rects;
  834. ost->sync_opts = av_rescale_q(pts, AV_TIME_BASE_Q, enc->time_base);
  835. if (!check_recording_time(ost))
  836. return;
  837. sub->pts = pts;
  838. // start_display_time is required to be 0
  839. sub->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
  840. sub->end_display_time -= sub->start_display_time;
  841. sub->start_display_time = 0;
  842. if (i == 1)
  843. sub->num_rects = 0;
  844. ost->frames_encoded++;
  845. subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
  846. subtitle_out_max_size, sub);
  847. if (i == 1)
  848. sub->num_rects = save_num_rects;
  849. if (subtitle_out_size < 0) {
  850. av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
  851. exit_program(1);
  852. }
  853. av_init_packet(&pkt);
  854. pkt.data = subtitle_out;
  855. pkt.size = subtitle_out_size;
  856. pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
  857. pkt.duration = av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, ost->st->time_base);
  858. if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
  859. /* XXX: the pts correction is handled here. Maybe handling
  860. it in the codec would be better */
  861. if (i == 0)
  862. pkt.pts += 90 * sub->start_display_time;
  863. else
  864. pkt.pts += 90 * sub->end_display_time;
  865. }
  866. pkt.dts = pkt.pts;
  867. output_packet(of, &pkt, ost);
  868. }
  869. }
  870. static void do_video_out(OutputFile *of,
  871. OutputStream *ost,
  872. AVFrame *next_picture,
  873. double sync_ipts)
  874. {
  875. int ret, format_video_sync;
  876. AVPacket pkt;
  877. AVCodecContext *enc = ost->enc_ctx;
  878. AVCodecParameters *mux_par = ost->st->codecpar;
  879. int nb_frames, nb0_frames, i;
  880. double delta, delta0;
  881. double duration = 0;
  882. int frame_size = 0;
  883. InputStream *ist = NULL;
  884. AVFilterContext *filter = ost->filter->filter;
  885. if (ost->source_index >= 0)
  886. ist = input_streams[ost->source_index];
  887. if (filter->inputs[0]->frame_rate.num > 0 &&
  888. filter->inputs[0]->frame_rate.den > 0)
  889. duration = 1/(av_q2d(filter->inputs[0]->frame_rate) * av_q2d(enc->time_base));
  890. if(ist && ist->st->start_time != AV_NOPTS_VALUE && ist->st->first_dts != AV_NOPTS_VALUE && ost->frame_rate.num)
  891. duration = FFMIN(duration, 1/(av_q2d(ost->frame_rate) * av_q2d(enc->time_base)));
  892. if (!ost->filters_script &&
  893. !ost->filters &&
  894. next_picture &&
  895. ist &&
  896. lrintf(av_frame_get_pkt_duration(next_picture) * av_q2d(ist->st->time_base) / av_q2d(enc->time_base)) > 0) {
  897. duration = lrintf(av_frame_get_pkt_duration(next_picture) * av_q2d(ist->st->time_base) / av_q2d(enc->time_base));
  898. }
  899. if (!next_picture) {
  900. //end, flushing
  901. nb0_frames = nb_frames = mid_pred(ost->last_nb0_frames[0],
  902. ost->last_nb0_frames[1],
  903. ost->last_nb0_frames[2]);
  904. } else {
  905. delta0 = sync_ipts - ost->sync_opts; // delta0 is the "drift" between the input frame (next_picture) and where it would fall in the output.
  906. delta = delta0 + duration;
  907. /* by default, we output a single frame */
  908. nb0_frames = 0; // tracks the number of times the PREVIOUS frame should be duplicated, mostly for variable framerate (VFR)
  909. nb_frames = 1;
  910. format_video_sync = video_sync_method;
  911. if (format_video_sync == VSYNC_AUTO) {
  912. if(!strcmp(of->ctx->oformat->name, "avi")) {
  913. format_video_sync = VSYNC_VFR;
  914. } else
  915. format_video_sync = (of->ctx->oformat->flags & AVFMT_VARIABLE_FPS) ? ((of->ctx->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH : VSYNC_VFR) : VSYNC_CFR;
  916. if ( ist
  917. && format_video_sync == VSYNC_CFR
  918. && input_files[ist->file_index]->ctx->nb_streams == 1
  919. && input_files[ist->file_index]->input_ts_offset == 0) {
  920. format_video_sync = VSYNC_VSCFR;
  921. }
  922. if (format_video_sync == VSYNC_CFR && copy_ts) {
  923. format_video_sync = VSYNC_VSCFR;
  924. }
  925. }
  926. ost->is_cfr = (format_video_sync == VSYNC_CFR || format_video_sync == VSYNC_VSCFR);
  927. if (delta0 < 0 &&
  928. delta > 0 &&
  929. format_video_sync != VSYNC_PASSTHROUGH &&
  930. format_video_sync != VSYNC_DROP) {
  931. if (delta0 < -0.6) {
  932. av_log(NULL, AV_LOG_WARNING, "Past duration %f too large\n", -delta0);
  933. } else
  934. av_log(NULL, AV_LOG_DEBUG, "Clipping frame in rate conversion by %f\n", -delta0);
  935. sync_ipts = ost->sync_opts;
  936. duration += delta0;
  937. delta0 = 0;
  938. }
  939. switch (format_video_sync) {
  940. case VSYNC_VSCFR:
  941. if (ost->frame_number == 0 && delta0 >= 0.5) {
  942. av_log(NULL, AV_LOG_DEBUG, "Not duplicating %d initial frames\n", (int)lrintf(delta0));
  943. delta = duration;
  944. delta0 = 0;
  945. ost->sync_opts = lrint(sync_ipts);
  946. }
  947. case VSYNC_CFR:
  948. // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
  949. if (frame_drop_threshold && delta < frame_drop_threshold && ost->frame_number) {
  950. nb_frames = 0;
  951. } else if (delta < -1.1)
  952. nb_frames = 0;
  953. else if (delta > 1.1) {
  954. nb_frames = lrintf(delta);
  955. if (delta0 > 1.1)
  956. nb0_frames = lrintf(delta0 - 0.6);
  957. }
  958. break;
  959. case VSYNC_VFR:
  960. if (delta <= -0.6)
  961. nb_frames = 0;
  962. else if (delta > 0.6)
  963. ost->sync_opts = lrint(sync_ipts);
  964. break;
  965. case VSYNC_DROP:
  966. case VSYNC_PASSTHROUGH:
  967. ost->sync_opts = lrint(sync_ipts);
  968. break;
  969. default:
  970. av_assert0(0);
  971. }
  972. }
  973. nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
  974. nb0_frames = FFMIN(nb0_frames, nb_frames);
  975. memmove(ost->last_nb0_frames + 1,
  976. ost->last_nb0_frames,
  977. sizeof(ost->last_nb0_frames[0]) * (FF_ARRAY_ELEMS(ost->last_nb0_frames) - 1));
  978. ost->last_nb0_frames[0] = nb0_frames;
  979. if (nb0_frames == 0 && ost->last_dropped) {
  980. nb_frames_drop++;
  981. av_log(NULL, AV_LOG_VERBOSE,
  982. "*** dropping frame %d from stream %d at ts %"PRId64"\n",
  983. ost->frame_number, ost->st->index, ost->last_frame->pts);
  984. }
  985. if (nb_frames > (nb0_frames && ost->last_dropped) + (nb_frames > nb0_frames)) {
  986. if (nb_frames > dts_error_threshold * 30) {
  987. av_log(NULL, AV_LOG_ERROR, "%d frame duplication too large, skipping\n", nb_frames - 1);
  988. nb_frames_drop++;
  989. return;
  990. }
  991. nb_frames_dup += nb_frames - (nb0_frames && ost->last_dropped) - (nb_frames > nb0_frames);
  992. av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);
  993. if (nb_frames_dup > dup_warning) {
  994. av_log(NULL, AV_LOG_WARNING, "More than %d frames duplicated\n", dup_warning);
  995. dup_warning *= 10;
  996. }
  997. }
  998. ost->last_dropped = nb_frames == nb0_frames && next_picture;
  999. /* duplicates frame if needed */
  1000. for (i = 0; i < nb_frames; i++) {
  1001. AVFrame *in_picture;
  1002. av_init_packet(&pkt);
  1003. pkt.data = NULL;
  1004. pkt.size = 0;
  1005. if (i < nb0_frames && ost->last_frame) {
  1006. in_picture = ost->last_frame;
  1007. } else
  1008. in_picture = next_picture;
  1009. if (!in_picture)
  1010. return;
  1011. in_picture->pts = ost->sync_opts;
  1012. #if 1
  1013. if (!check_recording_time(ost))
  1014. #else
  1015. if (ost->frame_number >= ost->max_frames)
  1016. #endif
  1017. return;
  1018. #if FF_API_LAVF_FMT_RAWPICTURE
  1019. if (of->ctx->oformat->flags & AVFMT_RAWPICTURE &&
  1020. enc->codec->id == AV_CODEC_ID_RAWVIDEO) {
  1021. /* raw pictures are written as AVPicture structure to
  1022. avoid any copies. We support temporarily the older
  1023. method. */
  1024. if (in_picture->interlaced_frame)
  1025. mux_par->field_order = in_picture->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
  1026. else
  1027. mux_par->field_order = AV_FIELD_PROGRESSIVE;
  1028. pkt.data = (uint8_t *)in_picture;
  1029. pkt.size = sizeof(AVPicture);
  1030. pkt.pts = av_rescale_q(in_picture->pts, enc->time_base, ost->st->time_base);
  1031. pkt.flags |= AV_PKT_FLAG_KEY;
  1032. output_packet(of, &pkt, ost);
  1033. } else
  1034. #endif
  1035. {
  1036. int forced_keyframe = 0;
  1037. double pts_time;
  1038. if (enc->flags & (AV_CODEC_FLAG_INTERLACED_DCT | AV_CODEC_FLAG_INTERLACED_ME) &&
  1039. ost->top_field_first >= 0)
  1040. in_picture->top_field_first = !!ost->top_field_first;
  1041. if (in_picture->interlaced_frame) {
  1042. if (enc->codec->id == AV_CODEC_ID_MJPEG)
  1043. mux_par->field_order = in_picture->top_field_first ? AV_FIELD_TT:AV_FIELD_BB;
  1044. else
  1045. mux_par->field_order = in_picture->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
  1046. } else
  1047. mux_par->field_order = AV_FIELD_PROGRESSIVE;
  1048. in_picture->quality = enc->global_quality;
  1049. in_picture->pict_type = 0;
  1050. pts_time = in_picture->pts != AV_NOPTS_VALUE ?
  1051. in_picture->pts * av_q2d(enc->time_base) : NAN;
  1052. if (ost->forced_kf_index < ost->forced_kf_count &&
  1053. in_picture->pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
  1054. ost->forced_kf_index++;
  1055. forced_keyframe = 1;
  1056. } else if (ost->forced_keyframes_pexpr) {
  1057. double res;
  1058. ost->forced_keyframes_expr_const_values[FKF_T] = pts_time;
  1059. res = av_expr_eval(ost->forced_keyframes_pexpr,
  1060. ost->forced_keyframes_expr_const_values, NULL);
  1061. ff_dlog(NULL, "force_key_frame: n:%f n_forced:%f prev_forced_n:%f t:%f prev_forced_t:%f -> res:%f\n",
  1062. ost->forced_keyframes_expr_const_values[FKF_N],
  1063. ost->forced_keyframes_expr_const_values[FKF_N_FORCED],
  1064. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N],
  1065. ost->forced_keyframes_expr_const_values[FKF_T],
  1066. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T],
  1067. res);
  1068. if (res) {
  1069. forced_keyframe = 1;
  1070. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] =
  1071. ost->forced_keyframes_expr_const_values[FKF_N];
  1072. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] =
  1073. ost->forced_keyframes_expr_const_values[FKF_T];
  1074. ost->forced_keyframes_expr_const_values[FKF_N_FORCED] += 1;
  1075. }
  1076. ost->forced_keyframes_expr_const_values[FKF_N] += 1;
  1077. } else if ( ost->forced_keyframes
  1078. && !strncmp(ost->forced_keyframes, "source", 6)
  1079. && in_picture->key_frame==1) {
  1080. forced_keyframe = 1;
  1081. }
  1082. if (forced_keyframe) {
  1083. in_picture->pict_type = AV_PICTURE_TYPE_I;
  1084. av_log(NULL, AV_LOG_DEBUG, "Forced keyframe at time %f\n", pts_time);
  1085. }
  1086. update_benchmark(NULL);
  1087. if (debug_ts) {
  1088. av_log(NULL, AV_LOG_INFO, "encoder <- type:video "
  1089. "frame_pts:%s frame_pts_time:%s time_base:%d/%d\n",
  1090. av_ts2str(in_picture->pts), av_ts2timestr(in_picture->pts, &enc->time_base),
  1091. enc->time_base.num, enc->time_base.den);
  1092. }
  1093. ost->frames_encoded++;
  1094. ret = avcodec_send_frame(enc, in_picture);
  1095. if (ret < 0)
  1096. goto error;
  1097. while (1) {
  1098. ret = avcodec_receive_packet(enc, &pkt);
  1099. update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
  1100. if (ret == AVERROR(EAGAIN))
  1101. break;
  1102. if (ret < 0)
  1103. goto error;
  1104. if (debug_ts) {
  1105. av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
  1106. "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
  1107. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &enc->time_base),
  1108. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &enc->time_base));
  1109. }
  1110. if (pkt.pts == AV_NOPTS_VALUE && !(enc->codec->capabilities & AV_CODEC_CAP_DELAY))
  1111. pkt.pts = ost->sync_opts;
  1112. av_packet_rescale_ts(&pkt, enc->time_base, ost->st->time_base);
  1113. if (debug_ts) {
  1114. av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
  1115. "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
  1116. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
  1117. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
  1118. }
  1119. frame_size = pkt.size;
  1120. output_packet(of, &pkt, ost);
  1121. /* if two pass, output log */
  1122. if (ost->logfile && enc->stats_out) {
  1123. fprintf(ost->logfile, "%s", enc->stats_out);
  1124. }
  1125. }
  1126. }
  1127. ost->sync_opts++;
  1128. /*
  1129. * For video, number of frames in == number of packets out.
  1130. * But there may be reordering, so we can't throw away frames on encoder
  1131. * flush, we need to limit them here, before they go into encoder.
  1132. */
  1133. ost->frame_number++;
  1134. if (vstats_filename && frame_size)
  1135. do_video_stats(ost, frame_size);
  1136. }
  1137. if (!ost->last_frame)
  1138. ost->last_frame = av_frame_alloc();
  1139. av_frame_unref(ost->last_frame);
  1140. if (next_picture && ost->last_frame)
  1141. av_frame_ref(ost->last_frame, next_picture);
  1142. else
  1143. av_frame_free(&ost->last_frame);
  1144. return;
  1145. error:
  1146. av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
  1147. exit_program(1);
  1148. }
  1149. static double psnr(double d)
  1150. {
  1151. return -10.0 * log10(d);
  1152. }
  1153. static void do_video_stats(OutputStream *ost, int frame_size)
  1154. {
  1155. AVCodecContext *enc;
  1156. int frame_number;
  1157. double ti1, bitrate, avg_bitrate;
  1158. /* this is executed just the first time do_video_stats is called */
  1159. if (!vstats_file) {
  1160. vstats_file = fopen(vstats_filename, "w");
  1161. if (!vstats_file) {
  1162. perror("fopen");
  1163. exit_program(1);
  1164. }
  1165. }
  1166. enc = ost->enc_ctx;
  1167. if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  1168. frame_number = ost->st->nb_frames;
  1169. fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number,
  1170. ost->quality / (float)FF_QP2LAMBDA);
  1171. if (ost->error[0]>=0 && (enc->flags & AV_CODEC_FLAG_PSNR))
  1172. fprintf(vstats_file, "PSNR= %6.2f ", psnr(ost->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
  1173. fprintf(vstats_file,"f_size= %6d ", frame_size);
  1174. /* compute pts value */
  1175. ti1 = av_stream_get_end_pts(ost->st) * av_q2d(ost->st->time_base);
  1176. if (ti1 < 0.01)
  1177. ti1 = 0.01;
  1178. bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
  1179. avg_bitrate = (double)(ost->data_size * 8) / ti1 / 1000.0;
  1180. fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
  1181. (double)ost->data_size / 1024, ti1, bitrate, avg_bitrate);
  1182. fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(ost->pict_type));
  1183. }
  1184. }
  1185. static void finish_output_stream(OutputStream *ost)
  1186. {
  1187. OutputFile *of = output_files[ost->file_index];
  1188. int i;
  1189. ost->finished = ENCODER_FINISHED | MUXER_FINISHED;
  1190. if (of->shortest) {
  1191. for (i = 0; i < of->ctx->nb_streams; i++)
  1192. output_streams[of->ost_index + i]->finished = ENCODER_FINISHED | MUXER_FINISHED;
  1193. }
  1194. }
  1195. /**
  1196. * Get and encode new output from any of the filtergraphs, without causing
  1197. * activity.
  1198. *
  1199. * @return 0 for success, <0 for severe errors
  1200. */
  1201. static int reap_filters(int flush)
  1202. {
  1203. AVFrame *filtered_frame = NULL;
  1204. int i;
  1205. /* Reap all buffers present in the buffer sinks */
  1206. for (i = 0; i < nb_output_streams; i++) {
  1207. OutputStream *ost = output_streams[i];
  1208. OutputFile *of = output_files[ost->file_index];
  1209. AVFilterContext *filter;
  1210. AVCodecContext *enc = ost->enc_ctx;
  1211. int ret = 0;
  1212. if (!ost->filter)
  1213. continue;
  1214. filter = ost->filter->filter;
  1215. if (!ost->filtered_frame && !(ost->filtered_frame = av_frame_alloc())) {
  1216. return AVERROR(ENOMEM);
  1217. }
  1218. filtered_frame = ost->filtered_frame;
  1219. while (1) {
  1220. double float_pts = AV_NOPTS_VALUE; // this is identical to filtered_frame.pts but with higher precision
  1221. ret = av_buffersink_get_frame_flags(filter, filtered_frame,
  1222. AV_BUFFERSINK_FLAG_NO_REQUEST);
  1223. if (ret < 0) {
  1224. if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) {
  1225. av_log(NULL, AV_LOG_WARNING,
  1226. "Error in av_buffersink_get_frame_flags(): %s\n", av_err2str(ret));
  1227. } else if (flush && ret == AVERROR_EOF) {
  1228. if (filter->inputs[0]->type == AVMEDIA_TYPE_VIDEO)
  1229. do_video_out(of, ost, NULL, AV_NOPTS_VALUE);
  1230. }
  1231. break;
  1232. }
  1233. if (ost->finished) {
  1234. av_frame_unref(filtered_frame);
  1235. continue;
  1236. }
  1237. if (filtered_frame->pts != AV_NOPTS_VALUE) {
  1238. int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
  1239. AVRational tb = enc->time_base;
  1240. int extra_bits = av_clip(29 - av_log2(tb.den), 0, 16);
  1241. tb.den <<= extra_bits;
  1242. float_pts =
  1243. av_rescale_q(filtered_frame->pts, filter->inputs[0]->time_base, tb) -
  1244. av_rescale_q(start_time, AV_TIME_BASE_Q, tb);
  1245. float_pts /= 1 << extra_bits;
  1246. // avoid exact midoints to reduce the chance of rounding differences, this can be removed in case the fps code is changed to work with integers
  1247. float_pts += FFSIGN(float_pts) * 1.0 / (1<<17);
  1248. filtered_frame->pts =
  1249. av_rescale_q(filtered_frame->pts, filter->inputs[0]->time_base, enc->time_base) -
  1250. av_rescale_q(start_time, AV_TIME_BASE_Q, enc->time_base);
  1251. }
  1252. //if (ost->source_index >= 0)
  1253. // *filtered_frame= *input_streams[ost->source_index]->decoded_frame; //for me_threshold
  1254. switch (filter->inputs[0]->type) {
  1255. case AVMEDIA_TYPE_VIDEO:
  1256. if (!ost->frame_aspect_ratio.num)
  1257. enc->sample_aspect_ratio = filtered_frame->sample_aspect_ratio;
  1258. if (debug_ts) {
  1259. av_log(NULL, AV_LOG_INFO, "filter -> pts:%s pts_time:%s exact:%f time_base:%d/%d\n",
  1260. av_ts2str(filtered_frame->pts), av_ts2timestr(filtered_frame->pts, &enc->time_base),
  1261. float_pts,
  1262. enc->time_base.num, enc->time_base.den);
  1263. }
  1264. do_video_out(of, ost, filtered_frame, float_pts);
  1265. break;
  1266. case AVMEDIA_TYPE_AUDIO:
  1267. if (!(enc->codec->capabilities & AV_CODEC_CAP_PARAM_CHANGE) &&
  1268. enc->channels != av_frame_get_channels(filtered_frame)) {
  1269. av_log(NULL, AV_LOG_ERROR,
  1270. "Audio filter graph output is not normalized and encoder does not support parameter changes\n");
  1271. break;
  1272. }
  1273. do_audio_out(of, ost, filtered_frame);
  1274. break;
  1275. default:
  1276. // TODO support subtitle filters
  1277. av_assert0(0);
  1278. }
  1279. av_frame_unref(filtered_frame);
  1280. }
  1281. }
  1282. return 0;
  1283. }
  1284. static void print_final_stats(int64_t total_size)
  1285. {
  1286. uint64_t video_size = 0, audio_size = 0, extra_size = 0, other_size = 0;
  1287. uint64_t subtitle_size = 0;
  1288. uint64_t data_size = 0;
  1289. float percent = -1.0;
  1290. int i, j;
  1291. int pass1_used = 1;
  1292. for (i = 0; i < nb_output_streams; i++) {
  1293. OutputStream *ost = output_streams[i];
  1294. switch (ost->enc_ctx->codec_type) {
  1295. case AVMEDIA_TYPE_VIDEO: video_size += ost->data_size; break;
  1296. case AVMEDIA_TYPE_AUDIO: audio_size += ost->data_size; break;
  1297. case AVMEDIA_TYPE_SUBTITLE: subtitle_size += ost->data_size; break;
  1298. default: other_size += ost->data_size; break;
  1299. }
  1300. extra_size += ost->enc_ctx->extradata_size;
  1301. data_size += ost->data_size;
  1302. if ( (ost->enc_ctx->flags & (AV_CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))
  1303. != AV_CODEC_FLAG_PASS1)
  1304. pass1_used = 0;
  1305. }
  1306. if (data_size && total_size>0 && total_size >= data_size)
  1307. percent = 100.0 * (total_size - data_size) / data_size;
  1308. av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB subtitle:%1.0fkB other streams:%1.0fkB global headers:%1.0fkB muxing overhead: ",
  1309. video_size / 1024.0,
  1310. audio_size / 1024.0,
  1311. subtitle_size / 1024.0,
  1312. other_size / 1024.0,
  1313. extra_size / 1024.0);
  1314. if (percent >= 0.0)
  1315. av_log(NULL, AV_LOG_INFO, "%f%%", percent);
  1316. else
  1317. av_log(NULL, AV_LOG_INFO, "unknown");
  1318. av_log(NULL, AV_LOG_INFO, "\n");
  1319. /* print verbose per-stream stats */
  1320. for (i = 0; i < nb_input_files; i++) {
  1321. InputFile *f = input_files[i];
  1322. uint64_t total_packets = 0, total_size = 0;
  1323. av_log(NULL, AV_LOG_VERBOSE, "Input file #%d (%s):\n",
  1324. i, f->ctx->filename);
  1325. for (j = 0; j < f->nb_streams; j++) {
  1326. InputStream *ist = input_streams[f->ist_index + j];
  1327. enum AVMediaType type = ist->dec_ctx->codec_type;
  1328. total_size += ist->data_size;
  1329. total_packets += ist->nb_packets;
  1330. av_log(NULL, AV_LOG_VERBOSE, " Input stream #%d:%d (%s): ",
  1331. i, j, media_type_string(type));
  1332. av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" packets read (%"PRIu64" bytes); ",
  1333. ist->nb_packets, ist->data_size);
  1334. if (ist->decoding_needed) {
  1335. av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" frames decoded",
  1336. ist->frames_decoded);
  1337. if (type == AVMEDIA_TYPE_AUDIO)
  1338. av_log(NULL, AV_LOG_VERBOSE, " (%"PRIu64" samples)", ist->samples_decoded);
  1339. av_log(NULL, AV_LOG_VERBOSE, "; ");
  1340. }
  1341. av_log(NULL, AV_LOG_VERBOSE, "\n");
  1342. }
  1343. av_log(NULL, AV_LOG_VERBOSE, " Total: %"PRIu64" packets (%"PRIu64" bytes) demuxed\n",
  1344. total_packets, total_size);
  1345. }
  1346. for (i = 0; i < nb_output_files; i++) {
  1347. OutputFile *of = output_files[i];
  1348. uint64_t total_packets = 0, total_size = 0;
  1349. av_log(NULL, AV_LOG_VERBOSE, "Output file #%d (%s):\n",
  1350. i, of->ctx->filename);
  1351. for (j = 0; j < of->ctx->nb_streams; j++) {
  1352. OutputStream *ost = output_streams[of->ost_index + j];
  1353. enum AVMediaType type = ost->enc_ctx->codec_type;
  1354. total_size += ost->data_size;
  1355. total_packets += ost->packets_written;
  1356. av_log(NULL, AV_LOG_VERBOSE, " Output stream #%d:%d (%s): ",
  1357. i, j, media_type_string(type));
  1358. if (ost->encoding_needed) {
  1359. av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" frames encoded",
  1360. ost->frames_encoded);
  1361. if (type == AVMEDIA_TYPE_AUDIO)
  1362. av_log(NULL, AV_LOG_VERBOSE, " (%"PRIu64" samples)", ost->samples_encoded);
  1363. av_log(NULL, AV_LOG_VERBOSE, "; ");
  1364. }
  1365. av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" packets muxed (%"PRIu64" bytes); ",
  1366. ost->packets_written, ost->data_size);
  1367. av_log(NULL, AV_LOG_VERBOSE, "\n");
  1368. }
  1369. av_log(NULL, AV_LOG_VERBOSE, " Total: %"PRIu64" packets (%"PRIu64" bytes) muxed\n",
  1370. total_packets, total_size);
  1371. }
  1372. if(video_size + data_size + audio_size + subtitle_size + extra_size == 0){
  1373. av_log(NULL, AV_LOG_WARNING, "Output file is empty, nothing was encoded ");
  1374. if (pass1_used) {
  1375. av_log(NULL, AV_LOG_WARNING, "\n");
  1376. } else {
  1377. av_log(NULL, AV_LOG_WARNING, "(check -ss / -t / -frames parameters if used)\n");
  1378. }
  1379. }
  1380. }
  1381. static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
  1382. {
  1383. char buf[1024];
  1384. AVBPrint buf_script;
  1385. OutputStream *ost;
  1386. AVFormatContext *oc;
  1387. int64_t total_size;
  1388. AVCodecContext *enc;
  1389. int frame_number, vid, i;
  1390. double bitrate;
  1391. double speed;
  1392. int64_t pts = INT64_MIN + 1;
  1393. static int64_t last_time = -1;
  1394. static int qp_histogram[52];
  1395. int hours, mins, secs, us;
  1396. int ret;
  1397. float t;
  1398. if (!print_stats && !is_last_report && !progress_avio)
  1399. return;
  1400. if (!is_last_report) {
  1401. if (last_time == -1) {
  1402. last_time = cur_time;
  1403. return;
  1404. }
  1405. if ((cur_time - last_time) < 500000)
  1406. return;
  1407. last_time = cur_time;
  1408. }
  1409. t = (cur_time-timer_start) / 1000000.0;
  1410. oc = output_files[0]->ctx;
  1411. total_size = avio_size(oc->pb);
  1412. if (total_size <= 0) // FIXME improve avio_size() so it works with non seekable output too
  1413. total_size = avio_tell(oc->pb);
  1414. buf[0] = '\0';
  1415. vid = 0;
  1416. av_bprint_init(&buf_script, 0, 1);
  1417. for (i = 0; i < nb_output_streams; i++) {
  1418. float q = -1;
  1419. ost = output_streams[i];
  1420. enc = ost->enc_ctx;
  1421. if (!ost->stream_copy)
  1422. q = ost->quality / (float) FF_QP2LAMBDA;
  1423. if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  1424. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
  1425. av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
  1426. ost->file_index, ost->index, q);
  1427. }
  1428. if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  1429. float fps;
  1430. frame_number = ost->frame_number;
  1431. fps = t > 1 ? frame_number / t : 0;
  1432. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3.*f q=%3.1f ",
  1433. frame_number, fps < 9.95, fps, q);
  1434. av_bprintf(&buf_script, "frame=%d\n", frame_number);
  1435. av_bprintf(&buf_script, "fps=%.1f\n", fps);
  1436. av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
  1437. ost->file_index, ost->index, q);
  1438. if (is_last_report)
  1439. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
  1440. if (qp_hist) {
  1441. int j;
  1442. int qp = lrintf(q);
  1443. if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
  1444. qp_histogram[qp]++;
  1445. for (j = 0; j < 32; j++)
  1446. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", av_log2(qp_histogram[j] + 1));
  1447. }
  1448. if ((enc->flags & AV_CODEC_FLAG_PSNR) && (ost->pict_type != AV_PICTURE_TYPE_NONE || is_last_report)) {
  1449. int j;
  1450. double error, error_sum = 0;
  1451. double scale, scale_sum = 0;
  1452. double p;
  1453. char type[3] = { 'Y','U','V' };
  1454. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
  1455. for (j = 0; j < 3; j++) {
  1456. if (is_last_report) {
  1457. error = enc->error[j];
  1458. scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
  1459. } else {
  1460. error = ost->error[j];
  1461. scale = enc->width * enc->height * 255.0 * 255.0;
  1462. }
  1463. if (j)
  1464. scale /= 4;
  1465. error_sum += error;
  1466. scale_sum += scale;
  1467. p = psnr(error / scale);
  1468. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], p);
  1469. av_bprintf(&buf_script, "stream_%d_%d_psnr_%c=%2.2f\n",
  1470. ost->file_index, ost->index, type[j] | 32, p);
  1471. }
  1472. p = psnr(error_sum / scale_sum);
  1473. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
  1474. av_bprintf(&buf_script, "stream_%d_%d_psnr_all=%2.2f\n",
  1475. ost->file_index, ost->index, p);
  1476. }
  1477. vid = 1;
  1478. }
  1479. /* compute min output value */
  1480. if (av_stream_get_end_pts(ost->st) != AV_NOPTS_VALUE)
  1481. pts = FFMAX(pts, av_rescale_q(av_stream_get_end_pts(ost->st),
  1482. ost->st->time_base, AV_TIME_BASE_Q));
  1483. if (is_last_report)
  1484. nb_frames_drop += ost->last_dropped;
  1485. }
  1486. secs = FFABS(pts) / AV_TIME_BASE;
  1487. us = FFABS(pts) % AV_TIME_BASE;
  1488. mins = secs / 60;
  1489. secs %= 60;
  1490. hours = mins / 60;
  1491. mins %= 60;
  1492. bitrate = pts && total_size >= 0 ? total_size * 8 / (pts / 1000.0) : -1;
  1493. speed = t != 0.0 ? (double)pts / AV_TIME_BASE / t : -1;
  1494. if (total_size < 0) snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  1495. "size=N/A time=");
  1496. else snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  1497. "size=%8.0fkB time=", total_size / 1024.0);
  1498. if (pts < 0)
  1499. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "-");
  1500. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  1501. "%02d:%02d:%02d.%02d ", hours, mins, secs,
  1502. (100 * us) / AV_TIME_BASE);
  1503. if (bitrate < 0) {
  1504. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),"bitrate=N/A");
  1505. av_bprintf(&buf_script, "bitrate=N/A\n");
  1506. }else{
  1507. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),"bitrate=%6.1fkbits/s", bitrate);
  1508. av_bprintf(&buf_script, "bitrate=%6.1fkbits/s\n", bitrate);
  1509. }
  1510. if (total_size < 0) av_bprintf(&buf_script, "total_size=N/A\n");
  1511. else av_bprintf(&buf_script, "total_size=%"PRId64"\n", total_size);
  1512. av_bprintf(&buf_script, "out_time_ms=%"PRId64"\n", pts);
  1513. av_bprintf(&buf_script, "out_time=%02d:%02d:%02d.%06d\n",
  1514. hours, mins, secs, us);
  1515. if (nb_frames_dup || nb_frames_drop)
  1516. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
  1517. nb_frames_dup, nb_frames_drop);
  1518. av_bprintf(&buf_script, "dup_frames=%d\n", nb_frames_dup);
  1519. av_bprintf(&buf_script, "drop_frames=%d\n", nb_frames_drop);
  1520. if (speed < 0) {
  1521. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf)," speed=N/A");
  1522. av_bprintf(&buf_script, "speed=N/A\n");
  1523. } else {
  1524. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf)," speed=%4.3gx", speed);
  1525. av_bprintf(&buf_script, "speed=%4.3gx\n", speed);
  1526. }
  1527. if (print_stats || is_last_report) {
  1528. const char end = is_last_report ? '\n' : '\r';
  1529. if (print_stats==1 && AV_LOG_INFO > av_log_get_level()) {
  1530. fprintf(stderr, "%s %c", buf, end);
  1531. } else
  1532. av_log(NULL, AV_LOG_INFO, "%s %c", buf, end);
  1533. fflush(stderr);
  1534. }
  1535. if (progress_avio) {
  1536. av_bprintf(&buf_script, "progress=%s\n",
  1537. is_last_report ? "end" : "continue");
  1538. avio_write(progress_avio, buf_script.str,
  1539. FFMIN(buf_script.len, buf_script.size - 1));
  1540. avio_flush(progress_avio);
  1541. av_bprint_finalize(&buf_script, NULL);
  1542. if (is_last_report) {
  1543. if ((ret = avio_closep(&progress_avio)) < 0)
  1544. av_log(NULL, AV_LOG_ERROR,
  1545. "Error closing progress log, loss of information possible: %s\n", av_err2str(ret));
  1546. }
  1547. }
  1548. if (is_last_report)
  1549. print_final_stats(total_size);
  1550. }
  1551. static void flush_encoders(void)
  1552. {
  1553. int i, ret;
  1554. for (i = 0; i < nb_output_streams; i++) {
  1555. OutputStream *ost = output_streams[i];
  1556. AVCodecContext *enc = ost->enc_ctx;
  1557. OutputFile *of = output_files[ost->file_index];
  1558. int stop_encoding = 0;
  1559. if (!ost->encoding_needed)
  1560. continue;
  1561. if (enc->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
  1562. continue;
  1563. #if FF_API_LAVF_FMT_RAWPICTURE
  1564. if (enc->codec_type == AVMEDIA_TYPE_VIDEO && (of->ctx->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == AV_CODEC_ID_RAWVIDEO)
  1565. continue;
  1566. #endif
  1567. if (enc->codec_type != AVMEDIA_TYPE_VIDEO && enc->codec_type != AVMEDIA_TYPE_AUDIO)
  1568. continue;
  1569. avcodec_send_frame(enc, NULL);
  1570. for (;;) {
  1571. const char *desc = NULL;
  1572. switch (enc->codec_type) {
  1573. case AVMEDIA_TYPE_AUDIO:
  1574. desc = "audio";
  1575. break;
  1576. case AVMEDIA_TYPE_VIDEO:
  1577. desc = "video";
  1578. break;
  1579. default:
  1580. av_assert0(0);
  1581. }
  1582. if (1) {
  1583. AVPacket pkt;
  1584. int pkt_size;
  1585. av_init_packet(&pkt);
  1586. pkt.data = NULL;
  1587. pkt.size = 0;
  1588. update_benchmark(NULL);
  1589. ret = avcodec_receive_packet(enc, &pkt);
  1590. update_benchmark("flush_%s %d.%d", desc, ost->file_index, ost->index);
  1591. if (ret < 0 && ret != AVERROR_EOF) {
  1592. av_log(NULL, AV_LOG_FATAL, "%s encoding failed: %s\n",
  1593. desc,
  1594. av_err2str(ret));
  1595. exit_program(1);
  1596. }
  1597. if (ost->logfile && enc->stats_out) {
  1598. fprintf(ost->logfile, "%s", enc->stats_out);
  1599. }
  1600. if (ret == AVERROR_EOF) {
  1601. stop_encoding = 1;
  1602. break;
  1603. }
  1604. if (ost->finished & MUXER_FINISHED) {
  1605. av_packet_unref(&pkt);
  1606. continue;
  1607. }
  1608. av_packet_rescale_ts(&pkt, enc->time_base, ost->st->time_base);
  1609. pkt_size = pkt.size;
  1610. output_packet(of, &pkt, ost);
  1611. if (ost->enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO && vstats_filename) {
  1612. do_video_stats(ost, pkt_size);
  1613. }
  1614. }
  1615. if (stop_encoding)
  1616. break;
  1617. }
  1618. }
  1619. }
  1620. /*
  1621. * Check whether a packet from ist should be written into ost at this time
  1622. */
  1623. static int check_output_constraints(InputStream *ist, OutputStream *ost)
  1624. {
  1625. OutputFile *of = output_files[ost->file_index];
  1626. int ist_index = input_files[ist->file_index]->ist_index + ist->st->index;
  1627. if (ost->source_index != ist_index)
  1628. return 0;
  1629. if (ost->finished)
  1630. return 0;
  1631. if (of->start_time != AV_NOPTS_VALUE && ist->pts < of->start_time)
  1632. return 0;
  1633. return 1;
  1634. }
  1635. static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
  1636. {
  1637. OutputFile *of = output_files[ost->file_index];
  1638. InputFile *f = input_files [ist->file_index];
  1639. int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
  1640. int64_t ost_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q, ost->st->time_base);
  1641. AVPicture pict;
  1642. AVPacket opkt;
  1643. av_init_packet(&opkt);
  1644. if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
  1645. !ost->copy_initial_nonkeyframes)
  1646. return;
  1647. if (!ost->frame_number && !ost->copy_prior_start) {
  1648. int64_t comp_start = start_time;
  1649. if (copy_ts && f->start_time != AV_NOPTS_VALUE)
  1650. comp_start = FFMAX(start_time, f->start_time + f->ts_offset);
  1651. if (pkt->pts == AV_NOPTS_VALUE ?
  1652. ist->pts < comp_start :
  1653. pkt->pts < av_rescale_q(comp_start, AV_TIME_BASE_Q, ist->st->time_base))
  1654. return;
  1655. }
  1656. if (of->recording_time != INT64_MAX &&
  1657. ist->pts >= of->recording_time + start_time) {
  1658. close_output_stream(ost);
  1659. return;
  1660. }
  1661. if (f->recording_time != INT64_MAX) {
  1662. start_time = f->ctx->start_time;
  1663. if (f->start_time != AV_NOPTS_VALUE && copy_ts)
  1664. start_time += f->start_time;
  1665. if (ist->pts >= f->recording_time + start_time) {
  1666. close_output_stream(ost);
  1667. return;
  1668. }
  1669. }
  1670. /* force the input stream PTS */
  1671. if (ost->enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO)
  1672. ost->sync_opts++;
  1673. if (pkt->pts != AV_NOPTS_VALUE)
  1674. opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
  1675. else
  1676. opkt.pts = AV_NOPTS_VALUE;
  1677. if (pkt->dts == AV_NOPTS_VALUE)
  1678. opkt.dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ost->st->time_base);
  1679. else
  1680. opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
  1681. opkt.dts -= ost_tb_start_time;
  1682. if (ost->st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && pkt->dts != AV_NOPTS_VALUE) {
  1683. int duration = av_get_audio_frame_duration(ist->dec_ctx, pkt->size);
  1684. if(!duration)
  1685. duration = ist->dec_ctx->frame_size;
  1686. opkt.dts = opkt.pts = av_rescale_delta(ist->st->time_base, pkt->dts,
  1687. (AVRational){1, ist->dec_ctx->sample_rate}, duration, &ist->filter_in_rescale_delta_last,
  1688. ost->st->time_base) - ost_tb_start_time;
  1689. }
  1690. opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
  1691. opkt.flags = pkt->flags;
  1692. // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
  1693. if ( ost->st->codecpar->codec_id != AV_CODEC_ID_H264
  1694. && ost->st->codecpar->codec_id != AV_CODEC_ID_MPEG1VIDEO
  1695. && ost->st->codecpar->codec_id != AV_CODEC_ID_MPEG2VIDEO
  1696. && ost->st->codecpar->codec_id != AV_CODEC_ID_VC1
  1697. ) {
  1698. int ret = av_parser_change(ost->parser, ost->parser_avctx,
  1699. &opkt.data, &opkt.size,
  1700. pkt->data, pkt->size,
  1701. pkt->flags & AV_PKT_FLAG_KEY);
  1702. if (ret < 0) {
  1703. av_log(NULL, AV_LOG_FATAL, "av_parser_change failed: %s\n",
  1704. av_err2str(ret));
  1705. exit_program(1);
  1706. }
  1707. if (ret) {
  1708. opkt.buf = av_buffer_create(opkt.data, opkt.size, av_buffer_default_free, NULL, 0);
  1709. if (!opkt.buf)
  1710. exit_program(1);
  1711. }
  1712. } else {
  1713. opkt.data = pkt->data;
  1714. opkt.size = pkt->size;
  1715. }
  1716. av_copy_packet_side_data(&opkt, pkt);
  1717. #if FF_API_LAVF_FMT_RAWPICTURE
  1718. if (ost->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
  1719. ost->st->codecpar->codec_id == AV_CODEC_ID_RAWVIDEO &&
  1720. (of->ctx->oformat->flags & AVFMT_RAWPICTURE)) {
  1721. /* store AVPicture in AVPacket, as expected by the output format */
  1722. int ret = avpicture_fill(&pict, opkt.data, ost->st->codecpar->format, ost->st->codecpar->width, ost->st->codecpar->height);
  1723. if (ret < 0) {
  1724. av_log(NULL, AV_LOG_FATAL, "avpicture_fill failed: %s\n",
  1725. av_err2str(ret));
  1726. exit_program(1);
  1727. }
  1728. opkt.data = (uint8_t *)&pict;
  1729. opkt.size = sizeof(AVPicture);
  1730. opkt.flags |= AV_PKT_FLAG_KEY;
  1731. }
  1732. #endif
  1733. output_packet(of, &opkt, ost);
  1734. }
  1735. int guess_input_channel_layout(InputStream *ist)
  1736. {
  1737. AVCodecContext *dec = ist->dec_ctx;
  1738. if (!dec->channel_layout) {
  1739. char layout_name[256];
  1740. if (dec->channels > ist->guess_layout_max)
  1741. return 0;
  1742. dec->channel_layout = av_get_default_channel_layout(dec->channels);
  1743. if (!dec->channel_layout)
  1744. return 0;
  1745. av_get_channel_layout_string(layout_name, sizeof(layout_name),
  1746. dec->channels, dec->channel_layout);
  1747. av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Input Stream "
  1748. "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
  1749. }
  1750. return 1;
  1751. }
  1752. static void check_decode_result(InputStream *ist, int *got_output, int ret)
  1753. {
  1754. if (*got_output || ret<0)
  1755. decode_error_stat[ret<0] ++;
  1756. if (ret < 0 && exit_on_error)
  1757. exit_program(1);
  1758. if (exit_on_error && *got_output && ist) {
  1759. if (av_frame_get_decode_error_flags(ist->decoded_frame) || (ist->decoded_frame->flags & AV_FRAME_FLAG_CORRUPT)) {
  1760. av_log(NULL, AV_LOG_FATAL, "%s: corrupt decoded frame in stream %d\n", input_files[ist->file_index]->ctx->filename, ist->st->index);
  1761. exit_program(1);
  1762. }
  1763. }
  1764. }
  1765. // This does not quite work like avcodec_decode_audio4/avcodec_decode_video2.
  1766. // There is the following difference: if you got a frame, you must call
  1767. // it again with pkt=NULL. pkt==NULL is treated differently from pkt.size==0
  1768. // (pkt==NULL means get more output, pkt.size==0 is a flush/drain packet)
  1769. static int decode(AVCodecContext *avctx, AVFrame *frame, int *got_frame, AVPacket *pkt)
  1770. {
  1771. int ret;
  1772. *got_frame = 0;
  1773. if (pkt) {
  1774. ret = avcodec_send_packet(avctx, pkt);
  1775. // In particular, we don't expect AVERROR(EAGAIN), because we read all
  1776. // decoded frames with avcodec_receive_frame() until done.
  1777. if (ret < 0 && ret != AVERROR_EOF)
  1778. return ret;
  1779. }
  1780. ret = avcodec_receive_frame(avctx, frame);
  1781. if (ret < 0 && ret != AVERROR(EAGAIN))
  1782. return ret;
  1783. if (ret >= 0)
  1784. *got_frame = 1;
  1785. return 0;
  1786. }
  1787. static int send_frame_to_filters(InputStream *ist, AVFrame *decoded_frame)
  1788. {
  1789. int i, ret;
  1790. AVFrame *f;
  1791. for (i = 0; i < ist->nb_filters; i++) {
  1792. if (i < ist->nb_filters - 1) {
  1793. f = ist->filter_frame;
  1794. ret = av_frame_ref(f, decoded_frame);
  1795. if (ret < 0)
  1796. break;
  1797. } else
  1798. f = decoded_frame;
  1799. ret = av_buffersrc_add_frame_flags(ist->filters[i]->filter, f,
  1800. AV_BUFFERSRC_FLAG_PUSH);
  1801. if (ret == AVERROR_EOF)
  1802. ret = 0; /* ignore */
  1803. if (ret < 0) {
  1804. av_log(NULL, AV_LOG_ERROR,
  1805. "Failed to inject frame into filter network: %s\n", av_err2str(ret));
  1806. break;
  1807. }
  1808. }
  1809. return ret;
  1810. }
  1811. static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
  1812. {
  1813. AVFrame *decoded_frame;
  1814. AVCodecContext *avctx = ist->dec_ctx;
  1815. int i, ret, err = 0, resample_changed;
  1816. AVRational decoded_frame_tb;
  1817. if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
  1818. return AVERROR(ENOMEM);
  1819. if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
  1820. return AVERROR(ENOMEM);
  1821. decoded_frame = ist->decoded_frame;
  1822. update_benchmark(NULL);
  1823. ret = decode(avctx, decoded_frame, got_output, pkt);
  1824. update_benchmark("decode_audio %d.%d", ist->file_index, ist->st->index);
  1825. if (ret >= 0 && avctx->sample_rate <= 0) {
  1826. av_log(avctx, AV_LOG_ERROR, "Sample rate %d invalid\n", avctx->sample_rate);
  1827. ret = AVERROR_INVALIDDATA;
  1828. }
  1829. if (ret != AVERROR_EOF)
  1830. check_decode_result(ist, got_output, ret);
  1831. if (!*got_output || ret < 0)
  1832. return ret;
  1833. ist->samples_decoded += decoded_frame->nb_samples;
  1834. ist->frames_decoded++;
  1835. #if 1
  1836. /* increment next_dts to use for the case where the input stream does not
  1837. have timestamps or there are multiple frames in the packet */
  1838. ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
  1839. avctx->sample_rate;
  1840. ist->next_dts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
  1841. avctx->sample_rate;
  1842. #endif
  1843. resample_changed = ist->resample_sample_fmt != decoded_frame->format ||
  1844. ist->resample_channels != avctx->channels ||
  1845. ist->resample_channel_layout != decoded_frame->channel_layout ||
  1846. ist->resample_sample_rate != decoded_frame->sample_rate;
  1847. if (resample_changed) {
  1848. char layout1[64], layout2[64];
  1849. if (!guess_input_channel_layout(ist)) {
  1850. av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
  1851. "layout for Input Stream #%d.%d\n", ist->file_index,
  1852. ist->st->index);
  1853. exit_program(1);
  1854. }
  1855. decoded_frame->channel_layout = avctx->channel_layout;
  1856. av_get_channel_layout_string(layout1, sizeof(layout1), ist->resample_channels,
  1857. ist->resample_channel_layout);
  1858. av_get_channel_layout_string(layout2, sizeof(layout2), avctx->channels,
  1859. decoded_frame->channel_layout);
  1860. av_log(NULL, AV_LOG_INFO,
  1861. "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",
  1862. ist->file_index, ist->st->index,
  1863. ist->resample_sample_rate, av_get_sample_fmt_name(ist->resample_sample_fmt),
  1864. ist->resample_channels, layout1,
  1865. decoded_frame->sample_rate, av_get_sample_fmt_name(decoded_frame->format),
  1866. avctx->channels, layout2);
  1867. ist->resample_sample_fmt = decoded_frame->format;
  1868. ist->resample_sample_rate = decoded_frame->sample_rate;
  1869. ist->resample_channel_layout = decoded_frame->channel_layout;
  1870. ist->resample_channels = avctx->channels;
  1871. for (i = 0; i < ist->nb_filters; i++) {
  1872. err = ifilter_parameters_from_frame(ist->filters[i], decoded_frame);
  1873. if (err < 0) {
  1874. av_log(NULL, AV_LOG_ERROR,
  1875. "Error reconfiguring input stream %d:%d filter %d\n",
  1876. ist->file_index, ist->st->index, i);
  1877. goto fail;
  1878. }
  1879. }
  1880. for (i = 0; i < nb_filtergraphs; i++)
  1881. if (ist_in_filtergraph(filtergraphs[i], ist)) {
  1882. FilterGraph *fg = filtergraphs[i];
  1883. if (configure_filtergraph(fg) < 0) {
  1884. av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
  1885. exit_program(1);
  1886. }
  1887. }
  1888. }
  1889. if (decoded_frame->pts != AV_NOPTS_VALUE) {
  1890. decoded_frame_tb = ist->st->time_base;
  1891. } else if (pkt && pkt->pts != AV_NOPTS_VALUE) {
  1892. decoded_frame->pts = pkt->pts;
  1893. decoded_frame_tb = ist->st->time_base;
  1894. }else {
  1895. decoded_frame->pts = ist->dts;
  1896. decoded_frame_tb = AV_TIME_BASE_Q;
  1897. }
  1898. if (decoded_frame->pts != AV_NOPTS_VALUE)
  1899. decoded_frame->pts = av_rescale_delta(decoded_frame_tb, decoded_frame->pts,
  1900. (AVRational){1, avctx->sample_rate}, decoded_frame->nb_samples, &ist->filter_in_rescale_delta_last,
  1901. (AVRational){1, avctx->sample_rate});
  1902. ist->nb_samples = decoded_frame->nb_samples;
  1903. err = send_frame_to_filters(ist, decoded_frame);
  1904. decoded_frame->pts = AV_NOPTS_VALUE;
  1905. fail:
  1906. av_frame_unref(ist->filter_frame);
  1907. av_frame_unref(decoded_frame);
  1908. return err < 0 ? err : ret;
  1909. }
  1910. static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output, int eof)
  1911. {
  1912. AVFrame *decoded_frame;
  1913. int i, ret = 0, err = 0, resample_changed;
  1914. int64_t best_effort_timestamp;
  1915. int64_t dts = AV_NOPTS_VALUE;
  1916. AVPacket avpkt;
  1917. // With fate-indeo3-2, we're getting 0-sized packets before EOF for some
  1918. // reason. This seems like a semi-critical bug. Don't trigger EOF, and
  1919. // skip the packet.
  1920. if (!eof && pkt && pkt->size == 0)
  1921. return 0;
  1922. if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
  1923. return AVERROR(ENOMEM);
  1924. if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
  1925. return AVERROR(ENOMEM);
  1926. decoded_frame = ist->decoded_frame;
  1927. if (ist->dts != AV_NOPTS_VALUE)
  1928. dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ist->st->time_base);
  1929. if (pkt) {
  1930. avpkt = *pkt;
  1931. avpkt.dts = dts; // ffmpeg.c probably shouldn't do this
  1932. }
  1933. // The old code used to set dts on the drain packet, which does not work
  1934. // with the new API anymore.
  1935. if (eof) {
  1936. void *new = av_realloc_array(ist->dts_buffer, ist->nb_dts_buffer + 1, sizeof(ist->dts_buffer[0]));
  1937. if (!new)
  1938. return AVERROR(ENOMEM);
  1939. ist->dts_buffer = new;
  1940. ist->dts_buffer[ist->nb_dts_buffer++] = dts;
  1941. }
  1942. update_benchmark(NULL);
  1943. ret = decode(ist->dec_ctx, decoded_frame, got_output, pkt ? &avpkt : NULL);
  1944. update_benchmark("decode_video %d.%d", ist->file_index, ist->st->index);
  1945. // The following line may be required in some cases where there is no parser
  1946. // or the parser does not has_b_frames correctly
  1947. if (ist->st->codecpar->video_delay < ist->dec_ctx->has_b_frames) {
  1948. if (ist->dec_ctx->codec_id == AV_CODEC_ID_H264) {
  1949. ist->st->codecpar->video_delay = ist->dec_ctx->has_b_frames;
  1950. } else
  1951. av_log(ist->dec_ctx, AV_LOG_WARNING,
  1952. "video_delay is larger in decoder than demuxer %d > %d.\n"
  1953. "If you want to help, upload a sample "
  1954. "of this file to ftp://upload.ffmpeg.org/incoming/ "
  1955. "and contact the ffmpeg-devel mailing list. (ffmpeg-devel@ffmpeg.org)",
  1956. ist->dec_ctx->has_b_frames,
  1957. ist->st->codecpar->video_delay);
  1958. }
  1959. if (ret != AVERROR_EOF)
  1960. check_decode_result(ist, got_output, ret);
  1961. if (*got_output && ret >= 0) {
  1962. if (ist->dec_ctx->width != decoded_frame->width ||
  1963. ist->dec_ctx->height != decoded_frame->height ||
  1964. ist->dec_ctx->pix_fmt != decoded_frame->format) {
  1965. av_log(NULL, AV_LOG_DEBUG, "Frame parameters mismatch context %d,%d,%d != %d,%d,%d\n",
  1966. decoded_frame->width,
  1967. decoded_frame->height,
  1968. decoded_frame->format,
  1969. ist->dec_ctx->width,
  1970. ist->dec_ctx->height,
  1971. ist->dec_ctx->pix_fmt);
  1972. }
  1973. }
  1974. if (!*got_output || ret < 0)
  1975. return ret;
  1976. if(ist->top_field_first>=0)
  1977. decoded_frame->top_field_first = ist->top_field_first;
  1978. ist->frames_decoded++;
  1979. if (ist->hwaccel_retrieve_data && decoded_frame->format == ist->hwaccel_pix_fmt) {
  1980. err = ist->hwaccel_retrieve_data(ist->dec_ctx, decoded_frame);
  1981. if (err < 0)
  1982. goto fail;
  1983. }
  1984. ist->hwaccel_retrieved_pix_fmt = decoded_frame->format;
  1985. best_effort_timestamp= av_frame_get_best_effort_timestamp(decoded_frame);
  1986. if (eof && best_effort_timestamp == AV_NOPTS_VALUE && ist->nb_dts_buffer > 0) {
  1987. best_effort_timestamp = ist->dts_buffer[0];
  1988. for (i = 0; i < ist->nb_dts_buffer - 1; i++)
  1989. ist->dts_buffer[i] = ist->dts_buffer[i + 1];
  1990. ist->nb_dts_buffer--;
  1991. }
  1992. if(best_effort_timestamp != AV_NOPTS_VALUE) {
  1993. int64_t ts = av_rescale_q(decoded_frame->pts = best_effort_timestamp, ist->st->time_base, AV_TIME_BASE_Q);
  1994. if (ts != AV_NOPTS_VALUE)
  1995. ist->next_pts = ist->pts = ts;
  1996. }
  1997. if (debug_ts) {
  1998. av_log(NULL, AV_LOG_INFO, "decoder -> ist_index:%d type:video "
  1999. "frame_pts:%s frame_pts_time:%s best_effort_ts:%"PRId64" best_effort_ts_time:%s keyframe:%d frame_type:%d time_base:%d/%d\n",
  2000. ist->st->index, av_ts2str(decoded_frame->pts),
  2001. av_ts2timestr(decoded_frame->pts, &ist->st->time_base),
  2002. best_effort_timestamp,
  2003. av_ts2timestr(best_effort_timestamp, &ist->st->time_base),
  2004. decoded_frame->key_frame, decoded_frame->pict_type,
  2005. ist->st->time_base.num, ist->st->time_base.den);
  2006. }
  2007. if (ist->st->sample_aspect_ratio.num)
  2008. decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
  2009. resample_changed = ist->resample_width != decoded_frame->width ||
  2010. ist->resample_height != decoded_frame->height ||
  2011. ist->resample_pix_fmt != decoded_frame->format;
  2012. if (resample_changed) {
  2013. av_log(NULL, AV_LOG_INFO,
  2014. "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
  2015. ist->file_index, ist->st->index,
  2016. ist->resample_width, ist->resample_height, av_get_pix_fmt_name(ist->resample_pix_fmt),
  2017. decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
  2018. ist->resample_width = decoded_frame->width;
  2019. ist->resample_height = decoded_frame->height;
  2020. ist->resample_pix_fmt = decoded_frame->format;
  2021. for (i = 0; i < ist->nb_filters; i++) {
  2022. err = ifilter_parameters_from_frame(ist->filters[i], decoded_frame);
  2023. if (err < 0) {
  2024. av_log(NULL, AV_LOG_ERROR,
  2025. "Error reconfiguring input stream %d:%d filter %d\n",
  2026. ist->file_index, ist->st->index, i);
  2027. goto fail;
  2028. }
  2029. }
  2030. for (i = 0; i < nb_filtergraphs; i++) {
  2031. if (ist_in_filtergraph(filtergraphs[i], ist) && ist->reinit_filters &&
  2032. configure_filtergraph(filtergraphs[i]) < 0) {
  2033. av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
  2034. exit_program(1);
  2035. }
  2036. }
  2037. }
  2038. err = send_frame_to_filters(ist, decoded_frame);
  2039. fail:
  2040. av_frame_unref(ist->filter_frame);
  2041. av_frame_unref(decoded_frame);
  2042. return err < 0 ? err : ret;
  2043. }
  2044. static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
  2045. {
  2046. AVSubtitle subtitle;
  2047. int i, ret = avcodec_decode_subtitle2(ist->dec_ctx,
  2048. &subtitle, got_output, pkt);
  2049. check_decode_result(NULL, got_output, ret);
  2050. if (ret < 0 || !*got_output) {
  2051. if (!pkt->size)
  2052. sub2video_flush(ist);
  2053. return ret;
  2054. }
  2055. if (ist->fix_sub_duration) {
  2056. int end = 1;
  2057. if (ist->prev_sub.got_output) {
  2058. end = av_rescale(subtitle.pts - ist->prev_sub.subtitle.pts,
  2059. 1000, AV_TIME_BASE);
  2060. if (end < ist->prev_sub.subtitle.end_display_time) {
  2061. av_log(ist->dec_ctx, AV_LOG_DEBUG,
  2062. "Subtitle duration reduced from %d to %d%s\n",
  2063. ist->prev_sub.subtitle.end_display_time, end,
  2064. end <= 0 ? ", dropping it" : "");
  2065. ist->prev_sub.subtitle.end_display_time = end;
  2066. }
  2067. }
  2068. FFSWAP(int, *got_output, ist->prev_sub.got_output);
  2069. FFSWAP(int, ret, ist->prev_sub.ret);
  2070. FFSWAP(AVSubtitle, subtitle, ist->prev_sub.subtitle);
  2071. if (end <= 0)
  2072. goto out;
  2073. }
  2074. if (!*got_output)
  2075. return ret;
  2076. sub2video_update(ist, &subtitle);
  2077. if (!subtitle.num_rects)
  2078. goto out;
  2079. ist->frames_decoded++;
  2080. for (i = 0; i < nb_output_streams; i++) {
  2081. OutputStream *ost = output_streams[i];
  2082. if (!check_output_constraints(ist, ost) || !ost->encoding_needed
  2083. || ost->enc->type != AVMEDIA_TYPE_SUBTITLE)
  2084. continue;
  2085. do_subtitle_out(output_files[ost->file_index], ost, &subtitle);
  2086. }
  2087. out:
  2088. avsubtitle_free(&subtitle);
  2089. return ret;
  2090. }
  2091. static int send_filter_eof(InputStream *ist)
  2092. {
  2093. int i, ret;
  2094. for (i = 0; i < ist->nb_filters; i++) {
  2095. ret = av_buffersrc_add_frame(ist->filters[i]->filter, NULL);
  2096. if (ret < 0)
  2097. return ret;
  2098. }
  2099. return 0;
  2100. }
  2101. /* pkt = NULL means EOF (needed to flush decoder buffers) */
  2102. static int process_input_packet(InputStream *ist, const AVPacket *pkt, int no_eof)
  2103. {
  2104. int ret = 0, i;
  2105. int repeating = 0;
  2106. int eof_reached = 0;
  2107. AVPacket avpkt;
  2108. if (!ist->saw_first_ts) {
  2109. ist->dts = ist->st->avg_frame_rate.num ? - ist->dec_ctx->has_b_frames * AV_TIME_BASE / av_q2d(ist->st->avg_frame_rate) : 0;
  2110. ist->pts = 0;
  2111. if (pkt && pkt->pts != AV_NOPTS_VALUE && !ist->decoding_needed) {
  2112. ist->dts += av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
  2113. ist->pts = ist->dts; //unused but better to set it to a value thats not totally wrong
  2114. }
  2115. ist->saw_first_ts = 1;
  2116. }
  2117. if (ist->next_dts == AV_NOPTS_VALUE)
  2118. ist->next_dts = ist->dts;
  2119. if (ist->next_pts == AV_NOPTS_VALUE)
  2120. ist->next_pts = ist->pts;
  2121. if (!pkt) {
  2122. /* EOF handling */
  2123. av_init_packet(&avpkt);
  2124. avpkt.data = NULL;
  2125. avpkt.size = 0;
  2126. } else {
  2127. avpkt = *pkt;
  2128. }
  2129. if (pkt && pkt->dts != AV_NOPTS_VALUE) {
  2130. ist->next_dts = ist->dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
  2131. if (ist->dec_ctx->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)
  2132. ist->next_pts = ist->pts = ist->dts;
  2133. }
  2134. // while we have more to decode or while the decoder did output something on EOF
  2135. while (ist->decoding_needed) {
  2136. int duration = 0;
  2137. int got_output = 0;
  2138. ist->pts = ist->next_pts;
  2139. ist->dts = ist->next_dts;
  2140. switch (ist->dec_ctx->codec_type) {
  2141. case AVMEDIA_TYPE_AUDIO:
  2142. ret = decode_audio (ist, repeating ? NULL : &avpkt, &got_output);
  2143. break;
  2144. case AVMEDIA_TYPE_VIDEO:
  2145. ret = decode_video (ist, repeating ? NULL : &avpkt, &got_output, !pkt);
  2146. if (!repeating || !pkt || got_output) {
  2147. if (pkt && pkt->duration) {
  2148. duration = av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
  2149. } else if(ist->dec_ctx->framerate.num != 0 && ist->dec_ctx->framerate.den != 0) {
  2150. int ticks= av_stream_get_parser(ist->st) ? av_stream_get_parser(ist->st)->repeat_pict+1 : ist->dec_ctx->ticks_per_frame;
  2151. duration = ((int64_t)AV_TIME_BASE *
  2152. ist->dec_ctx->framerate.den * ticks) /
  2153. ist->dec_ctx->framerate.num / ist->dec_ctx->ticks_per_frame;
  2154. }
  2155. if(ist->dts != AV_NOPTS_VALUE && duration) {
  2156. ist->next_dts += duration;
  2157. }else
  2158. ist->next_dts = AV_NOPTS_VALUE;
  2159. }
  2160. if (got_output)
  2161. ist->next_pts += duration; //FIXME the duration is not correct in some cases
  2162. break;
  2163. case AVMEDIA_TYPE_SUBTITLE:
  2164. if (repeating)
  2165. break;
  2166. ret = transcode_subtitles(ist, &avpkt, &got_output);
  2167. if (!pkt && ret >= 0)
  2168. ret = AVERROR_EOF;
  2169. break;
  2170. default:
  2171. return -1;
  2172. }
  2173. if (ret == AVERROR_EOF) {
  2174. eof_reached = 1;
  2175. break;
  2176. }
  2177. if (ret < 0) {
  2178. av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d: %s\n",
  2179. ist->file_index, ist->st->index, av_err2str(ret));
  2180. if (exit_on_error)
  2181. exit_program(1);
  2182. // Decoding might not terminate if we're draining the decoder, and
  2183. // the decoder keeps returning an error.
  2184. // This should probably be considered a libavcodec issue.
  2185. // Sample: fate-vsynth1-dnxhd-720p-hr-lb
  2186. if (!pkt)
  2187. eof_reached = 1;
  2188. break;
  2189. }
  2190. if (!got_output)
  2191. break;
  2192. // During draining, we might get multiple output frames in this loop.
  2193. // ffmpeg.c does not drain the filter chain on configuration changes,
  2194. // which means if we send multiple frames at once to the filters, and
  2195. // one of those frames changes configuration, the buffered frames will
  2196. // be lost. This can upset certain FATE tests.
  2197. // Decode only 1 frame per call on EOF to appease these FATE tests.
  2198. // The ideal solution would be to rewrite decoding to use the new
  2199. // decoding API in a better way.
  2200. if (!pkt)
  2201. break;
  2202. repeating = 1;
  2203. }
  2204. /* after flushing, send an EOF on all the filter inputs attached to the stream */
  2205. /* except when looping we need to flush but not to send an EOF */
  2206. if (!pkt && ist->decoding_needed && eof_reached && !no_eof) {
  2207. int ret = send_filter_eof(ist);
  2208. if (ret < 0) {
  2209. av_log(NULL, AV_LOG_FATAL, "Error marking filters as finished\n");
  2210. exit_program(1);
  2211. }
  2212. }
  2213. /* handle stream copy */
  2214. if (!ist->decoding_needed) {
  2215. ist->dts = ist->next_dts;
  2216. switch (ist->dec_ctx->codec_type) {
  2217. case AVMEDIA_TYPE_AUDIO:
  2218. ist->next_dts += ((int64_t)AV_TIME_BASE * ist->dec_ctx->frame_size) /
  2219. ist->dec_ctx->sample_rate;
  2220. break;
  2221. case AVMEDIA_TYPE_VIDEO:
  2222. if (ist->framerate.num) {
  2223. // TODO: Remove work-around for c99-to-c89 issue 7
  2224. AVRational time_base_q = AV_TIME_BASE_Q;
  2225. int64_t next_dts = av_rescale_q(ist->next_dts, time_base_q, av_inv_q(ist->framerate));
  2226. ist->next_dts = av_rescale_q(next_dts + 1, av_inv_q(ist->framerate), time_base_q);
  2227. } else if (pkt->duration) {
  2228. ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
  2229. } else if(ist->dec_ctx->framerate.num != 0) {
  2230. int ticks= av_stream_get_parser(ist->st) ? av_stream_get_parser(ist->st)->repeat_pict + 1 : ist->dec_ctx->ticks_per_frame;
  2231. ist->next_dts += ((int64_t)AV_TIME_BASE *
  2232. ist->dec_ctx->framerate.den * ticks) /
  2233. ist->dec_ctx->framerate.num / ist->dec_ctx->ticks_per_frame;
  2234. }
  2235. break;
  2236. }
  2237. ist->pts = ist->dts;
  2238. ist->next_pts = ist->next_dts;
  2239. }
  2240. for (i = 0; pkt && i < nb_output_streams; i++) {
  2241. OutputStream *ost = output_streams[i];
  2242. if (!check_output_constraints(ist, ost) || ost->encoding_needed)
  2243. continue;
  2244. do_streamcopy(ist, ost, pkt);
  2245. }
  2246. return !eof_reached;
  2247. }
  2248. static void print_sdp(void)
  2249. {
  2250. char sdp[16384];
  2251. int i;
  2252. int j;
  2253. AVIOContext *sdp_pb;
  2254. AVFormatContext **avc;
  2255. for (i = 0; i < nb_output_files; i++) {
  2256. if (!output_files[i]->header_written)
  2257. return;
  2258. }
  2259. avc = av_malloc_array(nb_output_files, sizeof(*avc));
  2260. if (!avc)
  2261. exit_program(1);
  2262. for (i = 0, j = 0; i < nb_output_files; i++) {
  2263. if (!strcmp(output_files[i]->ctx->oformat->name, "rtp")) {
  2264. avc[j] = output_files[i]->ctx;
  2265. j++;
  2266. }
  2267. }
  2268. if (!j)
  2269. goto fail;
  2270. av_sdp_create(avc, j, sdp, sizeof(sdp));
  2271. if (!sdp_filename) {
  2272. printf("SDP:\n%s\n", sdp);
  2273. fflush(stdout);
  2274. } else {
  2275. if (avio_open2(&sdp_pb, sdp_filename, AVIO_FLAG_WRITE, &int_cb, NULL) < 0) {
  2276. av_log(NULL, AV_LOG_ERROR, "Failed to open sdp file '%s'\n", sdp_filename);
  2277. } else {
  2278. avio_printf(sdp_pb, "SDP:\n%s", sdp);
  2279. avio_closep(&sdp_pb);
  2280. av_freep(&sdp_filename);
  2281. }
  2282. }
  2283. fail:
  2284. av_freep(&avc);
  2285. }
  2286. static const HWAccel *get_hwaccel(enum AVPixelFormat pix_fmt)
  2287. {
  2288. int i;
  2289. for (i = 0; hwaccels[i].name; i++)
  2290. if (hwaccels[i].pix_fmt == pix_fmt)
  2291. return &hwaccels[i];
  2292. return NULL;
  2293. }
  2294. static enum AVPixelFormat get_format(AVCodecContext *s, const enum AVPixelFormat *pix_fmts)
  2295. {
  2296. InputStream *ist = s->opaque;
  2297. const enum AVPixelFormat *p;
  2298. int ret;
  2299. for (p = pix_fmts; *p != -1; p++) {
  2300. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(*p);
  2301. const HWAccel *hwaccel;
  2302. if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
  2303. break;
  2304. hwaccel = get_hwaccel(*p);
  2305. if (!hwaccel ||
  2306. (ist->active_hwaccel_id && ist->active_hwaccel_id != hwaccel->id) ||
  2307. (ist->hwaccel_id != HWACCEL_AUTO && ist->hwaccel_id != hwaccel->id))
  2308. continue;
  2309. ret = hwaccel->init(s);
  2310. if (ret < 0) {
  2311. if (ist->hwaccel_id == hwaccel->id) {
  2312. av_log(NULL, AV_LOG_FATAL,
  2313. "%s hwaccel requested for input stream #%d:%d, "
  2314. "but cannot be initialized.\n", hwaccel->name,
  2315. ist->file_index, ist->st->index);
  2316. return AV_PIX_FMT_NONE;
  2317. }
  2318. continue;
  2319. }
  2320. if (ist->hw_frames_ctx) {
  2321. s->hw_frames_ctx = av_buffer_ref(ist->hw_frames_ctx);
  2322. if (!s->hw_frames_ctx)
  2323. return AV_PIX_FMT_NONE;
  2324. }
  2325. ist->active_hwaccel_id = hwaccel->id;
  2326. ist->hwaccel_pix_fmt = *p;
  2327. break;
  2328. }
  2329. return *p;
  2330. }
  2331. static int get_buffer(AVCodecContext *s, AVFrame *frame, int flags)
  2332. {
  2333. InputStream *ist = s->opaque;
  2334. if (ist->hwaccel_get_buffer && frame->format == ist->hwaccel_pix_fmt)
  2335. return ist->hwaccel_get_buffer(s, frame, flags);
  2336. return avcodec_default_get_buffer2(s, frame, flags);
  2337. }
  2338. static int init_input_stream(int ist_index, char *error, int error_len)
  2339. {
  2340. int i, ret;
  2341. InputStream *ist = input_streams[ist_index];
  2342. for (i = 0; i < ist->nb_filters; i++) {
  2343. ret = ifilter_parameters_from_decoder(ist->filters[i], ist->dec_ctx);
  2344. if (ret < 0) {
  2345. av_log(NULL, AV_LOG_FATAL, "Error initializing filter input\n");
  2346. return ret;
  2347. }
  2348. }
  2349. if (ist->decoding_needed) {
  2350. AVCodec *codec = ist->dec;
  2351. if (!codec) {
  2352. snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
  2353. avcodec_get_name(ist->dec_ctx->codec_id), ist->file_index, ist->st->index);
  2354. return AVERROR(EINVAL);
  2355. }
  2356. ist->dec_ctx->opaque = ist;
  2357. ist->dec_ctx->get_format = get_format;
  2358. ist->dec_ctx->get_buffer2 = get_buffer;
  2359. ist->dec_ctx->thread_safe_callbacks = 1;
  2360. av_opt_set_int(ist->dec_ctx, "refcounted_frames", 1, 0);
  2361. if (ist->dec_ctx->codec_id == AV_CODEC_ID_DVB_SUBTITLE &&
  2362. (ist->decoding_needed & DECODING_FOR_OST)) {
  2363. av_dict_set(&ist->decoder_opts, "compute_edt", "1", AV_DICT_DONT_OVERWRITE);
  2364. if (ist->decoding_needed & DECODING_FOR_FILTER)
  2365. av_log(NULL, AV_LOG_WARNING, "Warning using DVB subtitles for filtering and output at the same time is not fully supported, also see -compute_edt [0|1]\n");
  2366. }
  2367. av_dict_set(&ist->decoder_opts, "sub_text_format", "ass", AV_DICT_DONT_OVERWRITE);
  2368. /* Useful for subtitles retiming by lavf (FIXME), skipping samples in
  2369. * audio, and video decoders such as cuvid or mediacodec */
  2370. av_codec_set_pkt_timebase(ist->dec_ctx, ist->st->time_base);
  2371. if (!av_dict_get(ist->decoder_opts, "threads", NULL, 0))
  2372. av_dict_set(&ist->decoder_opts, "threads", "auto", 0);
  2373. if ((ret = avcodec_open2(ist->dec_ctx, codec, &ist->decoder_opts)) < 0) {
  2374. if (ret == AVERROR_EXPERIMENTAL)
  2375. abort_codec_experimental(codec, 0);
  2376. snprintf(error, error_len,
  2377. "Error while opening decoder for input stream "
  2378. "#%d:%d : %s",
  2379. ist->file_index, ist->st->index, av_err2str(ret));
  2380. return ret;
  2381. }
  2382. assert_avoptions(ist->decoder_opts);
  2383. }
  2384. ist->next_pts = AV_NOPTS_VALUE;
  2385. ist->next_dts = AV_NOPTS_VALUE;
  2386. return 0;
  2387. }
  2388. static InputStream *get_input_stream(OutputStream *ost)
  2389. {
  2390. if (ost->source_index >= 0)
  2391. return input_streams[ost->source_index];
  2392. return NULL;
  2393. }
  2394. static int compare_int64(const void *a, const void *b)
  2395. {
  2396. return FFDIFFSIGN(*(const int64_t *)a, *(const int64_t *)b);
  2397. }
  2398. /* open the muxer when all the streams are initialized */
  2399. static int check_init_output_file(OutputFile *of, int file_index)
  2400. {
  2401. int ret, i;
  2402. for (i = 0; i < of->ctx->nb_streams; i++) {
  2403. OutputStream *ost = output_streams[of->ost_index + i];
  2404. if (!ost->initialized)
  2405. return 0;
  2406. }
  2407. of->ctx->interrupt_callback = int_cb;
  2408. ret = avformat_write_header(of->ctx, &of->opts);
  2409. if (ret < 0) {
  2410. av_log(NULL, AV_LOG_ERROR,
  2411. "Could not write header for output file #%d "
  2412. "(incorrect codec parameters ?): %s\n",
  2413. file_index, av_err2str(ret));
  2414. return ret;
  2415. }
  2416. //assert_avoptions(of->opts);
  2417. of->header_written = 1;
  2418. av_dump_format(of->ctx, file_index, of->ctx->filename, 1);
  2419. if (sdp_filename || want_sdp)
  2420. print_sdp();
  2421. /* flush the muxing queues */
  2422. for (i = 0; i < of->ctx->nb_streams; i++) {
  2423. OutputStream *ost = output_streams[of->ost_index + i];
  2424. while (av_fifo_size(ost->muxing_queue)) {
  2425. AVPacket pkt;
  2426. av_fifo_generic_read(ost->muxing_queue, &pkt, sizeof(pkt), NULL);
  2427. write_packet(of, &pkt, ost);
  2428. }
  2429. }
  2430. return 0;
  2431. }
  2432. static int init_output_bsfs(OutputStream *ost)
  2433. {
  2434. AVBSFContext *ctx;
  2435. int i, ret;
  2436. if (!ost->nb_bitstream_filters)
  2437. return 0;
  2438. for (i = 0; i < ost->nb_bitstream_filters; i++) {
  2439. ctx = ost->bsf_ctx[i];
  2440. ret = avcodec_parameters_copy(ctx->par_in,
  2441. i ? ost->bsf_ctx[i - 1]->par_out : ost->st->codecpar);
  2442. if (ret < 0)
  2443. return ret;
  2444. ctx->time_base_in = i ? ost->bsf_ctx[i - 1]->time_base_out : ost->st->time_base;
  2445. ret = av_bsf_init(ctx);
  2446. if (ret < 0) {
  2447. av_log(NULL, AV_LOG_ERROR, "Error initializing bitstream filter: %s\n",
  2448. ost->bsf_ctx[i]->filter->name);
  2449. return ret;
  2450. }
  2451. }
  2452. ctx = ost->bsf_ctx[ost->nb_bitstream_filters - 1];
  2453. ret = avcodec_parameters_copy(ost->st->codecpar, ctx->par_out);
  2454. if (ret < 0)
  2455. return ret;
  2456. ost->st->time_base = ctx->time_base_out;
  2457. return 0;
  2458. }
  2459. static int init_output_stream_streamcopy(OutputStream *ost)
  2460. {
  2461. OutputFile *of = output_files[ost->file_index];
  2462. InputStream *ist = get_input_stream(ost);
  2463. AVCodecParameters *par_dst = ost->st->codecpar;
  2464. AVCodecParameters *par_src = ost->ref_par;
  2465. AVRational sar;
  2466. int i, ret;
  2467. uint32_t codec_tag = par_dst->codec_tag;
  2468. av_assert0(ist && !ost->filter);
  2469. avcodec_parameters_to_context(ost->enc_ctx, ist->st->codecpar);
  2470. ret = av_opt_set_dict(ost->enc_ctx, &ost->encoder_opts);
  2471. if (ret < 0) {
  2472. av_log(NULL, AV_LOG_FATAL,
  2473. "Error setting up codec context options.\n");
  2474. return ret;
  2475. }
  2476. avcodec_parameters_from_context(par_src, ost->enc_ctx);
  2477. if (!codec_tag) {
  2478. unsigned int codec_tag_tmp;
  2479. if (!of->ctx->oformat->codec_tag ||
  2480. av_codec_get_id (of->ctx->oformat->codec_tag, par_src->codec_tag) == par_src->codec_id ||
  2481. !av_codec_get_tag2(of->ctx->oformat->codec_tag, par_src->codec_id, &codec_tag_tmp))
  2482. codec_tag = par_src->codec_tag;
  2483. }
  2484. ret = avcodec_parameters_copy(par_dst, par_src);
  2485. if (ret < 0)
  2486. return ret;
  2487. par_dst->codec_tag = codec_tag;
  2488. if (!ost->frame_rate.num)
  2489. ost->frame_rate = ist->framerate;
  2490. ost->st->avg_frame_rate = ost->frame_rate;
  2491. ret = avformat_transfer_internal_stream_timing_info(of->ctx->oformat, ost->st, ist->st, copy_tb);
  2492. if (ret < 0)
  2493. return ret;
  2494. // copy timebase while removing common factors
  2495. ost->st->time_base = av_add_q(av_stream_get_codec_timebase(ost->st), (AVRational){0, 1});
  2496. // copy disposition
  2497. ost->st->disposition = ist->st->disposition;
  2498. if (ist->st->nb_side_data) {
  2499. ost->st->side_data = av_realloc_array(NULL, ist->st->nb_side_data,
  2500. sizeof(*ist->st->side_data));
  2501. if (!ost->st->side_data)
  2502. return AVERROR(ENOMEM);
  2503. ost->st->nb_side_data = 0;
  2504. for (i = 0; i < ist->st->nb_side_data; i++) {
  2505. const AVPacketSideData *sd_src = &ist->st->side_data[i];
  2506. AVPacketSideData *sd_dst = &ost->st->side_data[ost->st->nb_side_data];
  2507. if (ost->rotate_overridden && sd_src->type == AV_PKT_DATA_DISPLAYMATRIX)
  2508. continue;
  2509. sd_dst->data = av_malloc(sd_src->size);
  2510. if (!sd_dst->data)
  2511. return AVERROR(ENOMEM);
  2512. memcpy(sd_dst->data, sd_src->data, sd_src->size);
  2513. sd_dst->size = sd_src->size;
  2514. sd_dst->type = sd_src->type;
  2515. ost->st->nb_side_data++;
  2516. }
  2517. }
  2518. ost->parser = av_parser_init(par_dst->codec_id);
  2519. ost->parser_avctx = avcodec_alloc_context3(NULL);
  2520. if (!ost->parser_avctx)
  2521. return AVERROR(ENOMEM);
  2522. switch (par_dst->codec_type) {
  2523. case AVMEDIA_TYPE_AUDIO:
  2524. if (audio_volume != 256) {
  2525. av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
  2526. exit_program(1);
  2527. }
  2528. if((par_dst->block_align == 1 || par_dst->block_align == 1152 || par_dst->block_align == 576) && par_dst->codec_id == AV_CODEC_ID_MP3)
  2529. par_dst->block_align= 0;
  2530. if(par_dst->codec_id == AV_CODEC_ID_AC3)
  2531. par_dst->block_align= 0;
  2532. break;
  2533. case AVMEDIA_TYPE_VIDEO:
  2534. if (ost->frame_aspect_ratio.num) { // overridden by the -aspect cli option
  2535. sar =
  2536. av_mul_q(ost->frame_aspect_ratio,
  2537. (AVRational){ par_dst->height, par_dst->width });
  2538. av_log(NULL, AV_LOG_WARNING, "Overriding aspect ratio "
  2539. "with stream copy may produce invalid files\n");
  2540. }
  2541. else if (ist->st->sample_aspect_ratio.num)
  2542. sar = ist->st->sample_aspect_ratio;
  2543. else
  2544. sar = par_src->sample_aspect_ratio;
  2545. ost->st->sample_aspect_ratio = par_dst->sample_aspect_ratio = sar;
  2546. ost->st->avg_frame_rate = ist->st->avg_frame_rate;
  2547. ost->st->r_frame_rate = ist->st->r_frame_rate;
  2548. break;
  2549. }
  2550. return 0;
  2551. }
  2552. static void set_encoder_id(OutputFile *of, OutputStream *ost)
  2553. {
  2554. AVDictionaryEntry *e;
  2555. uint8_t *encoder_string;
  2556. int encoder_string_len;
  2557. int format_flags = 0;
  2558. int codec_flags = 0;
  2559. if (av_dict_get(ost->st->metadata, "encoder", NULL, 0))
  2560. return;
  2561. e = av_dict_get(of->opts, "fflags", NULL, 0);
  2562. if (e) {
  2563. const AVOption *o = av_opt_find(of->ctx, "fflags", NULL, 0, 0);
  2564. if (!o)
  2565. return;
  2566. av_opt_eval_flags(of->ctx, o, e->value, &format_flags);
  2567. }
  2568. e = av_dict_get(ost->encoder_opts, "flags", NULL, 0);
  2569. if (e) {
  2570. const AVOption *o = av_opt_find(ost->enc_ctx, "flags", NULL, 0, 0);
  2571. if (!o)
  2572. return;
  2573. av_opt_eval_flags(ost->enc_ctx, o, e->value, &codec_flags);
  2574. }
  2575. encoder_string_len = sizeof(LIBAVCODEC_IDENT) + strlen(ost->enc->name) + 2;
  2576. encoder_string = av_mallocz(encoder_string_len);
  2577. if (!encoder_string)
  2578. exit_program(1);
  2579. if (!(format_flags & AVFMT_FLAG_BITEXACT) && !(codec_flags & AV_CODEC_FLAG_BITEXACT))
  2580. av_strlcpy(encoder_string, LIBAVCODEC_IDENT " ", encoder_string_len);
  2581. else
  2582. av_strlcpy(encoder_string, "Lavc ", encoder_string_len);
  2583. av_strlcat(encoder_string, ost->enc->name, encoder_string_len);
  2584. av_dict_set(&ost->st->metadata, "encoder", encoder_string,
  2585. AV_DICT_DONT_STRDUP_VAL | AV_DICT_DONT_OVERWRITE);
  2586. }
  2587. static void parse_forced_key_frames(char *kf, OutputStream *ost,
  2588. AVCodecContext *avctx)
  2589. {
  2590. char *p;
  2591. int n = 1, i, size, index = 0;
  2592. int64_t t, *pts;
  2593. for (p = kf; *p; p++)
  2594. if (*p == ',')
  2595. n++;
  2596. size = n;
  2597. pts = av_malloc_array(size, sizeof(*pts));
  2598. if (!pts) {
  2599. av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
  2600. exit_program(1);
  2601. }
  2602. p = kf;
  2603. for (i = 0; i < n; i++) {
  2604. char *next = strchr(p, ',');
  2605. if (next)
  2606. *next++ = 0;
  2607. if (!memcmp(p, "chapters", 8)) {
  2608. AVFormatContext *avf = output_files[ost->file_index]->ctx;
  2609. int j;
  2610. if (avf->nb_chapters > INT_MAX - size ||
  2611. !(pts = av_realloc_f(pts, size += avf->nb_chapters - 1,
  2612. sizeof(*pts)))) {
  2613. av_log(NULL, AV_LOG_FATAL,
  2614. "Could not allocate forced key frames array.\n");
  2615. exit_program(1);
  2616. }
  2617. t = p[8] ? parse_time_or_die("force_key_frames", p + 8, 1) : 0;
  2618. t = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
  2619. for (j = 0; j < avf->nb_chapters; j++) {
  2620. AVChapter *c = avf->chapters[j];
  2621. av_assert1(index < size);
  2622. pts[index++] = av_rescale_q(c->start, c->time_base,
  2623. avctx->time_base) + t;
  2624. }
  2625. } else {
  2626. t = parse_time_or_die("force_key_frames", p, 1);
  2627. av_assert1(index < size);
  2628. pts[index++] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
  2629. }
  2630. p = next;
  2631. }
  2632. av_assert0(index == size);
  2633. qsort(pts, size, sizeof(*pts), compare_int64);
  2634. ost->forced_kf_count = size;
  2635. ost->forced_kf_pts = pts;
  2636. }
  2637. static int init_output_stream_encode(OutputStream *ost)
  2638. {
  2639. InputStream *ist = get_input_stream(ost);
  2640. AVCodecContext *enc_ctx = ost->enc_ctx;
  2641. AVCodecContext *dec_ctx = NULL;
  2642. AVFormatContext *oc = output_files[ost->file_index]->ctx;
  2643. int j, ret;
  2644. set_encoder_id(output_files[ost->file_index], ost);
  2645. if (ist) {
  2646. ost->st->disposition = ist->st->disposition;
  2647. dec_ctx = ist->dec_ctx;
  2648. enc_ctx->chroma_sample_location = dec_ctx->chroma_sample_location;
  2649. } else {
  2650. for (j = 0; j < oc->nb_streams; j++) {
  2651. AVStream *st = oc->streams[j];
  2652. if (st != ost->st && st->codecpar->codec_type == ost->st->codecpar->codec_type)
  2653. break;
  2654. }
  2655. if (j == oc->nb_streams)
  2656. if (ost->st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO ||
  2657. ost->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
  2658. ost->st->disposition = AV_DISPOSITION_DEFAULT;
  2659. }
  2660. if ((enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
  2661. enc_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&
  2662. filtergraph_is_simple(ost->filter->graph)) {
  2663. FilterGraph *fg = ost->filter->graph;
  2664. if (configure_filtergraph(fg)) {
  2665. av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
  2666. exit_program(1);
  2667. }
  2668. }
  2669. if (enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO) {
  2670. if (!ost->frame_rate.num)
  2671. ost->frame_rate = av_buffersink_get_frame_rate(ost->filter->filter);
  2672. if (ist && !ost->frame_rate.num)
  2673. ost->frame_rate = ist->framerate;
  2674. if (ist && !ost->frame_rate.num)
  2675. ost->frame_rate = ist->st->r_frame_rate;
  2676. if (ist && !ost->frame_rate.num) {
  2677. ost->frame_rate = (AVRational){25, 1};
  2678. av_log(NULL, AV_LOG_WARNING,
  2679. "No information "
  2680. "about the input framerate is available. Falling "
  2681. "back to a default value of 25fps for output stream #%d:%d. Use the -r option "
  2682. "if you want a different framerate.\n",
  2683. ost->file_index, ost->index);
  2684. }
  2685. // ost->frame_rate = ist->st->avg_frame_rate.num ? ist->st->avg_frame_rate : (AVRational){25, 1};
  2686. if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
  2687. int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
  2688. ost->frame_rate = ost->enc->supported_framerates[idx];
  2689. }
  2690. // reduce frame rate for mpeg4 to be within the spec limits
  2691. if (enc_ctx->codec_id == AV_CODEC_ID_MPEG4) {
  2692. av_reduce(&ost->frame_rate.num, &ost->frame_rate.den,
  2693. ost->frame_rate.num, ost->frame_rate.den, 65535);
  2694. }
  2695. }
  2696. switch (enc_ctx->codec_type) {
  2697. case AVMEDIA_TYPE_AUDIO:
  2698. enc_ctx->sample_fmt = ost->filter->filter->inputs[0]->format;
  2699. if (dec_ctx)
  2700. enc_ctx->bits_per_raw_sample = FFMIN(dec_ctx->bits_per_raw_sample,
  2701. av_get_bytes_per_sample(enc_ctx->sample_fmt) << 3);
  2702. enc_ctx->sample_rate = ost->filter->filter->inputs[0]->sample_rate;
  2703. enc_ctx->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
  2704. enc_ctx->channels = avfilter_link_get_channels(ost->filter->filter->inputs[0]);
  2705. enc_ctx->time_base = (AVRational){ 1, enc_ctx->sample_rate };
  2706. break;
  2707. case AVMEDIA_TYPE_VIDEO:
  2708. enc_ctx->time_base = av_inv_q(ost->frame_rate);
  2709. if (!(enc_ctx->time_base.num && enc_ctx->time_base.den))
  2710. enc_ctx->time_base = ost->filter->filter->inputs[0]->time_base;
  2711. if ( av_q2d(enc_ctx->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH
  2712. && (video_sync_method == VSYNC_CFR || video_sync_method == VSYNC_VSCFR || (video_sync_method == VSYNC_AUTO && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
  2713. av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"
  2714. "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
  2715. }
  2716. for (j = 0; j < ost->forced_kf_count; j++)
  2717. ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
  2718. AV_TIME_BASE_Q,
  2719. enc_ctx->time_base);
  2720. enc_ctx->width = ost->filter->filter->inputs[0]->w;
  2721. enc_ctx->height = ost->filter->filter->inputs[0]->h;
  2722. enc_ctx->sample_aspect_ratio = ost->st->sample_aspect_ratio =
  2723. ost->frame_aspect_ratio.num ? // overridden by the -aspect cli option
  2724. av_mul_q(ost->frame_aspect_ratio, (AVRational){ enc_ctx->height, enc_ctx->width }) :
  2725. ost->filter->filter->inputs[0]->sample_aspect_ratio;
  2726. if (!strncmp(ost->enc->name, "libx264", 7) &&
  2727. enc_ctx->pix_fmt == AV_PIX_FMT_NONE &&
  2728. ost->filter->filter->inputs[0]->format != AV_PIX_FMT_YUV420P)
  2729. av_log(NULL, AV_LOG_WARNING,
  2730. "No pixel format specified, %s for H.264 encoding chosen.\n"
  2731. "Use -pix_fmt yuv420p for compatibility with outdated media players.\n",
  2732. av_get_pix_fmt_name(ost->filter->filter->inputs[0]->format));
  2733. if (!strncmp(ost->enc->name, "mpeg2video", 10) &&
  2734. enc_ctx->pix_fmt == AV_PIX_FMT_NONE &&
  2735. ost->filter->filter->inputs[0]->format != AV_PIX_FMT_YUV420P)
  2736. av_log(NULL, AV_LOG_WARNING,
  2737. "No pixel format specified, %s for MPEG-2 encoding chosen.\n"
  2738. "Use -pix_fmt yuv420p for compatibility with outdated media players.\n",
  2739. av_get_pix_fmt_name(ost->filter->filter->inputs[0]->format));
  2740. enc_ctx->pix_fmt = ost->filter->filter->inputs[0]->format;
  2741. if (dec_ctx)
  2742. enc_ctx->bits_per_raw_sample = FFMIN(dec_ctx->bits_per_raw_sample,
  2743. av_pix_fmt_desc_get(enc_ctx->pix_fmt)->comp[0].depth);
  2744. ost->st->avg_frame_rate = ost->frame_rate;
  2745. if (!dec_ctx ||
  2746. enc_ctx->width != dec_ctx->width ||
  2747. enc_ctx->height != dec_ctx->height ||
  2748. enc_ctx->pix_fmt != dec_ctx->pix_fmt) {
  2749. enc_ctx->bits_per_raw_sample = frame_bits_per_raw_sample;
  2750. }
  2751. if (ost->forced_keyframes) {
  2752. if (!strncmp(ost->forced_keyframes, "expr:", 5)) {
  2753. ret = av_expr_parse(&ost->forced_keyframes_pexpr, ost->forced_keyframes+5,
  2754. forced_keyframes_const_names, NULL, NULL, NULL, NULL, 0, NULL);
  2755. if (ret < 0) {
  2756. av_log(NULL, AV_LOG_ERROR,
  2757. "Invalid force_key_frames expression '%s'\n", ost->forced_keyframes+5);
  2758. return ret;
  2759. }
  2760. ost->forced_keyframes_expr_const_values[FKF_N] = 0;
  2761. ost->forced_keyframes_expr_const_values[FKF_N_FORCED] = 0;
  2762. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] = NAN;
  2763. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] = NAN;
  2764. // Don't parse the 'forced_keyframes' in case of 'keep-source-keyframes',
  2765. // parse it only for static kf timings
  2766. } else if(strncmp(ost->forced_keyframes, "source", 6)) {
  2767. parse_forced_key_frames(ost->forced_keyframes, ost, ost->enc_ctx);
  2768. }
  2769. }
  2770. break;
  2771. case AVMEDIA_TYPE_SUBTITLE:
  2772. enc_ctx->time_base = (AVRational){1, 1000};
  2773. if (!enc_ctx->width) {
  2774. enc_ctx->width = input_streams[ost->source_index]->st->codecpar->width;
  2775. enc_ctx->height = input_streams[ost->source_index]->st->codecpar->height;
  2776. }
  2777. break;
  2778. case AVMEDIA_TYPE_DATA:
  2779. break;
  2780. default:
  2781. abort();
  2782. break;
  2783. }
  2784. return 0;
  2785. }
  2786. static int init_output_stream(OutputStream *ost, char *error, int error_len)
  2787. {
  2788. int ret = 0;
  2789. if (ost->encoding_needed) {
  2790. AVCodec *codec = ost->enc;
  2791. AVCodecContext *dec = NULL;
  2792. InputStream *ist;
  2793. ret = init_output_stream_encode(ost);
  2794. if (ret < 0)
  2795. return ret;
  2796. if ((ist = get_input_stream(ost)))
  2797. dec = ist->dec_ctx;
  2798. if (dec && dec->subtitle_header) {
  2799. /* ASS code assumes this buffer is null terminated so add extra byte. */
  2800. ost->enc_ctx->subtitle_header = av_mallocz(dec->subtitle_header_size + 1);
  2801. if (!ost->enc_ctx->subtitle_header)
  2802. return AVERROR(ENOMEM);
  2803. memcpy(ost->enc_ctx->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
  2804. ost->enc_ctx->subtitle_header_size = dec->subtitle_header_size;
  2805. }
  2806. if (!av_dict_get(ost->encoder_opts, "threads", NULL, 0))
  2807. av_dict_set(&ost->encoder_opts, "threads", "auto", 0);
  2808. if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
  2809. !codec->defaults &&
  2810. !av_dict_get(ost->encoder_opts, "b", NULL, 0) &&
  2811. !av_dict_get(ost->encoder_opts, "ab", NULL, 0))
  2812. av_dict_set(&ost->encoder_opts, "b", "128000", 0);
  2813. if (ost->filter && ost->filter->filter->inputs[0]->hw_frames_ctx) {
  2814. ost->enc_ctx->hw_frames_ctx = av_buffer_ref(ost->filter->filter->inputs[0]->hw_frames_ctx);
  2815. if (!ost->enc_ctx->hw_frames_ctx)
  2816. return AVERROR(ENOMEM);
  2817. }
  2818. if ((ret = avcodec_open2(ost->enc_ctx, codec, &ost->encoder_opts)) < 0) {
  2819. if (ret == AVERROR_EXPERIMENTAL)
  2820. abort_codec_experimental(codec, 1);
  2821. snprintf(error, error_len,
  2822. "Error while opening encoder for output stream #%d:%d - "
  2823. "maybe incorrect parameters such as bit_rate, rate, width or height",
  2824. ost->file_index, ost->index);
  2825. return ret;
  2826. }
  2827. if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
  2828. !(ost->enc->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE))
  2829. av_buffersink_set_frame_size(ost->filter->filter,
  2830. ost->enc_ctx->frame_size);
  2831. assert_avoptions(ost->encoder_opts);
  2832. if (ost->enc_ctx->bit_rate && ost->enc_ctx->bit_rate < 1000)
  2833. av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
  2834. " It takes bits/s as argument, not kbits/s\n");
  2835. ret = avcodec_parameters_from_context(ost->st->codecpar, ost->enc_ctx);
  2836. if (ret < 0) {
  2837. av_log(NULL, AV_LOG_FATAL,
  2838. "Error initializing the output stream codec context.\n");
  2839. exit_program(1);
  2840. }
  2841. /*
  2842. * FIXME: ost->st->codec should't be needed here anymore.
  2843. */
  2844. ret = avcodec_copy_context(ost->st->codec, ost->enc_ctx);
  2845. if (ret < 0)
  2846. return ret;
  2847. if (ost->enc_ctx->nb_coded_side_data) {
  2848. int i;
  2849. ost->st->side_data = av_realloc_array(NULL, ost->enc_ctx->nb_coded_side_data,
  2850. sizeof(*ost->st->side_data));
  2851. if (!ost->st->side_data)
  2852. return AVERROR(ENOMEM);
  2853. for (i = 0; i < ost->enc_ctx->nb_coded_side_data; i++) {
  2854. const AVPacketSideData *sd_src = &ost->enc_ctx->coded_side_data[i];
  2855. AVPacketSideData *sd_dst = &ost->st->side_data[i];
  2856. sd_dst->data = av_malloc(sd_src->size);
  2857. if (!sd_dst->data)
  2858. return AVERROR(ENOMEM);
  2859. memcpy(sd_dst->data, sd_src->data, sd_src->size);
  2860. sd_dst->size = sd_src->size;
  2861. sd_dst->type = sd_src->type;
  2862. ost->st->nb_side_data++;
  2863. }
  2864. }
  2865. // copy timebase while removing common factors
  2866. ost->st->time_base = av_add_q(ost->enc_ctx->time_base, (AVRational){0, 1});
  2867. ost->st->codec->codec= ost->enc_ctx->codec;
  2868. } else if (ost->stream_copy) {
  2869. ret = init_output_stream_streamcopy(ost);
  2870. if (ret < 0)
  2871. return ret;
  2872. /*
  2873. * FIXME: will the codec context used by the parser during streamcopy
  2874. * This should go away with the new parser API.
  2875. */
  2876. ret = avcodec_parameters_to_context(ost->parser_avctx, ost->st->codecpar);
  2877. if (ret < 0)
  2878. return ret;
  2879. }
  2880. // parse user provided disposition, and update stream values
  2881. if (ost->disposition) {
  2882. static const AVOption opts[] = {
  2883. { "disposition" , NULL, 0, AV_OPT_TYPE_FLAGS, { .i64 = 0 }, INT64_MIN, INT64_MAX, .unit = "flags" },
  2884. { "default" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DEFAULT }, .unit = "flags" },
  2885. { "dub" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DUB }, .unit = "flags" },
  2886. { "original" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_ORIGINAL }, .unit = "flags" },
  2887. { "comment" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_COMMENT }, .unit = "flags" },
  2888. { "lyrics" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_LYRICS }, .unit = "flags" },
  2889. { "karaoke" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_KARAOKE }, .unit = "flags" },
  2890. { "forced" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_FORCED }, .unit = "flags" },
  2891. { "hearing_impaired" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_HEARING_IMPAIRED }, .unit = "flags" },
  2892. { "visual_impaired" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_VISUAL_IMPAIRED }, .unit = "flags" },
  2893. { "clean_effects" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_CLEAN_EFFECTS }, .unit = "flags" },
  2894. { "captions" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_CAPTIONS }, .unit = "flags" },
  2895. { "descriptions" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DESCRIPTIONS }, .unit = "flags" },
  2896. { "metadata" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_METADATA }, .unit = "flags" },
  2897. { NULL },
  2898. };
  2899. static const AVClass class = {
  2900. .class_name = "",
  2901. .item_name = av_default_item_name,
  2902. .option = opts,
  2903. .version = LIBAVUTIL_VERSION_INT,
  2904. };
  2905. const AVClass *pclass = &class;
  2906. ret = av_opt_eval_flags(&pclass, &opts[0], ost->disposition, &ost->st->disposition);
  2907. if (ret < 0)
  2908. return ret;
  2909. }
  2910. /* initialize bitstream filters for the output stream
  2911. * needs to be done here, because the codec id for streamcopy is not
  2912. * known until now */
  2913. ret = init_output_bsfs(ost);
  2914. if (ret < 0)
  2915. return ret;
  2916. ost->initialized = 1;
  2917. ret = check_init_output_file(output_files[ost->file_index], ost->file_index);
  2918. if (ret < 0)
  2919. return ret;
  2920. return ret;
  2921. }
  2922. static void report_new_stream(int input_index, AVPacket *pkt)
  2923. {
  2924. InputFile *file = input_files[input_index];
  2925. AVStream *st = file->ctx->streams[pkt->stream_index];
  2926. if (pkt->stream_index < file->nb_streams_warn)
  2927. return;
  2928. av_log(file->ctx, AV_LOG_WARNING,
  2929. "New %s stream %d:%d at pos:%"PRId64" and DTS:%ss\n",
  2930. av_get_media_type_string(st->codecpar->codec_type),
  2931. input_index, pkt->stream_index,
  2932. pkt->pos, av_ts2timestr(pkt->dts, &st->time_base));
  2933. file->nb_streams_warn = pkt->stream_index + 1;
  2934. }
  2935. static int transcode_init(void)
  2936. {
  2937. int ret = 0, i, j, k;
  2938. AVFormatContext *oc;
  2939. OutputStream *ost;
  2940. InputStream *ist;
  2941. char error[1024] = {0};
  2942. for (i = 0; i < nb_filtergraphs; i++) {
  2943. FilterGraph *fg = filtergraphs[i];
  2944. for (j = 0; j < fg->nb_outputs; j++) {
  2945. OutputFilter *ofilter = fg->outputs[j];
  2946. if (!ofilter->ost || ofilter->ost->source_index >= 0)
  2947. continue;
  2948. if (fg->nb_inputs != 1)
  2949. continue;
  2950. for (k = nb_input_streams-1; k >= 0 ; k--)
  2951. if (fg->inputs[0]->ist == input_streams[k])
  2952. break;
  2953. ofilter->ost->source_index = k;
  2954. }
  2955. }
  2956. /* init framerate emulation */
  2957. for (i = 0; i < nb_input_files; i++) {
  2958. InputFile *ifile = input_files[i];
  2959. if (ifile->rate_emu)
  2960. for (j = 0; j < ifile->nb_streams; j++)
  2961. input_streams[j + ifile->ist_index]->start = av_gettime_relative();
  2962. }
  2963. /* hwaccel transcoding */
  2964. for (i = 0; i < nb_output_streams; i++) {
  2965. ost = output_streams[i];
  2966. if (!ost->stream_copy) {
  2967. #if CONFIG_LIBMFX
  2968. if (qsv_transcode_init(ost))
  2969. exit_program(1);
  2970. #endif
  2971. #if CONFIG_CUVID
  2972. if (cuvid_transcode_init(ost))
  2973. exit_program(1);
  2974. #endif
  2975. }
  2976. }
  2977. /* init input streams */
  2978. for (i = 0; i < nb_input_streams; i++)
  2979. if ((ret = init_input_stream(i, error, sizeof(error))) < 0) {
  2980. for (i = 0; i < nb_output_streams; i++) {
  2981. ost = output_streams[i];
  2982. avcodec_close(ost->enc_ctx);
  2983. }
  2984. goto dump_format;
  2985. }
  2986. /* open each encoder */
  2987. for (i = 0; i < nb_output_streams; i++) {
  2988. ret = init_output_stream(output_streams[i], error, sizeof(error));
  2989. if (ret < 0)
  2990. goto dump_format;
  2991. }
  2992. /* discard unused programs */
  2993. for (i = 0; i < nb_input_files; i++) {
  2994. InputFile *ifile = input_files[i];
  2995. for (j = 0; j < ifile->ctx->nb_programs; j++) {
  2996. AVProgram *p = ifile->ctx->programs[j];
  2997. int discard = AVDISCARD_ALL;
  2998. for (k = 0; k < p->nb_stream_indexes; k++)
  2999. if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
  3000. discard = AVDISCARD_DEFAULT;
  3001. break;
  3002. }
  3003. p->discard = discard;
  3004. }
  3005. }
  3006. /* write headers for files with no streams */
  3007. for (i = 0; i < nb_output_files; i++) {
  3008. oc = output_files[i]->ctx;
  3009. if (oc->oformat->flags & AVFMT_NOSTREAMS && oc->nb_streams == 0) {
  3010. ret = check_init_output_file(output_files[i], i);
  3011. if (ret < 0)
  3012. goto dump_format;
  3013. }
  3014. }
  3015. dump_format:
  3016. /* dump the stream mapping */
  3017. av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
  3018. for (i = 0; i < nb_input_streams; i++) {
  3019. ist = input_streams[i];
  3020. for (j = 0; j < ist->nb_filters; j++) {
  3021. if (!filtergraph_is_simple(ist->filters[j]->graph)) {
  3022. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
  3023. ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
  3024. ist->filters[j]->name);
  3025. if (nb_filtergraphs > 1)
  3026. av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
  3027. av_log(NULL, AV_LOG_INFO, "\n");
  3028. }
  3029. }
  3030. }
  3031. for (i = 0; i < nb_output_streams; i++) {
  3032. ost = output_streams[i];
  3033. if (ost->attachment_filename) {
  3034. /* an attached file */
  3035. av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
  3036. ost->attachment_filename, ost->file_index, ost->index);
  3037. continue;
  3038. }
  3039. if (ost->filter && !filtergraph_is_simple(ost->filter->graph)) {
  3040. /* output from a complex graph */
  3041. av_log(NULL, AV_LOG_INFO, " %s", ost->filter->name);
  3042. if (nb_filtergraphs > 1)
  3043. av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
  3044. av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
  3045. ost->index, ost->enc ? ost->enc->name : "?");
  3046. continue;
  3047. }
  3048. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
  3049. input_streams[ost->source_index]->file_index,
  3050. input_streams[ost->source_index]->st->index,
  3051. ost->file_index,
  3052. ost->index);
  3053. if (ost->sync_ist != input_streams[ost->source_index])
  3054. av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
  3055. ost->sync_ist->file_index,
  3056. ost->sync_ist->st->index);
  3057. if (ost->stream_copy)
  3058. av_log(NULL, AV_LOG_INFO, " (copy)");
  3059. else {
  3060. const AVCodec *in_codec = input_streams[ost->source_index]->dec;
  3061. const AVCodec *out_codec = ost->enc;
  3062. const char *decoder_name = "?";
  3063. const char *in_codec_name = "?";
  3064. const char *encoder_name = "?";
  3065. const char *out_codec_name = "?";
  3066. const AVCodecDescriptor *desc;
  3067. if (in_codec) {
  3068. decoder_name = in_codec->name;
  3069. desc = avcodec_descriptor_get(in_codec->id);
  3070. if (desc)
  3071. in_codec_name = desc->name;
  3072. if (!strcmp(decoder_name, in_codec_name))
  3073. decoder_name = "native";
  3074. }
  3075. if (out_codec) {
  3076. encoder_name = out_codec->name;
  3077. desc = avcodec_descriptor_get(out_codec->id);
  3078. if (desc)
  3079. out_codec_name = desc->name;
  3080. if (!strcmp(encoder_name, out_codec_name))
  3081. encoder_name = "native";
  3082. }
  3083. av_log(NULL, AV_LOG_INFO, " (%s (%s) -> %s (%s))",
  3084. in_codec_name, decoder_name,
  3085. out_codec_name, encoder_name);
  3086. }
  3087. av_log(NULL, AV_LOG_INFO, "\n");
  3088. }
  3089. if (ret) {
  3090. av_log(NULL, AV_LOG_ERROR, "%s\n", error);
  3091. return ret;
  3092. }
  3093. transcode_init_done = 1;
  3094. return 0;
  3095. }
  3096. /* Return 1 if there remain streams where more output is wanted, 0 otherwise. */
  3097. static int need_output(void)
  3098. {
  3099. int i;
  3100. for (i = 0; i < nb_output_streams; i++) {
  3101. OutputStream *ost = output_streams[i];
  3102. OutputFile *of = output_files[ost->file_index];
  3103. AVFormatContext *os = output_files[ost->file_index]->ctx;
  3104. if (ost->finished ||
  3105. (os->pb && avio_tell(os->pb) >= of->limit_filesize))
  3106. continue;
  3107. if (ost->frame_number >= ost->max_frames) {
  3108. int j;
  3109. for (j = 0; j < of->ctx->nb_streams; j++)
  3110. close_output_stream(output_streams[of->ost_index + j]);
  3111. continue;
  3112. }
  3113. return 1;
  3114. }
  3115. return 0;
  3116. }
  3117. /**
  3118. * Select the output stream to process.
  3119. *
  3120. * @return selected output stream, or NULL if none available
  3121. */
  3122. static OutputStream *choose_output(void)
  3123. {
  3124. int i;
  3125. int64_t opts_min = INT64_MAX;
  3126. OutputStream *ost_min = NULL;
  3127. for (i = 0; i < nb_output_streams; i++) {
  3128. OutputStream *ost = output_streams[i];
  3129. int64_t opts = ost->st->cur_dts == AV_NOPTS_VALUE ? INT64_MIN :
  3130. av_rescale_q(ost->st->cur_dts, ost->st->time_base,
  3131. AV_TIME_BASE_Q);
  3132. if (ost->st->cur_dts == AV_NOPTS_VALUE)
  3133. av_log(NULL, AV_LOG_DEBUG, "cur_dts is invalid (this is harmless if it occurs once at the start per stream)\n");
  3134. if (!ost->finished && opts < opts_min) {
  3135. opts_min = opts;
  3136. ost_min = ost->unavailable ? NULL : ost;
  3137. }
  3138. }
  3139. return ost_min;
  3140. }
  3141. static void set_tty_echo(int on)
  3142. {
  3143. #if HAVE_TERMIOS_H
  3144. struct termios tty;
  3145. if (tcgetattr(0, &tty) == 0) {
  3146. if (on) tty.c_lflag |= ECHO;
  3147. else tty.c_lflag &= ~ECHO;
  3148. tcsetattr(0, TCSANOW, &tty);
  3149. }
  3150. #endif
  3151. }
  3152. static int check_keyboard_interaction(int64_t cur_time)
  3153. {
  3154. int i, ret, key;
  3155. static int64_t last_time;
  3156. if (received_nb_signals)
  3157. return AVERROR_EXIT;
  3158. /* read_key() returns 0 on EOF */
  3159. if(cur_time - last_time >= 100000 && !run_as_daemon){
  3160. key = read_key();
  3161. last_time = cur_time;
  3162. }else
  3163. key = -1;
  3164. if (key == 'q')
  3165. return AVERROR_EXIT;
  3166. if (key == '+') av_log_set_level(av_log_get_level()+10);
  3167. if (key == '-') av_log_set_level(av_log_get_level()-10);
  3168. if (key == 's') qp_hist ^= 1;
  3169. if (key == 'h'){
  3170. if (do_hex_dump){
  3171. do_hex_dump = do_pkt_dump = 0;
  3172. } else if(do_pkt_dump){
  3173. do_hex_dump = 1;
  3174. } else
  3175. do_pkt_dump = 1;
  3176. av_log_set_level(AV_LOG_DEBUG);
  3177. }
  3178. if (key == 'c' || key == 'C'){
  3179. char buf[4096], target[64], command[256], arg[256] = {0};
  3180. double time;
  3181. int k, n = 0;
  3182. fprintf(stderr, "\nEnter command: <target>|all <time>|-1 <command>[ <argument>]\n");
  3183. i = 0;
  3184. set_tty_echo(1);
  3185. while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
  3186. if (k > 0)
  3187. buf[i++] = k;
  3188. buf[i] = 0;
  3189. set_tty_echo(0);
  3190. fprintf(stderr, "\n");
  3191. if (k > 0 &&
  3192. (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
  3193. av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
  3194. target, time, command, arg);
  3195. for (i = 0; i < nb_filtergraphs; i++) {
  3196. FilterGraph *fg = filtergraphs[i];
  3197. if (fg->graph) {
  3198. if (time < 0) {
  3199. ret = avfilter_graph_send_command(fg->graph, target, command, arg, buf, sizeof(buf),
  3200. key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
  3201. fprintf(stderr, "Command reply for stream %d: ret:%d res:\n%s", i, ret, buf);
  3202. } else if (key == 'c') {
  3203. fprintf(stderr, "Queuing commands only on filters supporting the specific command is unsupported\n");
  3204. ret = AVERROR_PATCHWELCOME;
  3205. } else {
  3206. ret = avfilter_graph_queue_command(fg->graph, target, command, arg, 0, time);
  3207. if (ret < 0)
  3208. fprintf(stderr, "Queuing command failed with error %s\n", av_err2str(ret));
  3209. }
  3210. }
  3211. }
  3212. } else {
  3213. av_log(NULL, AV_LOG_ERROR,
  3214. "Parse error, at least 3 arguments were expected, "
  3215. "only %d given in string '%s'\n", n, buf);
  3216. }
  3217. }
  3218. if (key == 'd' || key == 'D'){
  3219. int debug=0;
  3220. if(key == 'D') {
  3221. debug = input_streams[0]->st->codec->debug<<1;
  3222. if(!debug) debug = 1;
  3223. while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
  3224. debug += debug;
  3225. }else{
  3226. char buf[32];
  3227. int k = 0;
  3228. i = 0;
  3229. set_tty_echo(1);
  3230. while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
  3231. if (k > 0)
  3232. buf[i++] = k;
  3233. buf[i] = 0;
  3234. set_tty_echo(0);
  3235. fprintf(stderr, "\n");
  3236. if (k <= 0 || sscanf(buf, "%d", &debug)!=1)
  3237. fprintf(stderr,"error parsing debug value\n");
  3238. }
  3239. for(i=0;i<nb_input_streams;i++) {
  3240. input_streams[i]->st->codec->debug = debug;
  3241. }
  3242. for(i=0;i<nb_output_streams;i++) {
  3243. OutputStream *ost = output_streams[i];
  3244. ost->enc_ctx->debug = debug;
  3245. }
  3246. if(debug) av_log_set_level(AV_LOG_DEBUG);
  3247. fprintf(stderr,"debug=%d\n", debug);
  3248. }
  3249. if (key == '?'){
  3250. fprintf(stderr, "key function\n"
  3251. "? show this help\n"
  3252. "+ increase verbosity\n"
  3253. "- decrease verbosity\n"
  3254. "c Send command to first matching filter supporting it\n"
  3255. "C Send/Queue command to all matching filters\n"
  3256. "D cycle through available debug modes\n"
  3257. "h dump packets/hex press to cycle through the 3 states\n"
  3258. "q quit\n"
  3259. "s Show QP histogram\n"
  3260. );
  3261. }
  3262. return 0;
  3263. }
  3264. #if HAVE_PTHREADS
  3265. static void *input_thread(void *arg)
  3266. {
  3267. InputFile *f = arg;
  3268. unsigned flags = f->non_blocking ? AV_THREAD_MESSAGE_NONBLOCK : 0;
  3269. int ret = 0;
  3270. while (1) {
  3271. AVPacket pkt;
  3272. ret = av_read_frame(f->ctx, &pkt);
  3273. if (ret == AVERROR(EAGAIN)) {
  3274. av_usleep(10000);
  3275. continue;
  3276. }
  3277. if (ret < 0) {
  3278. av_thread_message_queue_set_err_recv(f->in_thread_queue, ret);
  3279. break;
  3280. }
  3281. ret = av_thread_message_queue_send(f->in_thread_queue, &pkt, flags);
  3282. if (flags && ret == AVERROR(EAGAIN)) {
  3283. flags = 0;
  3284. ret = av_thread_message_queue_send(f->in_thread_queue, &pkt, flags);
  3285. av_log(f->ctx, AV_LOG_WARNING,
  3286. "Thread message queue blocking; consider raising the "
  3287. "thread_queue_size option (current value: %d)\n",
  3288. f->thread_queue_size);
  3289. }
  3290. if (ret < 0) {
  3291. if (ret != AVERROR_EOF)
  3292. av_log(f->ctx, AV_LOG_ERROR,
  3293. "Unable to send packet to main thread: %s\n",
  3294. av_err2str(ret));
  3295. av_packet_unref(&pkt);
  3296. av_thread_message_queue_set_err_recv(f->in_thread_queue, ret);
  3297. break;
  3298. }
  3299. }
  3300. return NULL;
  3301. }
  3302. static void free_input_threads(void)
  3303. {
  3304. int i;
  3305. for (i = 0; i < nb_input_files; i++) {
  3306. InputFile *f = input_files[i];
  3307. AVPacket pkt;
  3308. if (!f || !f->in_thread_queue)
  3309. continue;
  3310. av_thread_message_queue_set_err_send(f->in_thread_queue, AVERROR_EOF);
  3311. while (av_thread_message_queue_recv(f->in_thread_queue, &pkt, 0) >= 0)
  3312. av_packet_unref(&pkt);
  3313. pthread_join(f->thread, NULL);
  3314. f->joined = 1;
  3315. av_thread_message_queue_free(&f->in_thread_queue);
  3316. }
  3317. }
  3318. static int init_input_threads(void)
  3319. {
  3320. int i, ret;
  3321. if (nb_input_files == 1)
  3322. return 0;
  3323. for (i = 0; i < nb_input_files; i++) {
  3324. InputFile *f = input_files[i];
  3325. if (f->ctx->pb ? !f->ctx->pb->seekable :
  3326. strcmp(f->ctx->iformat->name, "lavfi"))
  3327. f->non_blocking = 1;
  3328. ret = av_thread_message_queue_alloc(&f->in_thread_queue,
  3329. f->thread_queue_size, sizeof(AVPacket));
  3330. if (ret < 0)
  3331. return ret;
  3332. if ((ret = pthread_create(&f->thread, NULL, input_thread, f))) {
  3333. av_log(NULL, AV_LOG_ERROR, "pthread_create failed: %s. Try to increase `ulimit -v` or decrease `ulimit -s`.\n", strerror(ret));
  3334. av_thread_message_queue_free(&f->in_thread_queue);
  3335. return AVERROR(ret);
  3336. }
  3337. }
  3338. return 0;
  3339. }
  3340. static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
  3341. {
  3342. return av_thread_message_queue_recv(f->in_thread_queue, pkt,
  3343. f->non_blocking ?
  3344. AV_THREAD_MESSAGE_NONBLOCK : 0);
  3345. }
  3346. #endif
  3347. static int get_input_packet(InputFile *f, AVPacket *pkt)
  3348. {
  3349. if (f->rate_emu) {
  3350. int i;
  3351. for (i = 0; i < f->nb_streams; i++) {
  3352. InputStream *ist = input_streams[f->ist_index + i];
  3353. int64_t pts = av_rescale(ist->dts, 1000000, AV_TIME_BASE);
  3354. int64_t now = av_gettime_relative() - ist->start;
  3355. if (pts > now)
  3356. return AVERROR(EAGAIN);
  3357. }
  3358. }
  3359. #if HAVE_PTHREADS
  3360. if (nb_input_files > 1)
  3361. return get_input_packet_mt(f, pkt);
  3362. #endif
  3363. return av_read_frame(f->ctx, pkt);
  3364. }
  3365. static int got_eagain(void)
  3366. {
  3367. int i;
  3368. for (i = 0; i < nb_output_streams; i++)
  3369. if (output_streams[i]->unavailable)
  3370. return 1;
  3371. return 0;
  3372. }
  3373. static void reset_eagain(void)
  3374. {
  3375. int i;
  3376. for (i = 0; i < nb_input_files; i++)
  3377. input_files[i]->eagain = 0;
  3378. for (i = 0; i < nb_output_streams; i++)
  3379. output_streams[i]->unavailable = 0;
  3380. }
  3381. // set duration to max(tmp, duration) in a proper time base and return duration's time_base
  3382. static AVRational duration_max(int64_t tmp, int64_t *duration, AVRational tmp_time_base,
  3383. AVRational time_base)
  3384. {
  3385. int ret;
  3386. if (!*duration) {
  3387. *duration = tmp;
  3388. return tmp_time_base;
  3389. }
  3390. ret = av_compare_ts(*duration, time_base, tmp, tmp_time_base);
  3391. if (ret < 0) {
  3392. *duration = tmp;
  3393. return tmp_time_base;
  3394. }
  3395. return time_base;
  3396. }
  3397. static int seek_to_start(InputFile *ifile, AVFormatContext *is)
  3398. {
  3399. InputStream *ist;
  3400. AVCodecContext *avctx;
  3401. int i, ret, has_audio = 0;
  3402. int64_t duration = 0;
  3403. ret = av_seek_frame(is, -1, is->start_time, 0);
  3404. if (ret < 0)
  3405. return ret;
  3406. for (i = 0; i < ifile->nb_streams; i++) {
  3407. ist = input_streams[ifile->ist_index + i];
  3408. avctx = ist->dec_ctx;
  3409. // flush decoders
  3410. if (ist->decoding_needed) {
  3411. process_input_packet(ist, NULL, 1);
  3412. avcodec_flush_buffers(avctx);
  3413. }
  3414. /* duration is the length of the last frame in a stream
  3415. * when audio stream is present we don't care about
  3416. * last video frame length because it's not defined exactly */
  3417. if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && ist->nb_samples)
  3418. has_audio = 1;
  3419. }
  3420. for (i = 0; i < ifile->nb_streams; i++) {
  3421. ist = input_streams[ifile->ist_index + i];
  3422. avctx = ist->dec_ctx;
  3423. if (has_audio) {
  3424. if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && ist->nb_samples) {
  3425. AVRational sample_rate = {1, avctx->sample_rate};
  3426. duration = av_rescale_q(ist->nb_samples, sample_rate, ist->st->time_base);
  3427. } else
  3428. continue;
  3429. } else {
  3430. if (ist->framerate.num) {
  3431. duration = av_rescale_q(1, ist->framerate, ist->st->time_base);
  3432. } else if (ist->st->avg_frame_rate.num) {
  3433. duration = av_rescale_q(1, ist->st->avg_frame_rate, ist->st->time_base);
  3434. } else duration = 1;
  3435. }
  3436. if (!ifile->duration)
  3437. ifile->time_base = ist->st->time_base;
  3438. /* the total duration of the stream, max_pts - min_pts is
  3439. * the duration of the stream without the last frame */
  3440. duration += ist->max_pts - ist->min_pts;
  3441. ifile->time_base = duration_max(duration, &ifile->duration, ist->st->time_base,
  3442. ifile->time_base);
  3443. }
  3444. if (ifile->loop > 0)
  3445. ifile->loop--;
  3446. return ret;
  3447. }
  3448. /*
  3449. * Return
  3450. * - 0 -- one packet was read and processed
  3451. * - AVERROR(EAGAIN) -- no packets were available for selected file,
  3452. * this function should be called again
  3453. * - AVERROR_EOF -- this function should not be called again
  3454. */
  3455. static int process_input(int file_index)
  3456. {
  3457. InputFile *ifile = input_files[file_index];
  3458. AVFormatContext *is;
  3459. InputStream *ist;
  3460. AVPacket pkt;
  3461. int ret, i, j;
  3462. int64_t duration;
  3463. int64_t pkt_dts;
  3464. is = ifile->ctx;
  3465. ret = get_input_packet(ifile, &pkt);
  3466. if (ret == AVERROR(EAGAIN)) {
  3467. ifile->eagain = 1;
  3468. return ret;
  3469. }
  3470. if (ret < 0 && ifile->loop) {
  3471. if ((ret = seek_to_start(ifile, is)) < 0)
  3472. return ret;
  3473. ret = get_input_packet(ifile, &pkt);
  3474. if (ret == AVERROR(EAGAIN)) {
  3475. ifile->eagain = 1;
  3476. return ret;
  3477. }
  3478. }
  3479. if (ret < 0) {
  3480. if (ret != AVERROR_EOF) {
  3481. print_error(is->filename, ret);
  3482. if (exit_on_error)
  3483. exit_program(1);
  3484. }
  3485. for (i = 0; i < ifile->nb_streams; i++) {
  3486. ist = input_streams[ifile->ist_index + i];
  3487. if (ist->decoding_needed) {
  3488. ret = process_input_packet(ist, NULL, 0);
  3489. if (ret>0)
  3490. return 0;
  3491. }
  3492. /* mark all outputs that don't go through lavfi as finished */
  3493. for (j = 0; j < nb_output_streams; j++) {
  3494. OutputStream *ost = output_streams[j];
  3495. if (ost->source_index == ifile->ist_index + i &&
  3496. (ost->stream_copy || ost->enc->type == AVMEDIA_TYPE_SUBTITLE))
  3497. finish_output_stream(ost);
  3498. }
  3499. }
  3500. ifile->eof_reached = 1;
  3501. return AVERROR(EAGAIN);
  3502. }
  3503. reset_eagain();
  3504. if (do_pkt_dump) {
  3505. av_pkt_dump_log2(NULL, AV_LOG_INFO, &pkt, do_hex_dump,
  3506. is->streams[pkt.stream_index]);
  3507. }
  3508. /* the following test is needed in case new streams appear
  3509. dynamically in stream : we ignore them */
  3510. if (pkt.stream_index >= ifile->nb_streams) {
  3511. report_new_stream(file_index, &pkt);
  3512. goto discard_packet;
  3513. }
  3514. ist = input_streams[ifile->ist_index + pkt.stream_index];
  3515. ist->data_size += pkt.size;
  3516. ist->nb_packets++;
  3517. if (ist->discard)
  3518. goto discard_packet;
  3519. if (exit_on_error && (pkt.flags & AV_PKT_FLAG_CORRUPT)) {
  3520. av_log(NULL, AV_LOG_FATAL, "%s: corrupt input packet in stream %d\n", is->filename, pkt.stream_index);
  3521. exit_program(1);
  3522. }
  3523. if (debug_ts) {
  3524. av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
  3525. "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",
  3526. ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->dec_ctx->codec_type),
  3527. av_ts2str(ist->next_dts), av_ts2timestr(ist->next_dts, &AV_TIME_BASE_Q),
  3528. av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &AV_TIME_BASE_Q),
  3529. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
  3530. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
  3531. av_ts2str(input_files[ist->file_index]->ts_offset),
  3532. av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
  3533. }
  3534. if(!ist->wrap_correction_done && is->start_time != AV_NOPTS_VALUE && ist->st->pts_wrap_bits < 64){
  3535. int64_t stime, stime2;
  3536. // Correcting starttime based on the enabled streams
  3537. // 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.
  3538. // so we instead do it here as part of discontinuity handling
  3539. if ( ist->next_dts == AV_NOPTS_VALUE
  3540. && ifile->ts_offset == -is->start_time
  3541. && (is->iformat->flags & AVFMT_TS_DISCONT)) {
  3542. int64_t new_start_time = INT64_MAX;
  3543. for (i=0; i<is->nb_streams; i++) {
  3544. AVStream *st = is->streams[i];
  3545. if(st->discard == AVDISCARD_ALL || st->start_time == AV_NOPTS_VALUE)
  3546. continue;
  3547. new_start_time = FFMIN(new_start_time, av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q));
  3548. }
  3549. if (new_start_time > is->start_time) {
  3550. av_log(is, AV_LOG_VERBOSE, "Correcting start time by %"PRId64"\n", new_start_time - is->start_time);
  3551. ifile->ts_offset = -new_start_time;
  3552. }
  3553. }
  3554. stime = av_rescale_q(is->start_time, AV_TIME_BASE_Q, ist->st->time_base);
  3555. stime2= stime + (1ULL<<ist->st->pts_wrap_bits);
  3556. ist->wrap_correction_done = 1;
  3557. if(stime2 > stime && pkt.dts != AV_NOPTS_VALUE && pkt.dts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
  3558. pkt.dts -= 1ULL<<ist->st->pts_wrap_bits;
  3559. ist->wrap_correction_done = 0;
  3560. }
  3561. if(stime2 > stime && pkt.pts != AV_NOPTS_VALUE && pkt.pts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
  3562. pkt.pts -= 1ULL<<ist->st->pts_wrap_bits;
  3563. ist->wrap_correction_done = 0;
  3564. }
  3565. }
  3566. /* add the stream-global side data to the first packet */
  3567. if (ist->nb_packets == 1) {
  3568. if (ist->st->nb_side_data)
  3569. av_packet_split_side_data(&pkt);
  3570. for (i = 0; i < ist->st->nb_side_data; i++) {
  3571. AVPacketSideData *src_sd = &ist->st->side_data[i];
  3572. uint8_t *dst_data;
  3573. if (av_packet_get_side_data(&pkt, src_sd->type, NULL))
  3574. continue;
  3575. if (ist->autorotate && src_sd->type == AV_PKT_DATA_DISPLAYMATRIX)
  3576. continue;
  3577. dst_data = av_packet_new_side_data(&pkt, src_sd->type, src_sd->size);
  3578. if (!dst_data)
  3579. exit_program(1);
  3580. memcpy(dst_data, src_sd->data, src_sd->size);
  3581. }
  3582. }
  3583. if (pkt.dts != AV_NOPTS_VALUE)
  3584. pkt.dts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
  3585. if (pkt.pts != AV_NOPTS_VALUE)
  3586. pkt.pts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
  3587. if (pkt.pts != AV_NOPTS_VALUE)
  3588. pkt.pts *= ist->ts_scale;
  3589. if (pkt.dts != AV_NOPTS_VALUE)
  3590. pkt.dts *= ist->ts_scale;
  3591. pkt_dts = av_rescale_q_rnd(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
  3592. if ((ist->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
  3593. ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&
  3594. pkt_dts != AV_NOPTS_VALUE && ist->next_dts == AV_NOPTS_VALUE && !copy_ts
  3595. && (is->iformat->flags & AVFMT_TS_DISCONT) && ifile->last_ts != AV_NOPTS_VALUE) {
  3596. int64_t delta = pkt_dts - ifile->last_ts;
  3597. if (delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
  3598. delta > 1LL*dts_delta_threshold*AV_TIME_BASE){
  3599. ifile->ts_offset -= delta;
  3600. av_log(NULL, AV_LOG_DEBUG,
  3601. "Inter stream timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
  3602. delta, ifile->ts_offset);
  3603. pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  3604. if (pkt.pts != AV_NOPTS_VALUE)
  3605. pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  3606. }
  3607. }
  3608. duration = av_rescale_q(ifile->duration, ifile->time_base, ist->st->time_base);
  3609. if (pkt.pts != AV_NOPTS_VALUE) {
  3610. pkt.pts += duration;
  3611. ist->max_pts = FFMAX(pkt.pts, ist->max_pts);
  3612. ist->min_pts = FFMIN(pkt.pts, ist->min_pts);
  3613. }
  3614. if (pkt.dts != AV_NOPTS_VALUE)
  3615. pkt.dts += duration;
  3616. pkt_dts = av_rescale_q_rnd(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
  3617. if ((ist->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
  3618. ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&
  3619. pkt_dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE &&
  3620. !copy_ts) {
  3621. int64_t delta = pkt_dts - ist->next_dts;
  3622. if (is->iformat->flags & AVFMT_TS_DISCONT) {
  3623. if (delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
  3624. delta > 1LL*dts_delta_threshold*AV_TIME_BASE ||
  3625. pkt_dts + AV_TIME_BASE/10 < FFMAX(ist->pts, ist->dts)) {
  3626. ifile->ts_offset -= delta;
  3627. av_log(NULL, AV_LOG_DEBUG,
  3628. "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
  3629. delta, ifile->ts_offset);
  3630. pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  3631. if (pkt.pts != AV_NOPTS_VALUE)
  3632. pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  3633. }
  3634. } else {
  3635. if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
  3636. delta > 1LL*dts_error_threshold*AV_TIME_BASE) {
  3637. av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);
  3638. pkt.dts = AV_NOPTS_VALUE;
  3639. }
  3640. if (pkt.pts != AV_NOPTS_VALUE){
  3641. int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);
  3642. delta = pkt_pts - ist->next_dts;
  3643. if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
  3644. delta > 1LL*dts_error_threshold*AV_TIME_BASE) {
  3645. av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);
  3646. pkt.pts = AV_NOPTS_VALUE;
  3647. }
  3648. }
  3649. }
  3650. }
  3651. if (pkt.dts != AV_NOPTS_VALUE)
  3652. ifile->last_ts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
  3653. if (debug_ts) {
  3654. 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",
  3655. ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->dec_ctx->codec_type),
  3656. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
  3657. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
  3658. av_ts2str(input_files[ist->file_index]->ts_offset),
  3659. av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
  3660. }
  3661. sub2video_heartbeat(ist, pkt.pts);
  3662. process_input_packet(ist, &pkt, 0);
  3663. discard_packet:
  3664. av_packet_unref(&pkt);
  3665. return 0;
  3666. }
  3667. /**
  3668. * Perform a step of transcoding for the specified filter graph.
  3669. *
  3670. * @param[in] graph filter graph to consider
  3671. * @param[out] best_ist input stream where a frame would allow to continue
  3672. * @return 0 for success, <0 for error
  3673. */
  3674. static int transcode_from_filter(FilterGraph *graph, InputStream **best_ist)
  3675. {
  3676. int i, ret;
  3677. int nb_requests, nb_requests_max = 0;
  3678. InputFilter *ifilter;
  3679. InputStream *ist;
  3680. *best_ist = NULL;
  3681. ret = avfilter_graph_request_oldest(graph->graph);
  3682. if (ret >= 0)
  3683. return reap_filters(0);
  3684. if (ret == AVERROR_EOF) {
  3685. ret = reap_filters(1);
  3686. for (i = 0; i < graph->nb_outputs; i++)
  3687. close_output_stream(graph->outputs[i]->ost);
  3688. return ret;
  3689. }
  3690. if (ret != AVERROR(EAGAIN))
  3691. return ret;
  3692. for (i = 0; i < graph->nb_inputs; i++) {
  3693. ifilter = graph->inputs[i];
  3694. ist = ifilter->ist;
  3695. if (input_files[ist->file_index]->eagain ||
  3696. input_files[ist->file_index]->eof_reached)
  3697. continue;
  3698. nb_requests = av_buffersrc_get_nb_failed_requests(ifilter->filter);
  3699. if (nb_requests > nb_requests_max) {
  3700. nb_requests_max = nb_requests;
  3701. *best_ist = ist;
  3702. }
  3703. }
  3704. if (!*best_ist)
  3705. for (i = 0; i < graph->nb_outputs; i++)
  3706. graph->outputs[i]->ost->unavailable = 1;
  3707. return 0;
  3708. }
  3709. /**
  3710. * Run a single step of transcoding.
  3711. *
  3712. * @return 0 for success, <0 for error
  3713. */
  3714. static int transcode_step(void)
  3715. {
  3716. OutputStream *ost;
  3717. InputStream *ist;
  3718. int ret;
  3719. ost = choose_output();
  3720. if (!ost) {
  3721. if (got_eagain()) {
  3722. reset_eagain();
  3723. av_usleep(10000);
  3724. return 0;
  3725. }
  3726. av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from, finishing.\n");
  3727. return AVERROR_EOF;
  3728. }
  3729. if (ost->filter) {
  3730. if ((ret = transcode_from_filter(ost->filter->graph, &ist)) < 0)
  3731. return ret;
  3732. if (!ist)
  3733. return 0;
  3734. } else {
  3735. av_assert0(ost->source_index >= 0);
  3736. ist = input_streams[ost->source_index];
  3737. }
  3738. ret = process_input(ist->file_index);
  3739. if (ret == AVERROR(EAGAIN)) {
  3740. if (input_files[ist->file_index]->eagain)
  3741. ost->unavailable = 1;
  3742. return 0;
  3743. }
  3744. if (ret < 0)
  3745. return ret == AVERROR_EOF ? 0 : ret;
  3746. return reap_filters(0);
  3747. }
  3748. /*
  3749. * The following code is the main loop of the file converter
  3750. */
  3751. static int transcode(void)
  3752. {
  3753. int ret, i;
  3754. AVFormatContext *os;
  3755. OutputStream *ost;
  3756. InputStream *ist;
  3757. int64_t timer_start;
  3758. int64_t total_packets_written = 0;
  3759. ret = transcode_init();
  3760. if (ret < 0)
  3761. goto fail;
  3762. if (stdin_interaction) {
  3763. av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
  3764. }
  3765. timer_start = av_gettime_relative();
  3766. #if HAVE_PTHREADS
  3767. if ((ret = init_input_threads()) < 0)
  3768. goto fail;
  3769. #endif
  3770. while (!received_sigterm) {
  3771. int64_t cur_time= av_gettime_relative();
  3772. /* if 'q' pressed, exits */
  3773. if (stdin_interaction)
  3774. if (check_keyboard_interaction(cur_time) < 0)
  3775. break;
  3776. /* check if there's any stream where output is still needed */
  3777. if (!need_output()) {
  3778. av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
  3779. break;
  3780. }
  3781. ret = transcode_step();
  3782. if (ret < 0 && ret != AVERROR_EOF) {
  3783. char errbuf[128];
  3784. av_strerror(ret, errbuf, sizeof(errbuf));
  3785. av_log(NULL, AV_LOG_ERROR, "Error while filtering: %s\n", errbuf);
  3786. break;
  3787. }
  3788. /* dump report by using the output first video and audio streams */
  3789. print_report(0, timer_start, cur_time);
  3790. }
  3791. #if HAVE_PTHREADS
  3792. free_input_threads();
  3793. #endif
  3794. /* at the end of stream, we must flush the decoder buffers */
  3795. for (i = 0; i < nb_input_streams; i++) {
  3796. ist = input_streams[i];
  3797. if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
  3798. process_input_packet(ist, NULL, 0);
  3799. }
  3800. }
  3801. flush_encoders();
  3802. term_exit();
  3803. /* write the trailer if needed and close file */
  3804. for (i = 0; i < nb_output_files; i++) {
  3805. os = output_files[i]->ctx;
  3806. if (!output_files[i]->header_written) {
  3807. av_log(NULL, AV_LOG_ERROR,
  3808. "Nothing was written into output file %d (%s), because "
  3809. "at least one of its streams received no packets.\n",
  3810. i, os->filename);
  3811. continue;
  3812. }
  3813. if ((ret = av_write_trailer(os)) < 0) {
  3814. av_log(NULL, AV_LOG_ERROR, "Error writing trailer of %s: %s", os->filename, av_err2str(ret));
  3815. if (exit_on_error)
  3816. exit_program(1);
  3817. }
  3818. }
  3819. /* dump report by using the first video and audio streams */
  3820. print_report(1, timer_start, av_gettime_relative());
  3821. /* close each encoder */
  3822. for (i = 0; i < nb_output_streams; i++) {
  3823. ost = output_streams[i];
  3824. if (ost->encoding_needed) {
  3825. av_freep(&ost->enc_ctx->stats_in);
  3826. }
  3827. total_packets_written += ost->packets_written;
  3828. }
  3829. if (!total_packets_written && (abort_on_flags & ABORT_ON_FLAG_EMPTY_OUTPUT)) {
  3830. av_log(NULL, AV_LOG_FATAL, "Empty output\n");
  3831. exit_program(1);
  3832. }
  3833. /* close each decoder */
  3834. for (i = 0; i < nb_input_streams; i++) {
  3835. ist = input_streams[i];
  3836. if (ist->decoding_needed) {
  3837. avcodec_close(ist->dec_ctx);
  3838. if (ist->hwaccel_uninit)
  3839. ist->hwaccel_uninit(ist->dec_ctx);
  3840. }
  3841. }
  3842. av_buffer_unref(&hw_device_ctx);
  3843. /* finished ! */
  3844. ret = 0;
  3845. fail:
  3846. #if HAVE_PTHREADS
  3847. free_input_threads();
  3848. #endif
  3849. if (output_streams) {
  3850. for (i = 0; i < nb_output_streams; i++) {
  3851. ost = output_streams[i];
  3852. if (ost) {
  3853. if (ost->logfile) {
  3854. if (fclose(ost->logfile))
  3855. av_log(NULL, AV_LOG_ERROR,
  3856. "Error closing logfile, loss of information possible: %s\n",
  3857. av_err2str(AVERROR(errno)));
  3858. ost->logfile = NULL;
  3859. }
  3860. av_freep(&ost->forced_kf_pts);
  3861. av_freep(&ost->apad);
  3862. av_freep(&ost->disposition);
  3863. av_dict_free(&ost->encoder_opts);
  3864. av_dict_free(&ost->sws_dict);
  3865. av_dict_free(&ost->swr_opts);
  3866. av_dict_free(&ost->resample_opts);
  3867. }
  3868. }
  3869. }
  3870. return ret;
  3871. }
  3872. static int64_t getutime(void)
  3873. {
  3874. #if HAVE_GETRUSAGE
  3875. struct rusage rusage;
  3876. getrusage(RUSAGE_SELF, &rusage);
  3877. return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
  3878. #elif HAVE_GETPROCESSTIMES
  3879. HANDLE proc;
  3880. FILETIME c, e, k, u;
  3881. proc = GetCurrentProcess();
  3882. GetProcessTimes(proc, &c, &e, &k, &u);
  3883. return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
  3884. #else
  3885. return av_gettime_relative();
  3886. #endif
  3887. }
  3888. static int64_t getmaxrss(void)
  3889. {
  3890. #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
  3891. struct rusage rusage;
  3892. getrusage(RUSAGE_SELF, &rusage);
  3893. return (int64_t)rusage.ru_maxrss * 1024;
  3894. #elif HAVE_GETPROCESSMEMORYINFO
  3895. HANDLE proc;
  3896. PROCESS_MEMORY_COUNTERS memcounters;
  3897. proc = GetCurrentProcess();
  3898. memcounters.cb = sizeof(memcounters);
  3899. GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
  3900. return memcounters.PeakPagefileUsage;
  3901. #else
  3902. return 0;
  3903. #endif
  3904. }
  3905. static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
  3906. {
  3907. }
  3908. int main(int argc, char **argv)
  3909. {
  3910. int i, ret;
  3911. int64_t ti;
  3912. init_dynload();
  3913. register_exit(ffmpeg_cleanup);
  3914. setvbuf(stderr,NULL,_IONBF,0); /* win32 runtime needs this */
  3915. av_log_set_flags(AV_LOG_SKIP_REPEATED);
  3916. parse_loglevel(argc, argv, options);
  3917. if(argc>1 && !strcmp(argv[1], "-d")){
  3918. run_as_daemon=1;
  3919. av_log_set_callback(log_callback_null);
  3920. argc--;
  3921. argv++;
  3922. }
  3923. avcodec_register_all();
  3924. #if CONFIG_AVDEVICE
  3925. avdevice_register_all();
  3926. #endif
  3927. avfilter_register_all();
  3928. av_register_all();
  3929. avformat_network_init();
  3930. show_banner(argc, argv, options);
  3931. /* parse options and open all input/output files */
  3932. ret = ffmpeg_parse_options(argc, argv);
  3933. if (ret < 0)
  3934. exit_program(1);
  3935. if (nb_output_files <= 0 && nb_input_files == 0) {
  3936. show_usage();
  3937. av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
  3938. exit_program(1);
  3939. }
  3940. /* file converter / grab */
  3941. if (nb_output_files <= 0) {
  3942. av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
  3943. exit_program(1);
  3944. }
  3945. // if (nb_input_files == 0) {
  3946. // av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
  3947. // exit_program(1);
  3948. // }
  3949. for (i = 0; i < nb_output_files; i++) {
  3950. if (strcmp(output_files[i]->ctx->oformat->name, "rtp"))
  3951. want_sdp = 0;
  3952. }
  3953. current_time = ti = getutime();
  3954. if (transcode() < 0)
  3955. exit_program(1);
  3956. ti = getutime() - ti;
  3957. if (do_benchmark) {
  3958. av_log(NULL, AV_LOG_INFO, "bench: utime=%0.3fs\n", ti / 1000000.0);
  3959. }
  3960. av_log(NULL, AV_LOG_DEBUG, "%"PRIu64" frames successfully decoded, %"PRIu64" decoding errors\n",
  3961. decode_error_stat[0], decode_error_stat[1]);
  3962. if ((decode_error_stat[0] + decode_error_stat[1]) * max_error_rate < decode_error_stat[1])
  3963. exit_program(69);
  3964. exit_program(received_nb_signals ? 255 : main_return_code);
  3965. return main_return_code;
  3966. }