ffmpeg.c 190 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159
  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 <signal.h>
  31. #include <limits.h>
  32. #include <unistd.h>
  33. #include "libavformat/avformat.h"
  34. #include "libavdevice/avdevice.h"
  35. #include "libswscale/swscale.h"
  36. #include "libavutil/opt.h"
  37. #include "libavcodec/audioconvert.h"
  38. #include "libavutil/audioconvert.h"
  39. #include "libavutil/parseutils.h"
  40. #include "libavutil/samplefmt.h"
  41. #include "libavutil/colorspace.h"
  42. #include "libavutil/fifo.h"
  43. #include "libavutil/intreadwrite.h"
  44. #include "libavutil/dict.h"
  45. #include "libavutil/mathematics.h"
  46. #include "libavutil/pixdesc.h"
  47. #include "libavutil/avstring.h"
  48. #include "libavutil/libm.h"
  49. #include "libavutil/imgutils.h"
  50. #include "libavformat/os_support.h"
  51. #include "libswresample/swresample.h"
  52. #include "libavformat/ffm.h" // not public API
  53. #if CONFIG_AVFILTER
  54. # include "libavfilter/avcodec.h"
  55. # include "libavfilter/avfilter.h"
  56. # include "libavfilter/avfiltergraph.h"
  57. # include "libavfilter/buffersink.h"
  58. # include "libavfilter/buffersrc.h"
  59. # include "libavfilter/vsrc_buffer.h"
  60. #endif
  61. #if HAVE_SYS_RESOURCE_H
  62. #include <sys/types.h>
  63. #include <sys/time.h>
  64. #include <sys/resource.h>
  65. #elif HAVE_GETPROCESSTIMES
  66. #include <windows.h>
  67. #endif
  68. #if HAVE_GETPROCESSMEMORYINFO
  69. #include <windows.h>
  70. #include <psapi.h>
  71. #endif
  72. #if HAVE_SYS_SELECT_H
  73. #include <sys/select.h>
  74. #endif
  75. #if HAVE_TERMIOS_H
  76. #include <fcntl.h>
  77. #include <sys/ioctl.h>
  78. #include <sys/time.h>
  79. #include <termios.h>
  80. #elif HAVE_KBHIT
  81. #include <conio.h>
  82. #endif
  83. #include <time.h>
  84. #include "cmdutils.h"
  85. #include "libavutil/avassert.h"
  86. #define VSYNC_AUTO -1
  87. #define VSYNC_PASSTHROUGH 0
  88. #define VSYNC_CFR 1
  89. #define VSYNC_VFR 2
  90. const char program_name[] = "ffmpeg";
  91. const int program_birth_year = 2000;
  92. /* select an input stream for an output stream */
  93. typedef struct StreamMap {
  94. int disabled; /** 1 is this mapping is disabled by a negative map */
  95. int file_index;
  96. int stream_index;
  97. int sync_file_index;
  98. int sync_stream_index;
  99. } StreamMap;
  100. typedef struct {
  101. int file_idx, stream_idx, channel_idx; // input
  102. int ofile_idx, ostream_idx; // output
  103. } AudioChannelMap;
  104. /**
  105. * select an input file for an output file
  106. */
  107. typedef struct MetadataMap {
  108. int file; ///< file index
  109. char type; ///< type of metadata to copy -- (g)lobal, (s)tream, (c)hapter or (p)rogram
  110. int index; ///< stream/chapter/program number
  111. } MetadataMap;
  112. static const OptionDef options[];
  113. #define MAX_STREAMS 1024 /* arbitrary sanity check value */
  114. static int frame_bits_per_raw_sample = 0;
  115. static int video_discard = 0;
  116. static int same_quant = 0;
  117. static int do_deinterlace = 0;
  118. static int intra_dc_precision = 8;
  119. static int loop_input = 0;
  120. static int loop_output = AVFMT_NOOUTPUTLOOP;
  121. static int qp_hist = 0;
  122. static int intra_only = 0;
  123. static const char *video_codec_name = NULL;
  124. static const char *audio_codec_name = NULL;
  125. static const char *subtitle_codec_name = NULL;
  126. static int file_overwrite = 0;
  127. static int no_file_overwrite = 0;
  128. static int do_benchmark = 0;
  129. static int do_hex_dump = 0;
  130. static int do_pkt_dump = 0;
  131. static int do_psnr = 0;
  132. static int do_pass = 0;
  133. static const char *pass_logfilename_prefix;
  134. static int video_sync_method = VSYNC_AUTO;
  135. static int audio_sync_method = 0;
  136. static float audio_drift_threshold = 0.1;
  137. static int copy_ts = 0;
  138. static int copy_tb = -1;
  139. static int opt_shortest = 0;
  140. static char *vstats_filename;
  141. static FILE *vstats_file;
  142. static int audio_volume = 256;
  143. static int exit_on_error = 0;
  144. static int using_stdin = 0;
  145. static int run_as_daemon = 0;
  146. static volatile int received_nb_signals = 0;
  147. static int64_t video_size = 0;
  148. static int64_t audio_size = 0;
  149. static int64_t extra_size = 0;
  150. static int nb_frames_dup = 0;
  151. static int nb_frames_drop = 0;
  152. static int input_sync;
  153. static float dts_delta_threshold = 10;
  154. static int print_stats = 1;
  155. static uint8_t *audio_buf;
  156. static unsigned int allocated_audio_buf_size;
  157. static uint8_t *input_tmp= NULL;
  158. #define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
  159. typedef struct FrameBuffer {
  160. uint8_t *base[4];
  161. uint8_t *data[4];
  162. int linesize[4];
  163. int h, w;
  164. enum PixelFormat pix_fmt;
  165. int refcount;
  166. struct InputStream *ist;
  167. struct FrameBuffer *next;
  168. } FrameBuffer;
  169. typedef struct InputStream {
  170. int file_index;
  171. AVStream *st;
  172. int discard; /* true if stream data should be discarded */
  173. int decoding_needed; /* true if the packets must be decoded in 'raw_fifo' */
  174. AVCodec *dec;
  175. AVFrame *decoded_frame;
  176. AVFrame *filtered_frame;
  177. int64_t start; /* time when read started */
  178. int64_t next_pts; /* synthetic pts for cases where pkt.pts
  179. is not defined */
  180. int64_t pts; /* current pts */
  181. double ts_scale;
  182. int is_start; /* is 1 at the start and after a discontinuity */
  183. int showed_multi_packet_warning;
  184. AVDictionary *opts;
  185. /* a pool of free buffers for decoded data */
  186. FrameBuffer *buffer_pool;
  187. int dr1;
  188. } InputStream;
  189. typedef struct InputFile {
  190. AVFormatContext *ctx;
  191. int eof_reached; /* true if eof reached */
  192. int ist_index; /* index of first stream in input_streams */
  193. int buffer_size; /* current total buffer size */
  194. int64_t ts_offset;
  195. int nb_streams; /* number of stream that ffmpeg is aware of; may be different
  196. from ctx.nb_streams if new streams appear during av_read_frame() */
  197. int rate_emu;
  198. } InputFile;
  199. typedef struct OutputStream {
  200. int file_index; /* file index */
  201. int index; /* stream index in the output file */
  202. int source_index; /* InputStream index */
  203. AVStream *st; /* stream in the output file */
  204. int encoding_needed; /* true if encoding needed for this stream */
  205. int frame_number;
  206. /* input pts and corresponding output pts
  207. for A/V sync */
  208. struct InputStream *sync_ist; /* input stream to sync against */
  209. int64_t sync_opts; /* output frame counter, could be changed to some true timestamp */ // FIXME look at frame_number
  210. AVBitStreamFilterContext *bitstream_filters;
  211. AVCodec *enc;
  212. int64_t max_frames;
  213. AVFrame *output_frame;
  214. /* video only */
  215. int video_resample;
  216. AVFrame resample_frame; /* temporary frame for image resampling */
  217. struct SwsContext *img_resample_ctx; /* for image resampling */
  218. int resample_height;
  219. int resample_width;
  220. int resample_pix_fmt;
  221. AVRational frame_rate;
  222. int force_fps;
  223. int top_field_first;
  224. float frame_aspect_ratio;
  225. /* forced key frames */
  226. int64_t *forced_kf_pts;
  227. int forced_kf_count;
  228. int forced_kf_index;
  229. /* audio only */
  230. int audio_resample;
  231. int audio_channels_map[SWR_CH_MAX]; ///< list of the channels id to pick from the source stream
  232. int audio_channels_mapped; ///< number of channels in audio_channels_map
  233. int resample_sample_fmt;
  234. int resample_channels;
  235. int resample_sample_rate;
  236. float rematrix_volume;
  237. AVFifoBuffer *fifo; /* for compression: one audio fifo per codec */
  238. FILE *logfile;
  239. struct SwrContext *swr;
  240. #if CONFIG_AVFILTER
  241. AVFilterContext *output_video_filter;
  242. AVFilterContext *input_video_filter;
  243. AVFilterBufferRef *picref;
  244. char *avfilter;
  245. AVFilterGraph *graph;
  246. #endif
  247. int64_t sws_flags;
  248. AVDictionary *opts;
  249. int is_past_recording_time;
  250. int stream_copy;
  251. const char *attachment_filename;
  252. int copy_initial_nonkeyframes;
  253. } OutputStream;
  254. #if HAVE_TERMIOS_H
  255. /* init terminal so that we can grab keys */
  256. static struct termios oldtty;
  257. static int restore_tty;
  258. #endif
  259. typedef struct OutputFile {
  260. AVFormatContext *ctx;
  261. AVDictionary *opts;
  262. int ost_index; /* index of the first stream in output_streams */
  263. int64_t recording_time; /* desired length of the resulting file in microseconds */
  264. int64_t start_time; /* start time in microseconds */
  265. uint64_t limit_filesize;
  266. } OutputFile;
  267. static InputStream *input_streams = NULL;
  268. static int nb_input_streams = 0;
  269. static InputFile *input_files = NULL;
  270. static int nb_input_files = 0;
  271. static OutputStream *output_streams = NULL;
  272. static int nb_output_streams = 0;
  273. static OutputFile *output_files = NULL;
  274. static int nb_output_files = 0;
  275. typedef struct OptionsContext {
  276. /* input/output options */
  277. int64_t start_time;
  278. const char *format;
  279. SpecifierOpt *codec_names;
  280. int nb_codec_names;
  281. SpecifierOpt *audio_channels;
  282. int nb_audio_channels;
  283. SpecifierOpt *audio_sample_rate;
  284. int nb_audio_sample_rate;
  285. SpecifierOpt *rematrix_volume;
  286. int nb_rematrix_volume;
  287. SpecifierOpt *frame_rates;
  288. int nb_frame_rates;
  289. SpecifierOpt *frame_sizes;
  290. int nb_frame_sizes;
  291. SpecifierOpt *frame_pix_fmts;
  292. int nb_frame_pix_fmts;
  293. /* input options */
  294. int64_t input_ts_offset;
  295. int rate_emu;
  296. SpecifierOpt *ts_scale;
  297. int nb_ts_scale;
  298. SpecifierOpt *dump_attachment;
  299. int nb_dump_attachment;
  300. /* output options */
  301. StreamMap *stream_maps;
  302. int nb_stream_maps;
  303. AudioChannelMap *audio_channel_maps; ///< one info entry per -map_channel
  304. int nb_audio_channel_maps; ///< number of (valid) -map_channel settings
  305. /* first item specifies output metadata, second is input */
  306. MetadataMap (*meta_data_maps)[2];
  307. int nb_meta_data_maps;
  308. int metadata_global_manual;
  309. int metadata_streams_manual;
  310. int metadata_chapters_manual;
  311. const char **attachments;
  312. int nb_attachments;
  313. int chapters_input_file;
  314. int64_t recording_time;
  315. uint64_t limit_filesize;
  316. float mux_preload;
  317. float mux_max_delay;
  318. int video_disable;
  319. int audio_disable;
  320. int subtitle_disable;
  321. int data_disable;
  322. /* indexed by output file stream index */
  323. int *streamid_map;
  324. int nb_streamid_map;
  325. SpecifierOpt *metadata;
  326. int nb_metadata;
  327. SpecifierOpt *max_frames;
  328. int nb_max_frames;
  329. SpecifierOpt *bitstream_filters;
  330. int nb_bitstream_filters;
  331. SpecifierOpt *codec_tags;
  332. int nb_codec_tags;
  333. SpecifierOpt *sample_fmts;
  334. int nb_sample_fmts;
  335. SpecifierOpt *qscale;
  336. int nb_qscale;
  337. SpecifierOpt *forced_key_frames;
  338. int nb_forced_key_frames;
  339. SpecifierOpt *force_fps;
  340. int nb_force_fps;
  341. SpecifierOpt *frame_aspect_ratios;
  342. int nb_frame_aspect_ratios;
  343. SpecifierOpt *rc_overrides;
  344. int nb_rc_overrides;
  345. SpecifierOpt *intra_matrices;
  346. int nb_intra_matrices;
  347. SpecifierOpt *inter_matrices;
  348. int nb_inter_matrices;
  349. SpecifierOpt *top_field_first;
  350. int nb_top_field_first;
  351. SpecifierOpt *metadata_map;
  352. int nb_metadata_map;
  353. SpecifierOpt *presets;
  354. int nb_presets;
  355. SpecifierOpt *copy_initial_nonkeyframes;
  356. int nb_copy_initial_nonkeyframes;
  357. #if CONFIG_AVFILTER
  358. SpecifierOpt *filters;
  359. int nb_filters;
  360. #endif
  361. } OptionsContext;
  362. #define MATCH_PER_STREAM_OPT(name, type, outvar, fmtctx, st)\
  363. {\
  364. int i, ret;\
  365. for (i = 0; i < o->nb_ ## name; i++) {\
  366. char *spec = o->name[i].specifier;\
  367. if ((ret = check_stream_specifier(fmtctx, st, spec)) > 0)\
  368. outvar = o->name[i].u.type;\
  369. else if (ret < 0)\
  370. exit_program(1);\
  371. }\
  372. }
  373. static void reset_options(OptionsContext *o, int is_input)
  374. {
  375. const OptionDef *po = options;
  376. OptionsContext bak= *o;
  377. /* all OPT_SPEC and OPT_STRING can be freed in generic way */
  378. while (po->name) {
  379. void *dst = (uint8_t*)o + po->u.off;
  380. if (po->flags & OPT_SPEC) {
  381. SpecifierOpt **so = dst;
  382. int i, *count = (int*)(so + 1);
  383. for (i = 0; i < *count; i++) {
  384. av_freep(&(*so)[i].specifier);
  385. if (po->flags & OPT_STRING)
  386. av_freep(&(*so)[i].u.str);
  387. }
  388. av_freep(so);
  389. *count = 0;
  390. } else if (po->flags & OPT_OFFSET && po->flags & OPT_STRING)
  391. av_freep(dst);
  392. po++;
  393. }
  394. av_freep(&o->stream_maps);
  395. av_freep(&o->audio_channel_maps);
  396. av_freep(&o->meta_data_maps);
  397. av_freep(&o->streamid_map);
  398. memset(o, 0, sizeof(*o));
  399. if(is_input) o->recording_time = bak.recording_time;
  400. else o->recording_time = INT64_MAX;
  401. o->mux_max_delay = 0.7;
  402. o->limit_filesize = UINT64_MAX;
  403. o->chapters_input_file = INT_MAX;
  404. uninit_opts();
  405. init_opts();
  406. }
  407. static int alloc_buffer(AVCodecContext *s, InputStream *ist, FrameBuffer **pbuf)
  408. {
  409. FrameBuffer *buf = av_mallocz(sizeof(*buf));
  410. int ret, i;
  411. const int pixel_size = av_pix_fmt_descriptors[s->pix_fmt].comp[0].step_minus1+1;
  412. int h_chroma_shift, v_chroma_shift;
  413. int edge = 32; // XXX should be avcodec_get_edge_width(), but that fails on svq1
  414. int w = s->width, h = s->height;
  415. if (!buf)
  416. return AVERROR(ENOMEM);
  417. if (!(s->flags & CODEC_FLAG_EMU_EDGE)) {
  418. w += 2*edge;
  419. h += 2*edge;
  420. }
  421. avcodec_align_dimensions(s, &w, &h);
  422. if ((ret = av_image_alloc(buf->base, buf->linesize, w, h,
  423. s->pix_fmt, 32)) < 0) {
  424. av_freep(&buf);
  425. return ret;
  426. }
  427. /* XXX this shouldn't be needed, but some tests break without this line
  428. * those decoders are buggy and need to be fixed.
  429. * the following tests fail:
  430. * bethsoft-vid, cdgraphics, ansi, aasc, fraps-v1, qtrle-1bit
  431. */
  432. memset(buf->base[0], 128, ret);
  433. avcodec_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift);
  434. for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
  435. const int h_shift = i==0 ? 0 : h_chroma_shift;
  436. const int v_shift = i==0 ? 0 : v_chroma_shift;
  437. if (s->flags & CODEC_FLAG_EMU_EDGE)
  438. buf->data[i] = buf->base[i];
  439. else if (buf->base[i])
  440. buf->data[i] = buf->base[i] +
  441. FFALIGN((buf->linesize[i]*edge >> v_shift) +
  442. (pixel_size*edge >> h_shift), 32);
  443. }
  444. buf->w = s->width;
  445. buf->h = s->height;
  446. buf->pix_fmt = s->pix_fmt;
  447. buf->ist = ist;
  448. *pbuf = buf;
  449. return 0;
  450. }
  451. static void free_buffer_pool(InputStream *ist)
  452. {
  453. FrameBuffer *buf = ist->buffer_pool;
  454. while (buf) {
  455. ist->buffer_pool = buf->next;
  456. av_freep(&buf->base[0]);
  457. av_free(buf);
  458. buf = ist->buffer_pool;
  459. }
  460. }
  461. static void unref_buffer(InputStream *ist, FrameBuffer *buf)
  462. {
  463. av_assert0(buf->refcount);
  464. buf->refcount--;
  465. if (!buf->refcount) {
  466. buf->next = ist->buffer_pool;
  467. ist->buffer_pool = buf;
  468. }
  469. }
  470. static int codec_get_buffer(AVCodecContext *s, AVFrame *frame)
  471. {
  472. InputStream *ist = s->opaque;
  473. FrameBuffer *buf;
  474. int ret, i;
  475. if(av_image_check_size(s->width, s->height, 0, s))
  476. return -1;
  477. if (!ist->buffer_pool && (ret = alloc_buffer(s, ist, &ist->buffer_pool)) < 0)
  478. return ret;
  479. buf = ist->buffer_pool;
  480. ist->buffer_pool = buf->next;
  481. buf->next = NULL;
  482. if (buf->w != s->width || buf->h != s->height || buf->pix_fmt != s->pix_fmt) {
  483. av_freep(&buf->base[0]);
  484. av_free(buf);
  485. ist->dr1 = 0;
  486. if ((ret = alloc_buffer(s, ist, &buf)) < 0)
  487. return ret;
  488. }
  489. buf->refcount++;
  490. frame->opaque = buf;
  491. frame->type = FF_BUFFER_TYPE_USER;
  492. frame->extended_data = frame->data;
  493. frame->pkt_pts = s->pkt ? s->pkt->pts : AV_NOPTS_VALUE;
  494. for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
  495. frame->base[i] = buf->base[i]; // XXX h264.c uses base though it shouldn't
  496. frame->data[i] = buf->data[i];
  497. frame->linesize[i] = buf->linesize[i];
  498. }
  499. return 0;
  500. }
  501. static void codec_release_buffer(AVCodecContext *s, AVFrame *frame)
  502. {
  503. InputStream *ist = s->opaque;
  504. FrameBuffer *buf = frame->opaque;
  505. int i;
  506. if(frame->type!=FF_BUFFER_TYPE_USER)
  507. return avcodec_default_release_buffer(s, frame);
  508. for (i = 0; i < FF_ARRAY_ELEMS(frame->data); i++)
  509. frame->data[i] = NULL;
  510. unref_buffer(ist, buf);
  511. }
  512. static void filter_release_buffer(AVFilterBuffer *fb)
  513. {
  514. FrameBuffer *buf = fb->priv;
  515. av_free(fb);
  516. unref_buffer(buf->ist, buf);
  517. }
  518. #if CONFIG_AVFILTER
  519. static int configure_video_filters(InputStream *ist, OutputStream *ost)
  520. {
  521. AVFilterContext *last_filter, *filter;
  522. /** filter graph containing all filters including input & output */
  523. AVCodecContext *codec = ost->st->codec;
  524. AVCodecContext *icodec = ist->st->codec;
  525. enum PixelFormat pix_fmts[] = { codec->pix_fmt, PIX_FMT_NONE };
  526. AVBufferSinkParams *buffersink_params = av_buffersink_params_alloc();
  527. AVRational sample_aspect_ratio;
  528. char args[255];
  529. int ret;
  530. ost->graph = avfilter_graph_alloc();
  531. if (ist->st->sample_aspect_ratio.num) {
  532. sample_aspect_ratio = ist->st->sample_aspect_ratio;
  533. } else
  534. sample_aspect_ratio = ist->st->codec->sample_aspect_ratio;
  535. snprintf(args, 255, "%d:%d:%d:%d:%d:%d:%d", ist->st->codec->width,
  536. ist->st->codec->height, ist->st->codec->pix_fmt, 1, AV_TIME_BASE,
  537. sample_aspect_ratio.num, sample_aspect_ratio.den);
  538. ret = avfilter_graph_create_filter(&ost->input_video_filter, avfilter_get_by_name("buffer"),
  539. "src", args, NULL, ost->graph);
  540. if (ret < 0)
  541. return ret;
  542. #if FF_API_OLD_VSINK_API
  543. ret = avfilter_graph_create_filter(&ost->output_video_filter, avfilter_get_by_name("buffersink"),
  544. "out", NULL, pix_fmts, ost->graph);
  545. #else
  546. buffersink_params->pixel_fmts = pix_fmts;
  547. ret = avfilter_graph_create_filter(&ost->output_video_filter, avfilter_get_by_name("buffersink"),
  548. "out", NULL, buffersink_params, ost->graph);
  549. #endif
  550. av_freep(&buffersink_params);
  551. if (ret < 0)
  552. return ret;
  553. last_filter = ost->input_video_filter;
  554. if (codec->width != icodec->width || codec->height != icodec->height) {
  555. snprintf(args, 255, "%d:%d:flags=0x%X",
  556. codec->width,
  557. codec->height,
  558. (unsigned)ost->sws_flags);
  559. if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
  560. NULL, args, NULL, ost->graph)) < 0)
  561. return ret;
  562. if ((ret = avfilter_link(last_filter, 0, filter, 0)) < 0)
  563. return ret;
  564. last_filter = filter;
  565. }
  566. snprintf(args, sizeof(args), "flags=0x%X", (unsigned)ost->sws_flags);
  567. ost->graph->scale_sws_opts = av_strdup(args);
  568. if (ost->avfilter) {
  569. AVFilterInOut *outputs = avfilter_inout_alloc();
  570. AVFilterInOut *inputs = avfilter_inout_alloc();
  571. outputs->name = av_strdup("in");
  572. outputs->filter_ctx = last_filter;
  573. outputs->pad_idx = 0;
  574. outputs->next = NULL;
  575. inputs->name = av_strdup("out");
  576. inputs->filter_ctx = ost->output_video_filter;
  577. inputs->pad_idx = 0;
  578. inputs->next = NULL;
  579. if ((ret = avfilter_graph_parse(ost->graph, ost->avfilter, &inputs, &outputs, NULL)) < 0)
  580. return ret;
  581. av_freep(&ost->avfilter);
  582. } else {
  583. if ((ret = avfilter_link(last_filter, 0, ost->output_video_filter, 0)) < 0)
  584. return ret;
  585. }
  586. if ((ret = avfilter_graph_config(ost->graph, NULL)) < 0)
  587. return ret;
  588. codec->width = ost->output_video_filter->inputs[0]->w;
  589. codec->height = ost->output_video_filter->inputs[0]->h;
  590. codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
  591. ost->frame_aspect_ratio ? // overridden by the -aspect cli option
  592. av_d2q(ost->frame_aspect_ratio * codec->height/codec->width, 255) :
  593. ost->output_video_filter->inputs[0]->sample_aspect_ratio;
  594. return 0;
  595. }
  596. #endif /* CONFIG_AVFILTER */
  597. static void term_exit(void)
  598. {
  599. av_log(NULL, AV_LOG_QUIET, "%s", "");
  600. #if HAVE_TERMIOS_H
  601. if(restore_tty)
  602. tcsetattr (0, TCSANOW, &oldtty);
  603. #endif
  604. }
  605. static volatile int received_sigterm = 0;
  606. static void sigterm_handler(int sig)
  607. {
  608. received_sigterm = sig;
  609. received_nb_signals++;
  610. term_exit();
  611. if(received_nb_signals > 3)
  612. exit(123);
  613. }
  614. static void term_init(void)
  615. {
  616. #if HAVE_TERMIOS_H
  617. if(!run_as_daemon){
  618. struct termios tty;
  619. if (tcgetattr (0, &tty) == 0) {
  620. oldtty = tty;
  621. restore_tty = 1;
  622. atexit(term_exit);
  623. tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
  624. |INLCR|IGNCR|ICRNL|IXON);
  625. tty.c_oflag |= OPOST;
  626. tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
  627. tty.c_cflag &= ~(CSIZE|PARENB);
  628. tty.c_cflag |= CS8;
  629. tty.c_cc[VMIN] = 1;
  630. tty.c_cc[VTIME] = 0;
  631. tcsetattr (0, TCSANOW, &tty);
  632. }
  633. signal(SIGQUIT, sigterm_handler); /* Quit (POSIX). */
  634. }
  635. #endif
  636. avformat_network_deinit();
  637. signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
  638. signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
  639. #ifdef SIGXCPU
  640. signal(SIGXCPU, sigterm_handler);
  641. #endif
  642. }
  643. /* read a key without blocking */
  644. static int read_key(void)
  645. {
  646. unsigned char ch;
  647. #if HAVE_TERMIOS_H
  648. int n = 1;
  649. struct timeval tv;
  650. fd_set rfds;
  651. FD_ZERO(&rfds);
  652. FD_SET(0, &rfds);
  653. tv.tv_sec = 0;
  654. tv.tv_usec = 0;
  655. n = select(1, &rfds, NULL, NULL, &tv);
  656. if (n > 0) {
  657. n = read(0, &ch, 1);
  658. if (n == 1)
  659. return ch;
  660. return n;
  661. }
  662. #elif HAVE_KBHIT
  663. # if HAVE_PEEKNAMEDPIPE
  664. static int is_pipe;
  665. static HANDLE input_handle;
  666. DWORD dw, nchars;
  667. if(!input_handle){
  668. input_handle = GetStdHandle(STD_INPUT_HANDLE);
  669. is_pipe = !GetConsoleMode(input_handle, &dw);
  670. }
  671. if (stdin->_cnt > 0) {
  672. read(0, &ch, 1);
  673. return ch;
  674. }
  675. if (is_pipe) {
  676. /* When running under a GUI, you will end here. */
  677. if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL))
  678. return -1;
  679. //Read it
  680. if(nchars != 0) {
  681. read(0, &ch, 1);
  682. return ch;
  683. }else{
  684. return -1;
  685. }
  686. }
  687. # endif
  688. if(kbhit())
  689. return(getch());
  690. #endif
  691. return -1;
  692. }
  693. static int decode_interrupt_cb(void *ctx)
  694. {
  695. return received_nb_signals > 1;
  696. }
  697. static const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
  698. void av_noreturn exit_program(int ret)
  699. {
  700. int i;
  701. /* close files */
  702. for (i = 0; i < nb_output_files; i++) {
  703. AVFormatContext *s = output_files[i].ctx;
  704. if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
  705. avio_close(s->pb);
  706. avformat_free_context(s);
  707. av_dict_free(&output_files[i].opts);
  708. }
  709. for (i = 0; i < nb_output_streams; i++) {
  710. AVBitStreamFilterContext *bsfc = output_streams[i].bitstream_filters;
  711. while (bsfc) {
  712. AVBitStreamFilterContext *next = bsfc->next;
  713. av_bitstream_filter_close(bsfc);
  714. bsfc = next;
  715. }
  716. output_streams[i].bitstream_filters = NULL;
  717. if (output_streams[i].output_frame) {
  718. AVFrame *frame = output_streams[i].output_frame;
  719. if (frame->extended_data != frame->data)
  720. av_freep(&frame->extended_data);
  721. av_freep(&frame);
  722. }
  723. }
  724. for (i = 0; i < nb_input_files; i++) {
  725. avformat_close_input(&input_files[i].ctx);
  726. }
  727. for (i = 0; i < nb_input_streams; i++) {
  728. av_freep(&input_streams[i].decoded_frame);
  729. av_freep(&input_streams[i].filtered_frame);
  730. av_dict_free(&input_streams[i].opts);
  731. free_buffer_pool(&input_streams[i]);
  732. }
  733. if (vstats_file)
  734. fclose(vstats_file);
  735. av_free(vstats_filename);
  736. av_freep(&input_streams);
  737. av_freep(&input_files);
  738. av_freep(&output_streams);
  739. av_freep(&output_files);
  740. uninit_opts();
  741. av_free(audio_buf);
  742. allocated_audio_buf_size = 0;
  743. #if CONFIG_AVFILTER
  744. avfilter_uninit();
  745. #endif
  746. avformat_network_deinit();
  747. av_freep(&input_tmp);
  748. if (received_sigterm) {
  749. av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
  750. (int) received_sigterm);
  751. exit (255);
  752. }
  753. exit(ret); /* not all OS-es handle main() return value */
  754. }
  755. static void assert_avoptions(AVDictionary *m)
  756. {
  757. AVDictionaryEntry *t;
  758. if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
  759. av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
  760. exit_program(1);
  761. }
  762. }
  763. static void assert_codec_experimental(AVCodecContext *c, int encoder)
  764. {
  765. const char *codec_string = encoder ? "encoder" : "decoder";
  766. AVCodec *codec;
  767. if (c->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
  768. c->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
  769. av_log(NULL, AV_LOG_FATAL, "%s '%s' is experimental and might produce bad "
  770. "results.\nAdd '-strict experimental' if you want to use it.\n",
  771. codec_string, c->codec->name);
  772. codec = encoder ? avcodec_find_encoder(c->codec->id) : avcodec_find_decoder(c->codec->id);
  773. if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))
  774. av_log(NULL, AV_LOG_FATAL, "Or use the non experimental %s '%s'.\n",
  775. codec_string, codec->name);
  776. exit_program(1);
  777. }
  778. }
  779. static void choose_sample_fmt(AVStream *st, AVCodec *codec)
  780. {
  781. if (codec && codec->sample_fmts) {
  782. const enum AVSampleFormat *p = codec->sample_fmts;
  783. for (; *p != -1; p++) {
  784. if (*p == st->codec->sample_fmt)
  785. break;
  786. }
  787. if (*p == -1) {
  788. if((codec->capabilities & CODEC_CAP_LOSSLESS) && av_get_sample_fmt_name(st->codec->sample_fmt) > av_get_sample_fmt_name(codec->sample_fmts[0]))
  789. av_log(NULL, AV_LOG_ERROR, "Conversion will not be lossless.\n");
  790. if(av_get_sample_fmt_name(st->codec->sample_fmt))
  791. av_log(NULL, AV_LOG_WARNING,
  792. "Incompatible sample format '%s' for codec '%s', auto-selecting format '%s'\n",
  793. av_get_sample_fmt_name(st->codec->sample_fmt),
  794. codec->name,
  795. av_get_sample_fmt_name(codec->sample_fmts[0]));
  796. st->codec->sample_fmt = codec->sample_fmts[0];
  797. }
  798. }
  799. }
  800. static void choose_sample_rate(AVStream *st, AVCodec *codec)
  801. {
  802. if (codec && codec->supported_samplerates) {
  803. const int *p = codec->supported_samplerates;
  804. int best = 0;
  805. int best_dist = INT_MAX;
  806. for (; *p; p++) {
  807. int dist = abs(st->codec->sample_rate - *p);
  808. if (dist < best_dist) {
  809. best_dist = dist;
  810. best = *p;
  811. }
  812. }
  813. if (best_dist) {
  814. av_log(st->codec, AV_LOG_WARNING, "Requested sampling rate unsupported using closest supported (%d)\n", best);
  815. }
  816. st->codec->sample_rate = best;
  817. }
  818. }
  819. static void choose_pixel_fmt(AVStream *st, AVCodec *codec)
  820. {
  821. if (codec && codec->pix_fmts) {
  822. const enum PixelFormat *p = codec->pix_fmts;
  823. int has_alpha= av_pix_fmt_descriptors[st->codec->pix_fmt].nb_components % 2 == 0;
  824. enum PixelFormat best= PIX_FMT_NONE;
  825. if (st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
  826. if (st->codec->codec_id == CODEC_ID_MJPEG) {
  827. p = (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_NONE };
  828. } else if (st->codec->codec_id == CODEC_ID_LJPEG) {
  829. p = (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUVJ444P, PIX_FMT_YUV420P,
  830. PIX_FMT_YUV422P, PIX_FMT_YUV444P, PIX_FMT_BGRA, PIX_FMT_NONE };
  831. }
  832. }
  833. for (; *p != PIX_FMT_NONE; p++) {
  834. best= avcodec_find_best_pix_fmt2(best, *p, st->codec->pix_fmt, has_alpha, NULL);
  835. if (*p == st->codec->pix_fmt)
  836. break;
  837. }
  838. if (*p == PIX_FMT_NONE) {
  839. if (st->codec->pix_fmt != PIX_FMT_NONE)
  840. av_log(NULL, AV_LOG_WARNING,
  841. "Incompatible pixel format '%s' for codec '%s', auto-selecting format '%s'\n",
  842. av_pix_fmt_descriptors[st->codec->pix_fmt].name,
  843. codec->name,
  844. av_pix_fmt_descriptors[best].name);
  845. st->codec->pix_fmt = best;
  846. }
  847. }
  848. }
  849. static double get_sync_ipts(const OutputStream *ost)
  850. {
  851. const InputStream *ist = ost->sync_ist;
  852. OutputFile *of = &output_files[ost->file_index];
  853. return (double)(ist->pts - of->start_time) / AV_TIME_BASE;
  854. }
  855. static void write_frame(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)
  856. {
  857. AVBitStreamFilterContext *bsfc = ost->bitstream_filters;
  858. AVCodecContext *avctx = ost->st->codec;
  859. int ret;
  860. /*
  861. * Audio encoders may split the packets -- #frames in != #packets out.
  862. * But there is no reordering, so we can limit the number of output packets
  863. * by simply dropping them here.
  864. * Counting encoded video frames needs to be done separately because of
  865. * reordering, see do_video_out()
  866. */
  867. if (!(avctx->codec_type == AVMEDIA_TYPE_VIDEO && avctx->codec)) {
  868. if (ost->frame_number >= ost->max_frames)
  869. return;
  870. ost->frame_number++;
  871. }
  872. while (bsfc) {
  873. AVPacket new_pkt = *pkt;
  874. int a = av_bitstream_filter_filter(bsfc, avctx, NULL,
  875. &new_pkt.data, &new_pkt.size,
  876. pkt->data, pkt->size,
  877. pkt->flags & AV_PKT_FLAG_KEY);
  878. if (a > 0) {
  879. av_free_packet(pkt);
  880. new_pkt.destruct = av_destruct_packet;
  881. } else if (a < 0) {
  882. av_log(NULL, AV_LOG_ERROR, "Failed to open bitstream filter %s for stream %d with codec %s",
  883. bsfc->filter->name, pkt->stream_index,
  884. avctx->codec ? avctx->codec->name : "copy");
  885. print_error("", a);
  886. if (exit_on_error)
  887. exit_program(1);
  888. }
  889. *pkt = new_pkt;
  890. bsfc = bsfc->next;
  891. }
  892. ret = av_interleaved_write_frame(s, pkt);
  893. if (ret < 0) {
  894. print_error("av_interleaved_write_frame()", ret);
  895. exit_program(1);
  896. }
  897. }
  898. static void generate_silence(uint8_t* buf, enum AVSampleFormat sample_fmt, size_t size)
  899. {
  900. int fill_char = 0x00;
  901. if (sample_fmt == AV_SAMPLE_FMT_U8)
  902. fill_char = 0x80;
  903. memset(buf, fill_char, size);
  904. }
  905. static int encode_audio_frame(AVFormatContext *s, OutputStream *ost,
  906. const uint8_t *buf, int buf_size)
  907. {
  908. AVCodecContext *enc = ost->st->codec;
  909. AVFrame *frame = NULL;
  910. AVPacket pkt;
  911. int ret, got_packet;
  912. av_init_packet(&pkt);
  913. pkt.data = NULL;
  914. pkt.size = 0;
  915. if (buf) {
  916. if (!ost->output_frame) {
  917. ost->output_frame = avcodec_alloc_frame();
  918. if (!ost->output_frame) {
  919. av_log(NULL, AV_LOG_FATAL, "out-of-memory in encode_audio_frame()\n");
  920. exit_program(1);
  921. }
  922. }
  923. frame = ost->output_frame;
  924. if (frame->extended_data != frame->data)
  925. av_freep(&frame->extended_data);
  926. avcodec_get_frame_defaults(frame);
  927. frame->nb_samples = buf_size /
  928. (enc->channels * av_get_bytes_per_sample(enc->sample_fmt));
  929. if ((ret = avcodec_fill_audio_frame(frame, enc->channels, enc->sample_fmt,
  930. buf, buf_size, 1)) < 0) {
  931. av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
  932. exit_program(1);
  933. }
  934. }
  935. got_packet = 0;
  936. if (avcodec_encode_audio2(enc, &pkt, frame, &got_packet) < 0) {
  937. av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
  938. exit_program(1);
  939. }
  940. ret = pkt.size;
  941. if (got_packet) {
  942. pkt.stream_index = ost->index;
  943. if (pkt.pts != AV_NOPTS_VALUE)
  944. pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
  945. if (pkt.duration > 0)
  946. pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
  947. write_frame(s, &pkt, ost);
  948. audio_size += pkt.size;
  949. av_free_packet(&pkt);
  950. }
  951. if (frame)
  952. ost->sync_opts += frame->nb_samples;
  953. return ret;
  954. }
  955. static void do_audio_out(AVFormatContext *s, OutputStream *ost,
  956. InputStream *ist, AVFrame *decoded_frame)
  957. {
  958. uint8_t *buftmp;
  959. int64_t audio_buf_size, size_out;
  960. int frame_bytes, resample_changed;
  961. AVCodecContext *enc = ost->st->codec;
  962. AVCodecContext *dec = ist->st->codec;
  963. int osize = av_get_bytes_per_sample(enc->sample_fmt);
  964. int isize = av_get_bytes_per_sample(dec->sample_fmt);
  965. uint8_t *buf = decoded_frame->data[0];
  966. int size = decoded_frame->nb_samples * dec->channels * isize;
  967. int64_t allocated_for_size = size;
  968. need_realloc:
  969. audio_buf_size = (allocated_for_size + isize * dec->channels - 1) / (isize * dec->channels);
  970. audio_buf_size = (audio_buf_size * enc->sample_rate + dec->sample_rate) / dec->sample_rate;
  971. audio_buf_size = audio_buf_size * 2 + 10000; // safety factors for the deprecated resampling API
  972. audio_buf_size = FFMAX(audio_buf_size, enc->frame_size);
  973. audio_buf_size *= osize * enc->channels;
  974. if (audio_buf_size > INT_MAX) {
  975. av_log(NULL, AV_LOG_FATAL, "Buffer sizes too large\n");
  976. exit_program(1);
  977. }
  978. av_fast_malloc(&audio_buf, &allocated_audio_buf_size, audio_buf_size);
  979. if (!audio_buf) {
  980. av_log(NULL, AV_LOG_FATAL, "Out of memory in do_audio_out\n");
  981. exit_program(1);
  982. }
  983. if (enc->channels != dec->channels
  984. || enc->sample_fmt != dec->sample_fmt
  985. || enc->sample_rate!= dec->sample_rate
  986. )
  987. ost->audio_resample = 1;
  988. resample_changed = ost->resample_sample_fmt != dec->sample_fmt ||
  989. ost->resample_channels != dec->channels ||
  990. ost->resample_sample_rate != dec->sample_rate;
  991. if ((ost->audio_resample && !ost->swr) || resample_changed || ost->audio_channels_mapped) {
  992. if (resample_changed) {
  993. av_log(NULL, AV_LOG_INFO, "Input stream #%d:%d frame changed from rate:%d fmt:%s ch:%d to rate:%d fmt:%s ch:%d\n",
  994. ist->file_index, ist->st->index,
  995. ost->resample_sample_rate, av_get_sample_fmt_name(ost->resample_sample_fmt), ost->resample_channels,
  996. dec->sample_rate, av_get_sample_fmt_name(dec->sample_fmt), dec->channels);
  997. ost->resample_sample_fmt = dec->sample_fmt;
  998. ost->resample_channels = dec->channels;
  999. ost->resample_sample_rate = dec->sample_rate;
  1000. swr_free(&ost->swr);
  1001. }
  1002. /* if audio_sync_method is >1 the resampler is needed for audio drift compensation */
  1003. if (audio_sync_method <= 1 && !ost->audio_channels_mapped &&
  1004. ost->resample_sample_fmt == enc->sample_fmt &&
  1005. ost->resample_channels == enc->channels &&
  1006. ost->resample_sample_rate == enc->sample_rate) {
  1007. //ost->swr = NULL;
  1008. ost->audio_resample = 0;
  1009. } else {
  1010. ost->swr = swr_alloc_set_opts(ost->swr,
  1011. enc->channel_layout, enc->sample_fmt, enc->sample_rate,
  1012. dec->channel_layout, dec->sample_fmt, dec->sample_rate,
  1013. 0, NULL);
  1014. if (ost->audio_channels_mapped)
  1015. swr_set_channel_mapping(ost->swr, ost->audio_channels_map);
  1016. av_opt_set_double(ost->swr, "rmvol", ost->rematrix_volume, 0);
  1017. if (ost->audio_channels_mapped) {
  1018. av_opt_set_int(ost->swr, "icl", av_get_default_channel_layout(ost->audio_channels_mapped), 0);
  1019. av_opt_set_int(ost->swr, "uch", ost->audio_channels_mapped, 0);
  1020. }
  1021. if (av_opt_set_int(ost->swr, "ich", dec->channels, 0) < 0) {
  1022. av_log(NULL, AV_LOG_FATAL, "Unsupported number of input channels\n");
  1023. exit_program(1);
  1024. }
  1025. if (av_opt_set_int(ost->swr, "och", enc->channels, 0) < 0) {
  1026. av_log(NULL, AV_LOG_FATAL, "Unsupported number of output channels\n");
  1027. exit_program(1);
  1028. }
  1029. if(audio_sync_method>1) av_opt_set_int(ost->swr, "flags", SWR_FLAG_RESAMPLE, 0);
  1030. if(ost->swr && swr_init(ost->swr) < 0){
  1031. av_log(NULL, AV_LOG_FATAL, "swr_init() failed\n");
  1032. swr_free(&ost->swr);
  1033. }
  1034. if (!ost->swr) {
  1035. av_log(NULL, AV_LOG_FATAL, "Can not resample %d channels @ %d Hz to %d channels @ %d Hz\n",
  1036. dec->channels, dec->sample_rate,
  1037. enc->channels, enc->sample_rate);
  1038. exit_program(1);
  1039. }
  1040. }
  1041. }
  1042. av_assert0(ost->audio_resample || dec->sample_fmt==enc->sample_fmt);
  1043. if (audio_sync_method) {
  1044. double delta = get_sync_ipts(ost) * enc->sample_rate - ost->sync_opts -
  1045. av_fifo_size(ost->fifo) / (enc->channels * osize);
  1046. int idelta = delta * dec->sample_rate / enc->sample_rate;
  1047. int byte_delta = idelta * isize * dec->channels;
  1048. // FIXME resample delay
  1049. if (fabs(delta) > 50) {
  1050. if (ist->is_start || fabs(delta) > audio_drift_threshold*enc->sample_rate) {
  1051. if (byte_delta < 0) {
  1052. byte_delta = FFMAX(byte_delta, -size);
  1053. size += byte_delta;
  1054. buf -= byte_delta;
  1055. av_log(NULL, AV_LOG_VERBOSE, "discarding %d audio samples\n",
  1056. -byte_delta / (isize * dec->channels));
  1057. if (!size)
  1058. return;
  1059. ist->is_start = 0;
  1060. } else {
  1061. input_tmp = av_realloc(input_tmp, byte_delta + size);
  1062. if (byte_delta > allocated_for_size - size) {
  1063. allocated_for_size = byte_delta + (int64_t)size;
  1064. goto need_realloc;
  1065. }
  1066. ist->is_start = 0;
  1067. generate_silence(input_tmp, dec->sample_fmt, byte_delta);
  1068. memcpy(input_tmp + byte_delta, buf, size);
  1069. buf = input_tmp;
  1070. size += byte_delta;
  1071. av_log(NULL, AV_LOG_VERBOSE, "adding %d audio samples of silence\n", idelta);
  1072. }
  1073. } else if (audio_sync_method > 1) {
  1074. int comp = av_clip(delta, -audio_sync_method, audio_sync_method);
  1075. av_assert0(ost->audio_resample);
  1076. av_log(NULL, AV_LOG_VERBOSE, "compensating audio timestamp drift:%f compensation:%d in:%d\n",
  1077. delta, comp, enc->sample_rate);
  1078. // fprintf(stderr, "drift:%f len:%d opts:%"PRId64" ipts:%"PRId64" fifo:%d\n", delta, -1, ost->sync_opts, (int64_t)(get_sync_ipts(ost) * enc->sample_rate), av_fifo_size(ost->fifo)/(ost->st->codec->channels * 2));
  1079. swr_set_compensation(ost->swr, comp, enc->sample_rate);
  1080. }
  1081. }
  1082. } else
  1083. ost->sync_opts = lrintf(get_sync_ipts(ost) * enc->sample_rate) -
  1084. av_fifo_size(ost->fifo) / (enc->channels * osize); // FIXME wrong
  1085. if (ost->audio_resample) {
  1086. buftmp = audio_buf;
  1087. size_out = swr_convert(ost->swr, ( uint8_t*[]){buftmp}, audio_buf_size / (enc->channels * osize),
  1088. (const uint8_t*[]){buf }, size / (dec->channels * isize));
  1089. size_out = size_out * enc->channels * osize;
  1090. } else {
  1091. buftmp = buf;
  1092. size_out = size;
  1093. }
  1094. av_assert0(ost->audio_resample || dec->sample_fmt==enc->sample_fmt);
  1095. /* now encode as many frames as possible */
  1096. if (!(enc->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE)) {
  1097. /* output resampled raw samples */
  1098. if (av_fifo_realloc2(ost->fifo, av_fifo_size(ost->fifo) + size_out) < 0) {
  1099. av_log(NULL, AV_LOG_FATAL, "av_fifo_realloc2() failed\n");
  1100. exit_program(1);
  1101. }
  1102. av_fifo_generic_write(ost->fifo, buftmp, size_out, NULL);
  1103. frame_bytes = enc->frame_size * osize * enc->channels;
  1104. while (av_fifo_size(ost->fifo) >= frame_bytes) {
  1105. av_fifo_generic_read(ost->fifo, audio_buf, frame_bytes, NULL);
  1106. encode_audio_frame(s, ost, audio_buf, frame_bytes);
  1107. }
  1108. } else {
  1109. encode_audio_frame(s, ost, buftmp, size_out);
  1110. }
  1111. }
  1112. static void pre_process_video_frame(InputStream *ist, AVPicture *picture, void **bufp)
  1113. {
  1114. AVCodecContext *dec;
  1115. AVPicture *picture2;
  1116. AVPicture picture_tmp;
  1117. uint8_t *buf = 0;
  1118. dec = ist->st->codec;
  1119. /* deinterlace : must be done before any resize */
  1120. if (do_deinterlace) {
  1121. int size;
  1122. /* create temporary picture */
  1123. size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
  1124. buf = av_malloc(size);
  1125. if (!buf)
  1126. return;
  1127. picture2 = &picture_tmp;
  1128. avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
  1129. if (avpicture_deinterlace(picture2, picture,
  1130. dec->pix_fmt, dec->width, dec->height) < 0) {
  1131. /* if error, do not deinterlace */
  1132. av_log(NULL, AV_LOG_WARNING, "Deinterlacing failed\n");
  1133. av_free(buf);
  1134. buf = NULL;
  1135. picture2 = picture;
  1136. }
  1137. } else {
  1138. picture2 = picture;
  1139. }
  1140. if (picture != picture2)
  1141. *picture = *picture2;
  1142. *bufp = buf;
  1143. }
  1144. static void do_subtitle_out(AVFormatContext *s,
  1145. OutputStream *ost,
  1146. InputStream *ist,
  1147. AVSubtitle *sub,
  1148. int64_t pts)
  1149. {
  1150. static uint8_t *subtitle_out = NULL;
  1151. int subtitle_out_max_size = 1024 * 1024;
  1152. int subtitle_out_size, nb, i;
  1153. AVCodecContext *enc;
  1154. AVPacket pkt;
  1155. if (pts == AV_NOPTS_VALUE) {
  1156. av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
  1157. if (exit_on_error)
  1158. exit_program(1);
  1159. return;
  1160. }
  1161. enc = ost->st->codec;
  1162. if (!subtitle_out) {
  1163. subtitle_out = av_malloc(subtitle_out_max_size);
  1164. }
  1165. /* Note: DVB subtitle need one packet to draw them and one other
  1166. packet to clear them */
  1167. /* XXX: signal it in the codec context ? */
  1168. if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
  1169. nb = 2;
  1170. else
  1171. nb = 1;
  1172. for (i = 0; i < nb; i++) {
  1173. sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
  1174. // start_display_time is required to be 0
  1175. sub->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
  1176. sub->end_display_time -= sub->start_display_time;
  1177. sub->start_display_time = 0;
  1178. subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
  1179. subtitle_out_max_size, sub);
  1180. if (subtitle_out_size < 0) {
  1181. av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
  1182. exit_program(1);
  1183. }
  1184. av_init_packet(&pkt);
  1185. pkt.stream_index = ost->index;
  1186. pkt.data = subtitle_out;
  1187. pkt.size = subtitle_out_size;
  1188. pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
  1189. if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
  1190. /* XXX: the pts correction is handled here. Maybe handling
  1191. it in the codec would be better */
  1192. if (i == 0)
  1193. pkt.pts += 90 * sub->start_display_time;
  1194. else
  1195. pkt.pts += 90 * sub->end_display_time;
  1196. }
  1197. write_frame(s, &pkt, ost);
  1198. }
  1199. }
  1200. static int bit_buffer_size = 1024 * 256;
  1201. static uint8_t *bit_buffer = NULL;
  1202. static void do_video_resample(OutputStream *ost,
  1203. InputStream *ist,
  1204. AVFrame *in_picture,
  1205. AVFrame **out_picture)
  1206. {
  1207. #if CONFIG_AVFILTER
  1208. *out_picture = in_picture;
  1209. #else
  1210. AVCodecContext *dec = ist->st->codec;
  1211. AVCodecContext *enc = ost->st->codec;
  1212. int resample_changed = ost->resample_width != in_picture->width ||
  1213. ost->resample_height != in_picture->height ||
  1214. ost->resample_pix_fmt != in_picture->format;
  1215. *out_picture = in_picture;
  1216. if (resample_changed) {
  1217. av_log(NULL, AV_LOG_INFO,
  1218. "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s / frm size:%dx%d fmt:%s\n",
  1219. ist->file_index, ist->st->index,
  1220. ost->resample_width, ost->resample_height, av_get_pix_fmt_name(ost->resample_pix_fmt),
  1221. dec->width , dec->height , av_get_pix_fmt_name(dec->pix_fmt),
  1222. in_picture->width, in_picture->height, av_get_pix_fmt_name(in_picture->format));
  1223. ost->resample_width = in_picture->width;
  1224. ost->resample_height = in_picture->height;
  1225. ost->resample_pix_fmt = in_picture->format;
  1226. }
  1227. ost->video_resample = in_picture->width != enc->width ||
  1228. in_picture->height != enc->height ||
  1229. in_picture->format != enc->pix_fmt;
  1230. if (ost->video_resample) {
  1231. *out_picture = &ost->resample_frame;
  1232. if (!ost->img_resample_ctx || resample_changed) {
  1233. /* initialize the destination picture */
  1234. if (!ost->resample_frame.data[0]) {
  1235. avcodec_get_frame_defaults(&ost->resample_frame);
  1236. if (avpicture_alloc((AVPicture *)&ost->resample_frame, enc->pix_fmt,
  1237. enc->width, enc->height)) {
  1238. av_log(NULL, AV_LOG_FATAL, "Cannot allocate temp picture, check pix fmt\n");
  1239. exit_program(1);
  1240. }
  1241. }
  1242. /* initialize a new scaler context */
  1243. sws_freeContext(ost->img_resample_ctx);
  1244. ost->img_resample_ctx = sws_getContext(in_picture->width, in_picture->height, in_picture->format,
  1245. enc->width, enc->height, enc->pix_fmt,
  1246. ost->sws_flags, NULL, NULL, NULL);
  1247. if (ost->img_resample_ctx == NULL) {
  1248. av_log(NULL, AV_LOG_FATAL, "Cannot get resampling context\n");
  1249. exit_program(1);
  1250. }
  1251. }
  1252. sws_scale(ost->img_resample_ctx, in_picture->data, in_picture->linesize,
  1253. 0, ost->resample_height, (*out_picture)->data, (*out_picture)->linesize);
  1254. }
  1255. #endif
  1256. }
  1257. static void do_video_out(AVFormatContext *s,
  1258. OutputStream *ost,
  1259. InputStream *ist,
  1260. AVFrame *in_picture,
  1261. int *frame_size, float quality)
  1262. {
  1263. int nb_frames, i, ret, format_video_sync;
  1264. AVFrame *final_picture;
  1265. AVCodecContext *enc;
  1266. double sync_ipts;
  1267. double duration = 0;
  1268. enc = ost->st->codec;
  1269. if (ist->st->start_time != AV_NOPTS_VALUE && ist->st->first_dts != AV_NOPTS_VALUE) {
  1270. duration = FFMAX(av_q2d(ist->st->time_base), av_q2d(ist->st->codec->time_base));
  1271. if(ist->st->avg_frame_rate.num)
  1272. duration= FFMAX(duration, 1/av_q2d(ist->st->avg_frame_rate));
  1273. duration /= av_q2d(enc->time_base);
  1274. }
  1275. sync_ipts = get_sync_ipts(ost) / av_q2d(enc->time_base);
  1276. /* by default, we output a single frame */
  1277. nb_frames = 1;
  1278. *frame_size = 0;
  1279. format_video_sync = video_sync_method;
  1280. if (format_video_sync == VSYNC_AUTO)
  1281. format_video_sync = (s->oformat->flags & AVFMT_VARIABLE_FPS) ? ((s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH : VSYNC_VFR) : 1;
  1282. if (format_video_sync != VSYNC_PASSTHROUGH) {
  1283. double vdelta = sync_ipts - ost->sync_opts + duration;
  1284. // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
  1285. if (vdelta < -1.1)
  1286. nb_frames = 0;
  1287. else if (format_video_sync == VSYNC_VFR) {
  1288. if (vdelta <= -0.6) {
  1289. nb_frames = 0;
  1290. } else if (vdelta > 0.6)
  1291. ost->sync_opts = lrintf(sync_ipts);
  1292. } else if (vdelta > 1.1)
  1293. nb_frames = lrintf(vdelta);
  1294. //fprintf(stderr, "vdelta:%f, ost->sync_opts:%"PRId64", ost->sync_ipts:%f nb_frames:%d\n", vdelta, ost->sync_opts, get_sync_ipts(ost), nb_frames);
  1295. if (nb_frames == 0) {
  1296. ++nb_frames_drop;
  1297. av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");
  1298. } else if (nb_frames > 1) {
  1299. nb_frames_dup += nb_frames - 1;
  1300. av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);
  1301. }
  1302. } else
  1303. ost->sync_opts = lrintf(sync_ipts);
  1304. nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
  1305. if (nb_frames <= 0)
  1306. return;
  1307. do_video_resample(ost, ist, in_picture, &final_picture);
  1308. /* duplicates frame if needed */
  1309. for (i = 0; i < nb_frames; i++) {
  1310. AVPacket pkt;
  1311. av_init_packet(&pkt);
  1312. pkt.stream_index = ost->index;
  1313. if (s->oformat->flags & AVFMT_RAWPICTURE &&
  1314. enc->codec->id == CODEC_ID_RAWVIDEO) {
  1315. /* raw pictures are written as AVPicture structure to
  1316. avoid any copies. We support temporarily the older
  1317. method. */
  1318. enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
  1319. enc->coded_frame->top_field_first = in_picture->top_field_first;
  1320. pkt.data = (uint8_t *)final_picture;
  1321. pkt.size = sizeof(AVPicture);
  1322. pkt.pts = av_rescale_q(ost->sync_opts, enc->time_base, ost->st->time_base);
  1323. pkt.flags |= AV_PKT_FLAG_KEY;
  1324. write_frame(s, &pkt, ost);
  1325. } else {
  1326. AVFrame big_picture;
  1327. big_picture = *final_picture;
  1328. /* better than nothing: use input picture interlaced
  1329. settings */
  1330. big_picture.interlaced_frame = in_picture->interlaced_frame;
  1331. if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)) {
  1332. if (ost->top_field_first == -1)
  1333. big_picture.top_field_first = in_picture->top_field_first;
  1334. else
  1335. big_picture.top_field_first = !!ost->top_field_first;
  1336. }
  1337. /* handles same_quant here. This is not correct because it may
  1338. not be a global option */
  1339. big_picture.quality = quality;
  1340. if (!enc->me_threshold)
  1341. big_picture.pict_type = 0;
  1342. // big_picture.pts = AV_NOPTS_VALUE;
  1343. big_picture.pts = ost->sync_opts;
  1344. // big_picture.pts= av_rescale(ost->sync_opts, AV_TIME_BASE*(int64_t)enc->time_base.num, enc->time_base.den);
  1345. // av_log(NULL, AV_LOG_DEBUG, "%"PRId64" -> encoder\n", ost->sync_opts);
  1346. if (ost->forced_kf_index < ost->forced_kf_count &&
  1347. big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
  1348. big_picture.pict_type = AV_PICTURE_TYPE_I;
  1349. ost->forced_kf_index++;
  1350. }
  1351. ret = avcodec_encode_video(enc,
  1352. bit_buffer, bit_buffer_size,
  1353. &big_picture);
  1354. if (ret < 0) {
  1355. av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
  1356. exit_program(1);
  1357. }
  1358. if (ret > 0) {
  1359. pkt.data = bit_buffer;
  1360. pkt.size = ret;
  1361. if (enc->coded_frame->pts != AV_NOPTS_VALUE)
  1362. pkt.pts = av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
  1363. /*av_log(NULL, AV_LOG_DEBUG, "encoder -> %"PRId64"/%"PRId64"\n",
  1364. pkt.pts != AV_NOPTS_VALUE ? av_rescale(pkt.pts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1,
  1365. pkt.dts != AV_NOPTS_VALUE ? av_rescale(pkt.dts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1);*/
  1366. if (enc->coded_frame->key_frame)
  1367. pkt.flags |= AV_PKT_FLAG_KEY;
  1368. write_frame(s, &pkt, ost);
  1369. *frame_size = ret;
  1370. video_size += ret;
  1371. // fprintf(stderr,"\nFrame: %3d size: %5d type: %d",
  1372. // enc->frame_number-1, ret, enc->pict_type);
  1373. /* if two pass, output log */
  1374. if (ost->logfile && enc->stats_out) {
  1375. fprintf(ost->logfile, "%s", enc->stats_out);
  1376. }
  1377. }
  1378. }
  1379. ost->sync_opts++;
  1380. /*
  1381. * For video, number of frames in == number of packets out.
  1382. * But there may be reordering, so we can't throw away frames on encoder
  1383. * flush, we need to limit them here, before they go into encoder.
  1384. */
  1385. ost->frame_number++;
  1386. }
  1387. }
  1388. static double psnr(double d)
  1389. {
  1390. return -10.0 * log(d) / log(10.0);
  1391. }
  1392. static void do_video_stats(AVFormatContext *os, OutputStream *ost,
  1393. int frame_size)
  1394. {
  1395. AVCodecContext *enc;
  1396. int frame_number;
  1397. double ti1, bitrate, avg_bitrate;
  1398. /* this is executed just the first time do_video_stats is called */
  1399. if (!vstats_file) {
  1400. vstats_file = fopen(vstats_filename, "w");
  1401. if (!vstats_file) {
  1402. perror("fopen");
  1403. exit_program(1);
  1404. }
  1405. }
  1406. enc = ost->st->codec;
  1407. if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  1408. frame_number = ost->frame_number;
  1409. fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality / (float)FF_QP2LAMBDA);
  1410. if (enc->flags&CODEC_FLAG_PSNR)
  1411. fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
  1412. fprintf(vstats_file,"f_size= %6d ", frame_size);
  1413. /* compute pts value */
  1414. ti1 = ost->sync_opts * av_q2d(enc->time_base);
  1415. if (ti1 < 0.01)
  1416. ti1 = 0.01;
  1417. bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
  1418. avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
  1419. fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
  1420. (double)video_size / 1024, ti1, bitrate, avg_bitrate);
  1421. fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
  1422. }
  1423. }
  1424. static void print_report(OutputFile *output_files,
  1425. OutputStream *ost_table, int nb_ostreams,
  1426. int is_last_report, int64_t timer_start, int64_t cur_time)
  1427. {
  1428. char buf[1024];
  1429. OutputStream *ost;
  1430. AVFormatContext *oc;
  1431. int64_t total_size;
  1432. AVCodecContext *enc;
  1433. int frame_number, vid, i;
  1434. double bitrate;
  1435. int64_t pts = INT64_MAX;
  1436. static int64_t last_time = -1;
  1437. static int qp_histogram[52];
  1438. int hours, mins, secs, us;
  1439. if (!print_stats && !is_last_report)
  1440. return;
  1441. if (!is_last_report) {
  1442. if (last_time == -1) {
  1443. last_time = cur_time;
  1444. return;
  1445. }
  1446. if ((cur_time - last_time) < 500000)
  1447. return;
  1448. last_time = cur_time;
  1449. }
  1450. oc = output_files[0].ctx;
  1451. total_size = avio_size(oc->pb);
  1452. if (total_size < 0) { // FIXME improve avio_size() so it works with non seekable output too
  1453. total_size = avio_tell(oc->pb);
  1454. if (total_size < 0)
  1455. total_size = 0;
  1456. }
  1457. buf[0] = '\0';
  1458. vid = 0;
  1459. for (i = 0; i < nb_ostreams; i++) {
  1460. float q = -1;
  1461. ost = &ost_table[i];
  1462. enc = ost->st->codec;
  1463. if (!ost->stream_copy && enc->coded_frame)
  1464. q = enc->coded_frame->quality / (float)FF_QP2LAMBDA;
  1465. if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  1466. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
  1467. }
  1468. if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  1469. float t = (cur_time-timer_start) / 1000000.0;
  1470. frame_number = ost->frame_number;
  1471. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3d q=%3.1f ",
  1472. frame_number, (t > 1) ? (int)(frame_number / t + 0.5) : 0, q);
  1473. if (is_last_report)
  1474. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
  1475. if (qp_hist) {
  1476. int j;
  1477. int qp = lrintf(q);
  1478. if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
  1479. qp_histogram[qp]++;
  1480. for (j = 0; j < 32; j++)
  1481. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j] + 1) / log(2)));
  1482. }
  1483. if (enc->flags&CODEC_FLAG_PSNR) {
  1484. int j;
  1485. double error, error_sum = 0;
  1486. double scale, scale_sum = 0;
  1487. char type[3] = { 'Y','U','V' };
  1488. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
  1489. for (j = 0; j < 3; j++) {
  1490. if (is_last_report) {
  1491. error = enc->error[j];
  1492. scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
  1493. } else {
  1494. error = enc->coded_frame->error[j];
  1495. scale = enc->width * enc->height * 255.0 * 255.0;
  1496. }
  1497. if (j)
  1498. scale /= 4;
  1499. error_sum += error;
  1500. scale_sum += scale;
  1501. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error / scale));
  1502. }
  1503. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
  1504. }
  1505. vid = 1;
  1506. }
  1507. /* compute min output value */
  1508. pts = FFMIN(pts, av_rescale_q(ost->st->pts.val,
  1509. ost->st->time_base, AV_TIME_BASE_Q));
  1510. }
  1511. secs = pts / AV_TIME_BASE;
  1512. us = pts % AV_TIME_BASE;
  1513. mins = secs / 60;
  1514. secs %= 60;
  1515. hours = mins / 60;
  1516. mins %= 60;
  1517. bitrate = pts ? total_size * 8 / (pts / 1000.0) : 0;
  1518. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  1519. "size=%8.0fkB time=", total_size / 1024.0);
  1520. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  1521. "%02d:%02d:%02d.%02d ", hours, mins, secs,
  1522. (100 * us) / AV_TIME_BASE);
  1523. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  1524. "bitrate=%6.1fkbits/s", bitrate);
  1525. if (nb_frames_dup || nb_frames_drop)
  1526. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
  1527. nb_frames_dup, nb_frames_drop);
  1528. av_log(NULL, AV_LOG_INFO, "%s \r", buf);
  1529. fflush(stderr);
  1530. if (is_last_report) {
  1531. int64_t raw= audio_size + video_size + extra_size;
  1532. av_log(NULL, AV_LOG_INFO, "\n");
  1533. av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
  1534. video_size / 1024.0,
  1535. audio_size / 1024.0,
  1536. extra_size / 1024.0,
  1537. 100.0 * (total_size - raw) / raw
  1538. );
  1539. if(video_size + audio_size + extra_size == 0){
  1540. av_log(NULL, AV_LOG_WARNING, "Output file is empty, nothing was encoded (check -ss / -t / -frames parameters if used)\n");
  1541. }
  1542. }
  1543. }
  1544. static void flush_encoders(OutputStream *ost_table, int nb_ostreams)
  1545. {
  1546. int i, ret;
  1547. for (i = 0; i < nb_ostreams; i++) {
  1548. OutputStream *ost = &ost_table[i];
  1549. AVCodecContext *enc = ost->st->codec;
  1550. AVFormatContext *os = output_files[ost->file_index].ctx;
  1551. int stop_encoding = 0;
  1552. if (!ost->encoding_needed)
  1553. continue;
  1554. if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
  1555. continue;
  1556. if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == CODEC_ID_RAWVIDEO)
  1557. continue;
  1558. for (;;) {
  1559. AVPacket pkt;
  1560. int fifo_bytes;
  1561. av_init_packet(&pkt);
  1562. pkt.data = NULL;
  1563. pkt.size = 0;
  1564. switch (ost->st->codec->codec_type) {
  1565. case AVMEDIA_TYPE_AUDIO:
  1566. fifo_bytes = av_fifo_size(ost->fifo);
  1567. if (fifo_bytes > 0) {
  1568. /* encode any samples remaining in fifo */
  1569. int frame_bytes = fifo_bytes;
  1570. av_fifo_generic_read(ost->fifo, audio_buf, fifo_bytes, NULL);
  1571. /* pad last frame with silence if needed */
  1572. if (!(enc->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME)) {
  1573. frame_bytes = enc->frame_size * enc->channels *
  1574. av_get_bytes_per_sample(enc->sample_fmt);
  1575. if (allocated_audio_buf_size < frame_bytes)
  1576. exit_program(1);
  1577. generate_silence(audio_buf+fifo_bytes, enc->sample_fmt, frame_bytes - fifo_bytes);
  1578. }
  1579. encode_audio_frame(os, ost, audio_buf, frame_bytes);
  1580. } else {
  1581. /* flush encoder with NULL frames until it is done
  1582. returning packets */
  1583. if (encode_audio_frame(os, ost, NULL, 0) == 0) {
  1584. stop_encoding = 1;
  1585. break;
  1586. }
  1587. }
  1588. break;
  1589. case AVMEDIA_TYPE_VIDEO:
  1590. ret = avcodec_encode_video(enc, bit_buffer, bit_buffer_size, NULL);
  1591. if (ret < 0) {
  1592. av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
  1593. exit_program(1);
  1594. }
  1595. video_size += ret;
  1596. if (enc->coded_frame && enc->coded_frame->key_frame)
  1597. pkt.flags |= AV_PKT_FLAG_KEY;
  1598. if (ost->logfile && enc->stats_out) {
  1599. fprintf(ost->logfile, "%s", enc->stats_out);
  1600. }
  1601. if (ret <= 0) {
  1602. stop_encoding = 1;
  1603. break;
  1604. }
  1605. pkt.stream_index = ost->index;
  1606. pkt.data = bit_buffer;
  1607. pkt.size = ret;
  1608. if (enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
  1609. pkt.pts = av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
  1610. write_frame(os, &pkt, ost);
  1611. break;
  1612. default:
  1613. stop_encoding = 1;
  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 = ist - input_streams;
  1627. if (ost->source_index != ist_index)
  1628. return 0;
  1629. if (of->start_time && ist->pts < of->start_time)
  1630. return 0;
  1631. if (of->recording_time != INT64_MAX &&
  1632. av_compare_ts(ist->pts, AV_TIME_BASE_Q, of->recording_time + of->start_time,
  1633. (AVRational){ 1, 1000000 }) >= 0) {
  1634. ost->is_past_recording_time = 1;
  1635. return 0;
  1636. }
  1637. return 1;
  1638. }
  1639. static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
  1640. {
  1641. OutputFile *of = &output_files[ost->file_index];
  1642. int64_t ost_tb_start_time = av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);
  1643. AVPicture pict;
  1644. AVPacket opkt;
  1645. av_init_packet(&opkt);
  1646. if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
  1647. !ost->copy_initial_nonkeyframes)
  1648. return;
  1649. /* force the input stream PTS */
  1650. if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
  1651. audio_size += pkt->size;
  1652. else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  1653. video_size += pkt->size;
  1654. ost->sync_opts++;
  1655. }
  1656. opkt.stream_index = ost->index;
  1657. if (pkt->pts != AV_NOPTS_VALUE)
  1658. opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
  1659. else
  1660. opkt.pts = AV_NOPTS_VALUE;
  1661. if (pkt->dts == AV_NOPTS_VALUE)
  1662. opkt.dts = av_rescale_q(ist->pts, AV_TIME_BASE_Q, ost->st->time_base);
  1663. else
  1664. opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
  1665. opkt.dts -= ost_tb_start_time;
  1666. opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
  1667. opkt.flags = pkt->flags;
  1668. // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
  1669. if ( ost->st->codec->codec_id != CODEC_ID_H264
  1670. && ost->st->codec->codec_id != CODEC_ID_MPEG1VIDEO
  1671. && ost->st->codec->codec_id != CODEC_ID_MPEG2VIDEO
  1672. ) {
  1673. if (av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY))
  1674. opkt.destruct = av_destruct_packet;
  1675. } else {
  1676. opkt.data = pkt->data;
  1677. opkt.size = pkt->size;
  1678. }
  1679. if (of->ctx->oformat->flags & AVFMT_RAWPICTURE) {
  1680. /* store AVPicture in AVPacket, as expected by the output format */
  1681. avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
  1682. opkt.data = (uint8_t *)&pict;
  1683. opkt.size = sizeof(AVPicture);
  1684. opkt.flags |= AV_PKT_FLAG_KEY;
  1685. }
  1686. write_frame(of->ctx, &opkt, ost);
  1687. ost->st->codec->frame_number++;
  1688. av_free_packet(&opkt);
  1689. }
  1690. static void rate_emu_sleep(InputStream *ist)
  1691. {
  1692. if (input_files[ist->file_index].rate_emu) {
  1693. int64_t pts = av_rescale(ist->pts, 1000000, AV_TIME_BASE);
  1694. int64_t now = av_gettime() - ist->start;
  1695. if (pts > now)
  1696. usleep(pts - now);
  1697. }
  1698. }
  1699. static int transcode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
  1700. {
  1701. AVFrame *decoded_frame;
  1702. AVCodecContext *avctx = ist->st->codec;
  1703. int bps = av_get_bytes_per_sample(ist->st->codec->sample_fmt);
  1704. int i, ret;
  1705. if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
  1706. return AVERROR(ENOMEM);
  1707. else
  1708. avcodec_get_frame_defaults(ist->decoded_frame);
  1709. decoded_frame = ist->decoded_frame;
  1710. ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
  1711. if (ret < 0) {
  1712. return ret;
  1713. }
  1714. if (!*got_output) {
  1715. /* no audio frame */
  1716. return ret;
  1717. }
  1718. /* if the decoder provides a pts, use it instead of the last packet pts.
  1719. the decoder could be delaying output by a packet or more. */
  1720. if (decoded_frame->pts != AV_NOPTS_VALUE)
  1721. ist->next_pts = decoded_frame->pts;
  1722. /* increment next_pts to use for the case where the input stream does not
  1723. have timestamps or there are multiple frames in the packet */
  1724. ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
  1725. avctx->sample_rate;
  1726. // preprocess audio (volume)
  1727. if (audio_volume != 256) {
  1728. int decoded_data_size = decoded_frame->nb_samples * avctx->channels * bps;
  1729. void *samples = decoded_frame->data[0];
  1730. switch (avctx->sample_fmt) {
  1731. case AV_SAMPLE_FMT_U8:
  1732. {
  1733. uint8_t *volp = samples;
  1734. for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
  1735. int v = (((*volp - 128) * audio_volume + 128) >> 8) + 128;
  1736. *volp++ = av_clip_uint8(v);
  1737. }
  1738. break;
  1739. }
  1740. case AV_SAMPLE_FMT_S16:
  1741. {
  1742. int16_t *volp = samples;
  1743. for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
  1744. int v = ((*volp) * audio_volume + 128) >> 8;
  1745. *volp++ = av_clip_int16(v);
  1746. }
  1747. break;
  1748. }
  1749. case AV_SAMPLE_FMT_S32:
  1750. {
  1751. int32_t *volp = samples;
  1752. for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
  1753. int64_t v = (((int64_t)*volp * audio_volume + 128) >> 8);
  1754. *volp++ = av_clipl_int32(v);
  1755. }
  1756. break;
  1757. }
  1758. case AV_SAMPLE_FMT_FLT:
  1759. {
  1760. float *volp = samples;
  1761. float scale = audio_volume / 256.f;
  1762. for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
  1763. *volp++ *= scale;
  1764. }
  1765. break;
  1766. }
  1767. case AV_SAMPLE_FMT_DBL:
  1768. {
  1769. double *volp = samples;
  1770. double scale = audio_volume / 256.;
  1771. for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
  1772. *volp++ *= scale;
  1773. }
  1774. break;
  1775. }
  1776. default:
  1777. av_log(NULL, AV_LOG_FATAL,
  1778. "Audio volume adjustment on sample format %s is not supported.\n",
  1779. av_get_sample_fmt_name(ist->st->codec->sample_fmt));
  1780. exit_program(1);
  1781. }
  1782. }
  1783. rate_emu_sleep(ist);
  1784. for (i = 0; i < nb_output_streams; i++) {
  1785. OutputStream *ost = &output_streams[i];
  1786. if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
  1787. continue;
  1788. do_audio_out(output_files[ost->file_index].ctx, ost, ist, decoded_frame);
  1789. }
  1790. return ret;
  1791. }
  1792. static int transcode_video(InputStream *ist, AVPacket *pkt, int *got_output, int64_t *pkt_pts, int64_t *pkt_dts)
  1793. {
  1794. AVFrame *decoded_frame, *filtered_frame = NULL;
  1795. void *buffer_to_free = NULL;
  1796. int i, ret = 0;
  1797. float quality = 0;
  1798. #if CONFIG_AVFILTER
  1799. int frame_available = 1;
  1800. #endif
  1801. int duration=0;
  1802. int64_t *best_effort_timestamp;
  1803. AVRational *frame_sample_aspect;
  1804. if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
  1805. return AVERROR(ENOMEM);
  1806. else
  1807. avcodec_get_frame_defaults(ist->decoded_frame);
  1808. decoded_frame = ist->decoded_frame;
  1809. pkt->pts = *pkt_pts;
  1810. pkt->dts = *pkt_dts;
  1811. *pkt_pts = AV_NOPTS_VALUE;
  1812. if (pkt->duration) {
  1813. duration = av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
  1814. } else if(ist->st->codec->time_base.num != 0) {
  1815. int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
  1816. duration = ((int64_t)AV_TIME_BASE *
  1817. ist->st->codec->time_base.num * ticks) /
  1818. ist->st->codec->time_base.den;
  1819. }
  1820. if(*pkt_dts != AV_NOPTS_VALUE && duration) {
  1821. *pkt_dts += duration;
  1822. }else
  1823. *pkt_dts = AV_NOPTS_VALUE;
  1824. ret = avcodec_decode_video2(ist->st->codec,
  1825. decoded_frame, got_output, pkt);
  1826. if (ret < 0)
  1827. return ret;
  1828. quality = same_quant ? decoded_frame->quality : 0;
  1829. if (!*got_output) {
  1830. /* no picture yet */
  1831. return ret;
  1832. }
  1833. best_effort_timestamp= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "best_effort_timestamp");
  1834. if(*best_effort_timestamp != AV_NOPTS_VALUE)
  1835. ist->next_pts = ist->pts = *best_effort_timestamp;
  1836. ist->next_pts += duration;
  1837. pkt->size = 0;
  1838. pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);
  1839. #if CONFIG_AVFILTER
  1840. frame_sample_aspect= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "sample_aspect_ratio");
  1841. for(i=0;i<nb_output_streams;i++) {
  1842. OutputStream *ost = ost = &output_streams[i];
  1843. if(check_output_constraints(ist, ost) && ost->encoding_needed){
  1844. if (!frame_sample_aspect->num)
  1845. *frame_sample_aspect = ist->st->sample_aspect_ratio;
  1846. decoded_frame->pts = ist->pts;
  1847. if (ist->dr1 && decoded_frame->type==FF_BUFFER_TYPE_USER) {
  1848. FrameBuffer *buf = decoded_frame->opaque;
  1849. AVFilterBufferRef *fb = avfilter_get_video_buffer_ref_from_arrays(
  1850. decoded_frame->data, decoded_frame->linesize,
  1851. AV_PERM_READ | AV_PERM_PRESERVE,
  1852. ist->st->codec->width, ist->st->codec->height,
  1853. ist->st->codec->pix_fmt);
  1854. avfilter_copy_frame_props(fb, decoded_frame);
  1855. fb->pts = ist->pts;
  1856. fb->buf->priv = buf;
  1857. fb->buf->free = filter_release_buffer;
  1858. buf->refcount++;
  1859. av_buffersrc_buffer(ost->input_video_filter, fb);
  1860. } else
  1861. if((av_vsrc_buffer_add_frame(ost->input_video_filter, decoded_frame, AV_VSRC_BUF_FLAG_OVERWRITE)) < 0){
  1862. av_log(0, AV_LOG_FATAL, "Failed to inject frame into filter network\n");
  1863. exit_program(1);
  1864. }
  1865. }
  1866. }
  1867. #endif
  1868. rate_emu_sleep(ist);
  1869. for (i = 0; i < nb_output_streams; i++) {
  1870. OutputStream *ost = &output_streams[i];
  1871. int frame_size;
  1872. if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
  1873. continue;
  1874. #if CONFIG_AVFILTER
  1875. if (ost->input_video_filter) {
  1876. frame_available = av_buffersink_poll_frame(ost->output_video_filter);
  1877. }
  1878. while (frame_available) {
  1879. if (ost->output_video_filter) {
  1880. AVRational ist_pts_tb = ost->output_video_filter->inputs[0]->time_base;
  1881. if (av_buffersink_get_buffer_ref(ost->output_video_filter, &ost->picref, 0) < 0){
  1882. av_log(0, AV_LOG_WARNING, "AV Filter told us it has a frame available but failed to output one\n");
  1883. goto cont;
  1884. }
  1885. if (!ist->filtered_frame && !(ist->filtered_frame = avcodec_alloc_frame())) {
  1886. av_free(buffer_to_free);
  1887. return AVERROR(ENOMEM);
  1888. } else
  1889. avcodec_get_frame_defaults(ist->filtered_frame);
  1890. filtered_frame = ist->filtered_frame;
  1891. *filtered_frame= *decoded_frame; //for me_threshold
  1892. if (ost->picref) {
  1893. avfilter_fill_frame_from_video_buffer_ref(filtered_frame, ost->picref);
  1894. ist->pts = av_rescale_q(ost->picref->pts, ist_pts_tb, AV_TIME_BASE_Q);
  1895. }
  1896. }
  1897. if (ost->picref->video && !ost->frame_aspect_ratio)
  1898. ost->st->codec->sample_aspect_ratio = ost->picref->video->sample_aspect_ratio;
  1899. #else
  1900. filtered_frame = decoded_frame;
  1901. #endif
  1902. do_video_out(output_files[ost->file_index].ctx, ost, ist, filtered_frame, &frame_size,
  1903. same_quant ? quality : ost->st->codec->global_quality);
  1904. if (vstats_filename && frame_size)
  1905. do_video_stats(output_files[ost->file_index].ctx, ost, frame_size);
  1906. #if CONFIG_AVFILTER
  1907. cont:
  1908. frame_available = ost->output_video_filter && av_buffersink_poll_frame(ost->output_video_filter);
  1909. avfilter_unref_buffer(ost->picref);
  1910. }
  1911. #endif
  1912. }
  1913. av_free(buffer_to_free);
  1914. return ret;
  1915. }
  1916. static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
  1917. {
  1918. AVSubtitle subtitle;
  1919. int i, ret = avcodec_decode_subtitle2(ist->st->codec,
  1920. &subtitle, got_output, pkt);
  1921. if (ret < 0)
  1922. return ret;
  1923. if (!*got_output)
  1924. return ret;
  1925. rate_emu_sleep(ist);
  1926. for (i = 0; i < nb_output_streams; i++) {
  1927. OutputStream *ost = &output_streams[i];
  1928. if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
  1929. continue;
  1930. do_subtitle_out(output_files[ost->file_index].ctx, ost, ist, &subtitle, pkt->pts);
  1931. }
  1932. avsubtitle_free(&subtitle);
  1933. return ret;
  1934. }
  1935. /* pkt = NULL means EOF (needed to flush decoder buffers) */
  1936. static int output_packet(InputStream *ist,
  1937. OutputStream *ost_table, int nb_ostreams,
  1938. const AVPacket *pkt)
  1939. {
  1940. int ret = 0, i;
  1941. int got_output;
  1942. int64_t pkt_dts = AV_NOPTS_VALUE;
  1943. int64_t pkt_pts = AV_NOPTS_VALUE;
  1944. AVPacket avpkt;
  1945. if (ist->next_pts == AV_NOPTS_VALUE)
  1946. ist->next_pts = ist->pts;
  1947. if (pkt == NULL) {
  1948. /* EOF handling */
  1949. av_init_packet(&avpkt);
  1950. avpkt.data = NULL;
  1951. avpkt.size = 0;
  1952. goto handle_eof;
  1953. } else {
  1954. avpkt = *pkt;
  1955. }
  1956. if (pkt->dts != AV_NOPTS_VALUE) {
  1957. if (ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)
  1958. ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
  1959. pkt_dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
  1960. }
  1961. if(pkt->pts != AV_NOPTS_VALUE)
  1962. pkt_pts = av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
  1963. // while we have more to decode or while the decoder did output something on EOF
  1964. while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
  1965. handle_eof:
  1966. ist->pts = ist->next_pts;
  1967. if (avpkt.size && avpkt.size != pkt->size) {
  1968. av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
  1969. "Multiple frames in a packet from stream %d\n", pkt->stream_index);
  1970. ist->showed_multi_packet_warning = 1;
  1971. }
  1972. switch (ist->st->codec->codec_type) {
  1973. case AVMEDIA_TYPE_AUDIO:
  1974. ret = transcode_audio (ist, &avpkt, &got_output);
  1975. break;
  1976. case AVMEDIA_TYPE_VIDEO:
  1977. ret = transcode_video (ist, &avpkt, &got_output, &pkt_pts, &pkt_dts);
  1978. break;
  1979. case AVMEDIA_TYPE_SUBTITLE:
  1980. ret = transcode_subtitles(ist, &avpkt, &got_output);
  1981. break;
  1982. default:
  1983. return -1;
  1984. }
  1985. if (ret < 0)
  1986. return ret;
  1987. avpkt.dts=
  1988. avpkt.pts= AV_NOPTS_VALUE;
  1989. // touch data and size only if not EOF
  1990. if (pkt) {
  1991. if(ist->st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
  1992. ret = avpkt.size;
  1993. avpkt.data += ret;
  1994. avpkt.size -= ret;
  1995. }
  1996. if (!got_output) {
  1997. continue;
  1998. }
  1999. }
  2000. /* handle stream copy */
  2001. if (!ist->decoding_needed) {
  2002. rate_emu_sleep(ist);
  2003. ist->pts = ist->next_pts;
  2004. switch (ist->st->codec->codec_type) {
  2005. case AVMEDIA_TYPE_AUDIO:
  2006. ist->next_pts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
  2007. ist->st->codec->sample_rate;
  2008. break;
  2009. case AVMEDIA_TYPE_VIDEO:
  2010. if (pkt->duration) {
  2011. ist->next_pts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
  2012. } else if(ist->st->codec->time_base.num != 0) {
  2013. int ticks= ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
  2014. ist->next_pts += ((int64_t)AV_TIME_BASE *
  2015. ist->st->codec->time_base.num * ticks) /
  2016. ist->st->codec->time_base.den;
  2017. }
  2018. break;
  2019. }
  2020. }
  2021. for (i = 0; pkt && i < nb_ostreams; i++) {
  2022. OutputStream *ost = &ost_table[i];
  2023. if (!check_output_constraints(ist, ost) || ost->encoding_needed)
  2024. continue;
  2025. do_streamcopy(ist, ost, pkt);
  2026. }
  2027. return 0;
  2028. }
  2029. static void print_sdp(OutputFile *output_files, int n)
  2030. {
  2031. char sdp[2048];
  2032. int i;
  2033. AVFormatContext **avc = av_malloc(sizeof(*avc) * n);
  2034. if (!avc)
  2035. exit_program(1);
  2036. for (i = 0; i < n; i++)
  2037. avc[i] = output_files[i].ctx;
  2038. av_sdp_create(avc, n, sdp, sizeof(sdp));
  2039. printf("SDP:\n%s\n", sdp);
  2040. fflush(stdout);
  2041. av_freep(&avc);
  2042. }
  2043. static int init_input_stream(int ist_index, OutputStream *output_streams, int nb_output_streams,
  2044. char *error, int error_len)
  2045. {
  2046. InputStream *ist = &input_streams[ist_index];
  2047. if (ist->decoding_needed) {
  2048. AVCodec *codec = ist->dec;
  2049. if (!codec) {
  2050. snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
  2051. avcodec_get_name(ist->st->codec->codec_id), ist->file_index, ist->st->index);
  2052. return AVERROR(EINVAL);
  2053. }
  2054. ist->dr1 = codec->capabilities & CODEC_CAP_DR1;
  2055. if (codec->type == AVMEDIA_TYPE_VIDEO && ist->dr1) {
  2056. ist->st->codec->get_buffer = codec_get_buffer;
  2057. ist->st->codec->release_buffer = codec_release_buffer;
  2058. ist->st->codec->opaque = ist;
  2059. }
  2060. if (!av_dict_get(ist->opts, "threads", NULL, 0))
  2061. av_dict_set(&ist->opts, "threads", "auto", 0);
  2062. if (avcodec_open2(ist->st->codec, codec, &ist->opts) < 0) {
  2063. snprintf(error, error_len, "Error while opening decoder for input stream #%d:%d",
  2064. ist->file_index, ist->st->index);
  2065. return AVERROR(EINVAL);
  2066. }
  2067. assert_codec_experimental(ist->st->codec, 0);
  2068. assert_avoptions(ist->opts);
  2069. }
  2070. ist->pts = ist->st->avg_frame_rate.num ? - ist->st->codec->has_b_frames * AV_TIME_BASE / av_q2d(ist->st->avg_frame_rate) : 0;
  2071. ist->next_pts = AV_NOPTS_VALUE;
  2072. ist->is_start = 1;
  2073. return 0;
  2074. }
  2075. static int transcode_init(OutputFile *output_files, int nb_output_files,
  2076. InputFile *input_files, int nb_input_files)
  2077. {
  2078. int ret = 0, i, j, k;
  2079. AVFormatContext *oc;
  2080. AVCodecContext *codec, *icodec;
  2081. OutputStream *ost;
  2082. InputStream *ist;
  2083. char error[1024];
  2084. int want_sdp = 1;
  2085. /* init framerate emulation */
  2086. for (i = 0; i < nb_input_files; i++) {
  2087. InputFile *ifile = &input_files[i];
  2088. if (ifile->rate_emu)
  2089. for (j = 0; j < ifile->nb_streams; j++)
  2090. input_streams[j + ifile->ist_index].start = av_gettime();
  2091. }
  2092. /* output stream init */
  2093. for (i = 0; i < nb_output_files; i++) {
  2094. oc = output_files[i].ctx;
  2095. if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
  2096. av_dump_format(oc, i, oc->filename, 1);
  2097. av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
  2098. return AVERROR(EINVAL);
  2099. }
  2100. }
  2101. /* for each output stream, we compute the right encoding parameters */
  2102. for (i = 0; i < nb_output_streams; i++) {
  2103. ost = &output_streams[i];
  2104. oc = output_files[ost->file_index].ctx;
  2105. ist = &input_streams[ost->source_index];
  2106. if (ost->attachment_filename)
  2107. continue;
  2108. codec = ost->st->codec;
  2109. icodec = ist->st->codec;
  2110. ost->st->disposition = ist->st->disposition;
  2111. codec->bits_per_raw_sample = icodec->bits_per_raw_sample;
  2112. codec->chroma_sample_location = icodec->chroma_sample_location;
  2113. if (ost->stream_copy) {
  2114. uint64_t extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
  2115. if (extra_size > INT_MAX) {
  2116. return AVERROR(EINVAL);
  2117. }
  2118. /* if stream_copy is selected, no need to decode or encode */
  2119. codec->codec_id = icodec->codec_id;
  2120. codec->codec_type = icodec->codec_type;
  2121. if (!codec->codec_tag) {
  2122. if (!oc->oformat->codec_tag ||
  2123. av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
  2124. av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0)
  2125. codec->codec_tag = icodec->codec_tag;
  2126. }
  2127. codec->bit_rate = icodec->bit_rate;
  2128. codec->rc_max_rate = icodec->rc_max_rate;
  2129. codec->rc_buffer_size = icodec->rc_buffer_size;
  2130. codec->field_order = icodec->field_order;
  2131. codec->extradata = av_mallocz(extra_size);
  2132. if (!codec->extradata) {
  2133. return AVERROR(ENOMEM);
  2134. }
  2135. memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
  2136. codec->extradata_size= icodec->extradata_size;
  2137. codec->time_base = ist->st->time_base;
  2138. if(!strcmp(oc->oformat->name, "avi")) {
  2139. if ( copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > 2*av_q2d(ist->st->time_base)
  2140. && av_q2d(ist->st->time_base) < 1.0/500
  2141. || copy_tb==0){
  2142. codec->time_base = icodec->time_base;
  2143. codec->time_base.num *= icodec->ticks_per_frame;
  2144. codec->time_base.den *= 2;
  2145. }
  2146. } else if(!(oc->oformat->flags & AVFMT_VARIABLE_FPS)
  2147. && strcmp(oc->oformat->name, "mov") && strcmp(oc->oformat->name, "mp4") && strcmp(oc->oformat->name, "3gp")
  2148. && strcmp(oc->oformat->name, "3g2") && strcmp(oc->oformat->name, "psp") && strcmp(oc->oformat->name, "ipod")
  2149. ) {
  2150. if( copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base)
  2151. && av_q2d(ist->st->time_base) < 1.0/500
  2152. || copy_tb==0){
  2153. codec->time_base = icodec->time_base;
  2154. codec->time_base.num *= icodec->ticks_per_frame;
  2155. }
  2156. }
  2157. av_reduce(&codec->time_base.num, &codec->time_base.den,
  2158. codec->time_base.num, codec->time_base.den, INT_MAX);
  2159. switch (codec->codec_type) {
  2160. case AVMEDIA_TYPE_AUDIO:
  2161. if (audio_volume != 256) {
  2162. av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
  2163. exit_program(1);
  2164. }
  2165. codec->channel_layout = icodec->channel_layout;
  2166. codec->sample_rate = icodec->sample_rate;
  2167. codec->channels = icodec->channels;
  2168. codec->frame_size = icodec->frame_size;
  2169. codec->audio_service_type = icodec->audio_service_type;
  2170. codec->block_align = icodec->block_align;
  2171. break;
  2172. case AVMEDIA_TYPE_VIDEO:
  2173. codec->pix_fmt = icodec->pix_fmt;
  2174. codec->width = icodec->width;
  2175. codec->height = icodec->height;
  2176. codec->has_b_frames = icodec->has_b_frames;
  2177. if (!codec->sample_aspect_ratio.num) {
  2178. codec->sample_aspect_ratio =
  2179. ost->st->sample_aspect_ratio =
  2180. ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
  2181. ist->st->codec->sample_aspect_ratio.num ?
  2182. ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};
  2183. }
  2184. ost->st->avg_frame_rate = ist->st->avg_frame_rate;
  2185. break;
  2186. case AVMEDIA_TYPE_SUBTITLE:
  2187. codec->width = icodec->width;
  2188. codec->height = icodec->height;
  2189. break;
  2190. case AVMEDIA_TYPE_DATA:
  2191. case AVMEDIA_TYPE_ATTACHMENT:
  2192. break;
  2193. default:
  2194. abort();
  2195. }
  2196. } else {
  2197. if (!ost->enc)
  2198. ost->enc = avcodec_find_encoder(ost->st->codec->codec_id);
  2199. ist->decoding_needed = 1;
  2200. ost->encoding_needed = 1;
  2201. switch (codec->codec_type) {
  2202. case AVMEDIA_TYPE_AUDIO:
  2203. ost->fifo = av_fifo_alloc(1024);
  2204. if (!ost->fifo) {
  2205. return AVERROR(ENOMEM);
  2206. }
  2207. if (!codec->sample_rate)
  2208. codec->sample_rate = icodec->sample_rate;
  2209. choose_sample_rate(ost->st, ost->enc);
  2210. codec->time_base = (AVRational){ 1, codec->sample_rate };
  2211. if (codec->sample_fmt == AV_SAMPLE_FMT_NONE)
  2212. codec->sample_fmt = icodec->sample_fmt;
  2213. choose_sample_fmt(ost->st, ost->enc);
  2214. if (ost->audio_channels_mapped) {
  2215. /* the requested output channel is set to the number of
  2216. * -map_channel only if no -ac are specified */
  2217. if (!codec->channels) {
  2218. codec->channels = ost->audio_channels_mapped;
  2219. codec->channel_layout = av_get_default_channel_layout(codec->channels);
  2220. if (!codec->channel_layout) {
  2221. av_log(NULL, AV_LOG_FATAL, "Unable to find an appropriate channel layout for requested number of channel\n");
  2222. exit_program(1);
  2223. }
  2224. }
  2225. /* fill unused channel mapping with -1 (which means a muted
  2226. * channel in case the number of output channels is bigger
  2227. * than the number of mapped channel) */
  2228. for (j = ost->audio_channels_mapped; j < FF_ARRAY_ELEMS(ost->audio_channels_map); j++)
  2229. ost->audio_channels_map[j] = -1;
  2230. } else if (!codec->channels) {
  2231. codec->channels = icodec->channels;
  2232. codec->channel_layout = icodec->channel_layout;
  2233. }
  2234. if (av_get_channel_layout_nb_channels(codec->channel_layout) != codec->channels)
  2235. codec->channel_layout = 0;
  2236. ost->audio_resample = codec->sample_rate != icodec->sample_rate || audio_sync_method > 1;
  2237. ost->audio_resample |= codec->sample_fmt != icodec->sample_fmt
  2238. || codec->channel_layout != icodec->channel_layout;
  2239. icodec->request_channels = codec->channels;
  2240. ost->resample_sample_fmt = icodec->sample_fmt;
  2241. ost->resample_sample_rate = icodec->sample_rate;
  2242. ost->resample_channels = icodec->channels;
  2243. break;
  2244. case AVMEDIA_TYPE_VIDEO:
  2245. if (codec->pix_fmt == PIX_FMT_NONE)
  2246. codec->pix_fmt = icodec->pix_fmt;
  2247. choose_pixel_fmt(ost->st, ost->enc);
  2248. if (ost->st->codec->pix_fmt == PIX_FMT_NONE) {
  2249. av_log(NULL, AV_LOG_FATAL, "Video pixel format is unknown, stream cannot be encoded\n");
  2250. exit_program(1);
  2251. }
  2252. if (!codec->width || !codec->height) {
  2253. codec->width = icodec->width;
  2254. codec->height = icodec->height;
  2255. }
  2256. ost->video_resample = codec->width != icodec->width ||
  2257. codec->height != icodec->height ||
  2258. codec->pix_fmt != icodec->pix_fmt;
  2259. if (ost->video_resample) {
  2260. codec->bits_per_raw_sample = frame_bits_per_raw_sample;
  2261. }
  2262. ost->resample_height = icodec->height;
  2263. ost->resample_width = icodec->width;
  2264. ost->resample_pix_fmt = icodec->pix_fmt;
  2265. if (!ost->frame_rate.num)
  2266. ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational) { 25, 1 };
  2267. if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
  2268. int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
  2269. ost->frame_rate = ost->enc->supported_framerates[idx];
  2270. }
  2271. codec->time_base = (AVRational){ost->frame_rate.den, ost->frame_rate.num};
  2272. if ( av_q2d(codec->time_base) < 0.001 && video_sync_method
  2273. && (video_sync_method==1 || (video_sync_method<0 && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
  2274. av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not effciciently supporting it.\n"
  2275. "Please consider specifiying a lower framerate, a different muxer or -vsync 2\n");
  2276. }
  2277. for (j = 0; j < ost->forced_kf_count; j++)
  2278. ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
  2279. AV_TIME_BASE_Q,
  2280. codec->time_base);
  2281. #if CONFIG_AVFILTER
  2282. if (configure_video_filters(ist, ost)) {
  2283. av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
  2284. exit(1);
  2285. }
  2286. #endif
  2287. break;
  2288. case AVMEDIA_TYPE_SUBTITLE:
  2289. break;
  2290. default:
  2291. abort();
  2292. break;
  2293. }
  2294. /* two pass mode */
  2295. if (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2)) {
  2296. char logfilename[1024];
  2297. FILE *f;
  2298. snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
  2299. pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,
  2300. i);
  2301. if (!strcmp(ost->enc->name, "libx264")) {
  2302. av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
  2303. } else {
  2304. if (codec->flags & CODEC_FLAG_PASS2) {
  2305. char *logbuffer;
  2306. size_t logbuffer_size;
  2307. if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
  2308. av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
  2309. logfilename);
  2310. exit_program(1);
  2311. }
  2312. codec->stats_in = logbuffer;
  2313. }
  2314. if (codec->flags & CODEC_FLAG_PASS1) {
  2315. f = fopen(logfilename, "wb");
  2316. if (!f) {
  2317. av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
  2318. logfilename, strerror(errno));
  2319. exit_program(1);
  2320. }
  2321. ost->logfile = f;
  2322. }
  2323. }
  2324. }
  2325. }
  2326. if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  2327. /* maximum video buffer size is 8-bytes per pixel, plus DPX header size (1664)*/
  2328. int size = codec->width * codec->height;
  2329. bit_buffer_size = FFMAX(bit_buffer_size, 9*size + 10000);
  2330. }
  2331. }
  2332. if (!bit_buffer)
  2333. bit_buffer = av_malloc(bit_buffer_size);
  2334. if (!bit_buffer) {
  2335. av_log(NULL, AV_LOG_ERROR, "Cannot allocate %d bytes output buffer\n",
  2336. bit_buffer_size);
  2337. return AVERROR(ENOMEM);
  2338. }
  2339. /* open each encoder */
  2340. for (i = 0; i < nb_output_streams; i++) {
  2341. ost = &output_streams[i];
  2342. if (ost->encoding_needed) {
  2343. AVCodec *codec = ost->enc;
  2344. AVCodecContext *dec = input_streams[ost->source_index].st->codec;
  2345. if (!codec) {
  2346. snprintf(error, sizeof(error), "Encoder (codec %s) not found for output stream #%d:%d",
  2347. avcodec_get_name(ost->st->codec->codec_id), ost->file_index, ost->index);
  2348. ret = AVERROR(EINVAL);
  2349. goto dump_format;
  2350. }
  2351. if (dec->subtitle_header) {
  2352. ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);
  2353. if (!ost->st->codec->subtitle_header) {
  2354. ret = AVERROR(ENOMEM);
  2355. goto dump_format;
  2356. }
  2357. memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
  2358. ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
  2359. }
  2360. if (!av_dict_get(ost->opts, "threads", NULL, 0))
  2361. av_dict_set(&ost->opts, "threads", "auto", 0);
  2362. if (avcodec_open2(ost->st->codec, codec, &ost->opts) < 0) {
  2363. snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
  2364. ost->file_index, ost->index);
  2365. ret = AVERROR(EINVAL);
  2366. goto dump_format;
  2367. }
  2368. assert_codec_experimental(ost->st->codec, 1);
  2369. assert_avoptions(ost->opts);
  2370. if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
  2371. av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
  2372. " It takes bits/s as argument, not kbits/s\n");
  2373. extra_size += ost->st->codec->extradata_size;
  2374. if (ost->st->codec->me_threshold)
  2375. input_streams[ost->source_index].st->codec->debug |= FF_DEBUG_MV;
  2376. }
  2377. }
  2378. /* init input streams */
  2379. for (i = 0; i < nb_input_streams; i++)
  2380. if ((ret = init_input_stream(i, output_streams, nb_output_streams, error, sizeof(error))) < 0)
  2381. goto dump_format;
  2382. /* discard unused programs */
  2383. for (i = 0; i < nb_input_files; i++) {
  2384. InputFile *ifile = &input_files[i];
  2385. for (j = 0; j < ifile->ctx->nb_programs; j++) {
  2386. AVProgram *p = ifile->ctx->programs[j];
  2387. int discard = AVDISCARD_ALL;
  2388. for (k = 0; k < p->nb_stream_indexes; k++)
  2389. if (!input_streams[ifile->ist_index + p->stream_index[k]].discard) {
  2390. discard = AVDISCARD_DEFAULT;
  2391. break;
  2392. }
  2393. p->discard = discard;
  2394. }
  2395. }
  2396. /* open files and write file headers */
  2397. for (i = 0; i < nb_output_files; i++) {
  2398. oc = output_files[i].ctx;
  2399. oc->interrupt_callback = int_cb;
  2400. if (avformat_write_header(oc, &output_files[i].opts) < 0) {
  2401. snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?)", i);
  2402. ret = AVERROR(EINVAL);
  2403. goto dump_format;
  2404. }
  2405. // assert_avoptions(output_files[i].opts);
  2406. if (strcmp(oc->oformat->name, "rtp")) {
  2407. want_sdp = 0;
  2408. }
  2409. }
  2410. dump_format:
  2411. /* dump the file output parameters - cannot be done before in case
  2412. of stream copy */
  2413. for (i = 0; i < nb_output_files; i++) {
  2414. av_dump_format(output_files[i].ctx, i, output_files[i].ctx->filename, 1);
  2415. }
  2416. /* dump the stream mapping */
  2417. av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
  2418. for (i = 0; i < nb_output_streams; i++) {
  2419. ost = &output_streams[i];
  2420. if (ost->attachment_filename) {
  2421. /* an attached file */
  2422. av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
  2423. ost->attachment_filename, ost->file_index, ost->index);
  2424. continue;
  2425. }
  2426. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
  2427. input_streams[ost->source_index].file_index,
  2428. input_streams[ost->source_index].st->index,
  2429. ost->file_index,
  2430. ost->index);
  2431. if (ost->audio_channels_mapped) {
  2432. av_log(NULL, AV_LOG_INFO, " [ch:");
  2433. for (j = 0; j < ost->audio_channels_mapped; j++)
  2434. if (ost->audio_channels_map[j] == -1)
  2435. av_log(NULL, AV_LOG_INFO, " M");
  2436. else
  2437. av_log(NULL, AV_LOG_INFO, " %d", ost->audio_channels_map[j]);
  2438. av_log(NULL, AV_LOG_INFO, "]");
  2439. }
  2440. if (ost->sync_ist != &input_streams[ost->source_index])
  2441. av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
  2442. ost->sync_ist->file_index,
  2443. ost->sync_ist->st->index);
  2444. if (ost->stream_copy)
  2445. av_log(NULL, AV_LOG_INFO, " (copy)");
  2446. else
  2447. av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index].dec ?
  2448. input_streams[ost->source_index].dec->name : "?",
  2449. ost->enc ? ost->enc->name : "?");
  2450. av_log(NULL, AV_LOG_INFO, "\n");
  2451. }
  2452. if (ret) {
  2453. av_log(NULL, AV_LOG_ERROR, "%s\n", error);
  2454. return ret;
  2455. }
  2456. if (want_sdp) {
  2457. print_sdp(output_files, nb_output_files);
  2458. }
  2459. return 0;
  2460. }
  2461. /*
  2462. * The following code is the main loop of the file converter
  2463. */
  2464. static int transcode(OutputFile *output_files, int nb_output_files,
  2465. InputFile *input_files, int nb_input_files)
  2466. {
  2467. int ret, i;
  2468. AVFormatContext *is, *os;
  2469. OutputStream *ost;
  2470. InputStream *ist;
  2471. uint8_t *no_packet;
  2472. int no_packet_count = 0;
  2473. int64_t timer_start;
  2474. int key;
  2475. if (!(no_packet = av_mallocz(nb_input_files)))
  2476. exit_program(1);
  2477. ret = transcode_init(output_files, nb_output_files, input_files, nb_input_files);
  2478. if (ret < 0)
  2479. goto fail;
  2480. if (!using_stdin) {
  2481. av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
  2482. }
  2483. timer_start = av_gettime();
  2484. for (; received_sigterm == 0;) {
  2485. int file_index, ist_index;
  2486. AVPacket pkt;
  2487. int64_t ipts_min;
  2488. double opts_min;
  2489. int64_t cur_time= av_gettime();
  2490. ipts_min = INT64_MAX;
  2491. opts_min = 1e100;
  2492. /* if 'q' pressed, exits */
  2493. if (!using_stdin) {
  2494. static int64_t last_time;
  2495. if (received_nb_signals)
  2496. break;
  2497. /* read_key() returns 0 on EOF */
  2498. if(cur_time - last_time >= 100000 && !run_as_daemon){
  2499. key = read_key();
  2500. last_time = cur_time;
  2501. }else
  2502. key = -1;
  2503. if (key == 'q')
  2504. break;
  2505. if (key == '+') av_log_set_level(av_log_get_level()+10);
  2506. if (key == '-') av_log_set_level(av_log_get_level()-10);
  2507. if (key == 's') qp_hist ^= 1;
  2508. if (key == 'h'){
  2509. if (do_hex_dump){
  2510. do_hex_dump = do_pkt_dump = 0;
  2511. } else if(do_pkt_dump){
  2512. do_hex_dump = 1;
  2513. } else
  2514. do_pkt_dump = 1;
  2515. av_log_set_level(AV_LOG_DEBUG);
  2516. }
  2517. #if CONFIG_AVFILTER
  2518. if (key == 'c' || key == 'C'){
  2519. char buf[4096], target[64], command[256], arg[256] = {0};
  2520. double time;
  2521. int k, n = 0;
  2522. fprintf(stderr, "\nEnter command: <target> <time> <command>[ <argument>]\n");
  2523. i = 0;
  2524. while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
  2525. if (k > 0)
  2526. buf[i++] = k;
  2527. buf[i] = 0;
  2528. if (k > 0 &&
  2529. (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
  2530. av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
  2531. target, time, command, arg);
  2532. for (i = 0; i < nb_output_streams; i++) {
  2533. ost = &output_streams[i];
  2534. if (ost->graph) {
  2535. if (time < 0) {
  2536. ret = avfilter_graph_send_command(ost->graph, target, command, arg, buf, sizeof(buf),
  2537. key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
  2538. fprintf(stderr, "Command reply for stream %d: ret:%d res:%s\n", i, ret, buf);
  2539. } else {
  2540. ret = avfilter_graph_queue_command(ost->graph, target, command, arg, 0, time);
  2541. }
  2542. }
  2543. }
  2544. } else {
  2545. av_log(NULL, AV_LOG_ERROR,
  2546. "Parse error, at least 3 arguments were expected, "
  2547. "only %d given in string '%s'\n", n, buf);
  2548. }
  2549. }
  2550. #endif
  2551. if (key == 'd' || key == 'D'){
  2552. int debug=0;
  2553. if(key == 'D') {
  2554. debug = input_streams[0].st->codec->debug<<1;
  2555. if(!debug) debug = 1;
  2556. while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
  2557. debug += debug;
  2558. }else
  2559. if(scanf("%d", &debug)!=1)
  2560. fprintf(stderr,"error parsing debug value\n");
  2561. for(i=0;i<nb_input_streams;i++) {
  2562. input_streams[i].st->codec->debug = debug;
  2563. }
  2564. for(i=0;i<nb_output_streams;i++) {
  2565. ost = &output_streams[i];
  2566. ost->st->codec->debug = debug;
  2567. }
  2568. if(debug) av_log_set_level(AV_LOG_DEBUG);
  2569. fprintf(stderr,"debug=%d\n", debug);
  2570. }
  2571. if (key == '?'){
  2572. fprintf(stderr, "key function\n"
  2573. "? show this help\n"
  2574. "+ increase verbosity\n"
  2575. "- decrease verbosity\n"
  2576. "c Send command to filtergraph\n"
  2577. "D cycle through available debug modes\n"
  2578. "h dump packets/hex press to cycle through the 3 states\n"
  2579. "q quit\n"
  2580. "s Show QP histogram\n"
  2581. );
  2582. }
  2583. }
  2584. /* select the stream that we must read now by looking at the
  2585. smallest output pts */
  2586. file_index = -1;
  2587. for (i = 0; i < nb_output_streams; i++) {
  2588. OutputFile *of;
  2589. int64_t ipts;
  2590. double opts;
  2591. ost = &output_streams[i];
  2592. of = &output_files[ost->file_index];
  2593. os = output_files[ost->file_index].ctx;
  2594. ist = &input_streams[ost->source_index];
  2595. if (ost->is_past_recording_time || no_packet[ist->file_index] ||
  2596. (os->pb && avio_tell(os->pb) >= of->limit_filesize))
  2597. continue;
  2598. opts = ost->st->pts.val * av_q2d(ost->st->time_base);
  2599. ipts = ist->pts;
  2600. if (!input_files[ist->file_index].eof_reached) {
  2601. if (ipts < ipts_min) {
  2602. ipts_min = ipts;
  2603. if (input_sync)
  2604. file_index = ist->file_index;
  2605. }
  2606. if (opts < opts_min) {
  2607. opts_min = opts;
  2608. if (!input_sync) file_index = ist->file_index;
  2609. }
  2610. }
  2611. if (ost->frame_number >= ost->max_frames) {
  2612. int j;
  2613. for (j = 0; j < of->ctx->nb_streams; j++)
  2614. output_streams[of->ost_index + j].is_past_recording_time = 1;
  2615. continue;
  2616. }
  2617. }
  2618. /* if none, if is finished */
  2619. if (file_index < 0) {
  2620. if (no_packet_count) {
  2621. no_packet_count = 0;
  2622. memset(no_packet, 0, nb_input_files);
  2623. usleep(10000);
  2624. continue;
  2625. }
  2626. break;
  2627. }
  2628. /* read a frame from it and output it in the fifo */
  2629. is = input_files[file_index].ctx;
  2630. ret = av_read_frame(is, &pkt);
  2631. if (ret == AVERROR(EAGAIN)) {
  2632. no_packet[file_index] = 1;
  2633. no_packet_count++;
  2634. continue;
  2635. }
  2636. if (ret < 0) {
  2637. input_files[file_index].eof_reached = 1;
  2638. if (opt_shortest)
  2639. break;
  2640. else
  2641. continue;
  2642. }
  2643. no_packet_count = 0;
  2644. memset(no_packet, 0, nb_input_files);
  2645. if (do_pkt_dump) {
  2646. av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
  2647. is->streams[pkt.stream_index]);
  2648. }
  2649. /* the following test is needed in case new streams appear
  2650. dynamically in stream : we ignore them */
  2651. if (pkt.stream_index >= input_files[file_index].nb_streams)
  2652. goto discard_packet;
  2653. ist_index = input_files[file_index].ist_index + pkt.stream_index;
  2654. ist = &input_streams[ist_index];
  2655. if (ist->discard)
  2656. goto discard_packet;
  2657. if (pkt.dts != AV_NOPTS_VALUE)
  2658. pkt.dts += av_rescale_q(input_files[ist->file_index].ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
  2659. if (pkt.pts != AV_NOPTS_VALUE)
  2660. pkt.pts += av_rescale_q(input_files[ist->file_index].ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
  2661. if (pkt.pts != AV_NOPTS_VALUE)
  2662. pkt.pts *= ist->ts_scale;
  2663. if (pkt.dts != AV_NOPTS_VALUE)
  2664. pkt.dts *= ist->ts_scale;
  2665. //fprintf(stderr, "next:%"PRId64" dts:%"PRId64" off:%"PRId64" %d\n",
  2666. // ist->next_pts,
  2667. // pkt.dts, input_files[ist->file_index].ts_offset,
  2668. // ist->st->codec->codec_type);
  2669. if (pkt.dts != AV_NOPTS_VALUE && ist->next_pts != AV_NOPTS_VALUE
  2670. && (is->iformat->flags & AVFMT_TS_DISCONT)) {
  2671. int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
  2672. int64_t delta = pkt_dts - ist->next_pts;
  2673. if((delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
  2674. (delta > 1LL*dts_delta_threshold*AV_TIME_BASE &&
  2675. ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
  2676. pkt_dts+1<ist->pts)&& !copy_ts){
  2677. input_files[ist->file_index].ts_offset -= delta;
  2678. av_log(NULL, AV_LOG_DEBUG,
  2679. "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
  2680. delta, input_files[ist->file_index].ts_offset);
  2681. pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  2682. if (pkt.pts != AV_NOPTS_VALUE)
  2683. pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  2684. }
  2685. }
  2686. // fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->st->index, pkt.size);
  2687. if (output_packet(ist, output_streams, nb_output_streams, &pkt) < 0) {
  2688. av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d\n",
  2689. ist->file_index, ist->st->index);
  2690. if (exit_on_error)
  2691. exit_program(1);
  2692. av_free_packet(&pkt);
  2693. continue;
  2694. }
  2695. discard_packet:
  2696. av_free_packet(&pkt);
  2697. /* dump report by using the output first video and audio streams */
  2698. print_report(output_files, output_streams, nb_output_streams, 0, timer_start, cur_time);
  2699. }
  2700. /* at the end of stream, we must flush the decoder buffers */
  2701. for (i = 0; i < nb_input_streams; i++) {
  2702. ist = &input_streams[i];
  2703. if (ist->decoding_needed) {
  2704. output_packet(ist, output_streams, nb_output_streams, NULL);
  2705. }
  2706. }
  2707. flush_encoders(output_streams, nb_output_streams);
  2708. term_exit();
  2709. /* write the trailer if needed and close file */
  2710. for (i = 0; i < nb_output_files; i++) {
  2711. os = output_files[i].ctx;
  2712. av_write_trailer(os);
  2713. }
  2714. /* dump report by using the first video and audio streams */
  2715. print_report(output_files, output_streams, nb_output_streams, 1, timer_start, av_gettime());
  2716. /* close each encoder */
  2717. for (i = 0; i < nb_output_streams; i++) {
  2718. ost = &output_streams[i];
  2719. if (ost->encoding_needed) {
  2720. av_freep(&ost->st->codec->stats_in);
  2721. avcodec_close(ost->st->codec);
  2722. }
  2723. #if CONFIG_AVFILTER
  2724. avfilter_graph_free(&ost->graph);
  2725. #endif
  2726. }
  2727. /* close each decoder */
  2728. for (i = 0; i < nb_input_streams; i++) {
  2729. ist = &input_streams[i];
  2730. if (ist->decoding_needed) {
  2731. avcodec_close(ist->st->codec);
  2732. }
  2733. }
  2734. /* finished ! */
  2735. ret = 0;
  2736. fail:
  2737. av_freep(&bit_buffer);
  2738. av_freep(&no_packet);
  2739. if (output_streams) {
  2740. for (i = 0; i < nb_output_streams; i++) {
  2741. ost = &output_streams[i];
  2742. if (ost) {
  2743. if (ost->stream_copy)
  2744. av_freep(&ost->st->codec->extradata);
  2745. if (ost->logfile) {
  2746. fclose(ost->logfile);
  2747. ost->logfile = NULL;
  2748. }
  2749. av_fifo_free(ost->fifo); /* works even if fifo is not
  2750. initialized but set to zero */
  2751. av_freep(&ost->st->codec->subtitle_header);
  2752. av_free(ost->resample_frame.data[0]);
  2753. av_free(ost->forced_kf_pts);
  2754. if (ost->video_resample)
  2755. sws_freeContext(ost->img_resample_ctx);
  2756. swr_free(&ost->swr);
  2757. av_dict_free(&ost->opts);
  2758. }
  2759. }
  2760. }
  2761. return ret;
  2762. }
  2763. static int opt_frame_crop(const char *opt, const char *arg)
  2764. {
  2765. av_log(NULL, AV_LOG_FATAL, "Option '%s' has been removed, use the crop filter instead\n", opt);
  2766. return AVERROR(EINVAL);
  2767. }
  2768. static int opt_pad(const char *opt, const char *arg)
  2769. {
  2770. av_log(NULL, AV_LOG_FATAL, "Option '%s' has been removed, use the pad filter instead\n", opt);
  2771. return -1;
  2772. }
  2773. static double parse_frame_aspect_ratio(const char *arg)
  2774. {
  2775. int x = 0, y = 0;
  2776. double ar = 0;
  2777. const char *p;
  2778. char *end;
  2779. p = strchr(arg, ':');
  2780. if (p) {
  2781. x = strtol(arg, &end, 10);
  2782. if (end == p)
  2783. y = strtol(end + 1, &end, 10);
  2784. if (x > 0 && y > 0)
  2785. ar = (double)x / (double)y;
  2786. } else
  2787. ar = strtod(arg, NULL);
  2788. if (!ar) {
  2789. av_log(NULL, AV_LOG_FATAL, "Incorrect aspect ratio specification.\n");
  2790. exit_program(1);
  2791. }
  2792. return ar;
  2793. }
  2794. static int opt_video_channel(const char *opt, const char *arg)
  2795. {
  2796. av_log(NULL, AV_LOG_WARNING, "This option is deprecated, use -channel.\n");
  2797. return opt_default("channel", arg);
  2798. }
  2799. static int opt_video_standard(const char *opt, const char *arg)
  2800. {
  2801. av_log(NULL, AV_LOG_WARNING, "This option is deprecated, use -standard.\n");
  2802. return opt_default("standard", arg);
  2803. }
  2804. static int opt_audio_codec(OptionsContext *o, const char *opt, const char *arg)
  2805. {
  2806. audio_codec_name = arg;
  2807. return parse_option(o, "codec:a", arg, options);
  2808. }
  2809. static int opt_video_codec(OptionsContext *o, const char *opt, const char *arg)
  2810. {
  2811. video_codec_name = arg;
  2812. return parse_option(o, "codec:v", arg, options);
  2813. }
  2814. static int opt_subtitle_codec(OptionsContext *o, const char *opt, const char *arg)
  2815. {
  2816. subtitle_codec_name = arg;
  2817. return parse_option(o, "codec:s", arg, options);
  2818. }
  2819. static int opt_data_codec(OptionsContext *o, const char *opt, const char *arg)
  2820. {
  2821. return parse_option(o, "codec:d", arg, options);
  2822. }
  2823. static int opt_map(OptionsContext *o, const char *opt, const char *arg)
  2824. {
  2825. StreamMap *m = NULL;
  2826. int i, negative = 0, file_idx;
  2827. int sync_file_idx = -1, sync_stream_idx = 0;
  2828. char *p, *sync;
  2829. char *map;
  2830. if (*arg == '-') {
  2831. negative = 1;
  2832. arg++;
  2833. }
  2834. map = av_strdup(arg);
  2835. /* parse sync stream first, just pick first matching stream */
  2836. if (sync = strchr(map, ',')) {
  2837. *sync = 0;
  2838. sync_file_idx = strtol(sync + 1, &sync, 0);
  2839. if (sync_file_idx >= nb_input_files || sync_file_idx < 0) {
  2840. av_log(NULL, AV_LOG_FATAL, "Invalid sync file index: %d.\n", sync_file_idx);
  2841. exit_program(1);
  2842. }
  2843. if (*sync)
  2844. sync++;
  2845. for (i = 0; i < input_files[sync_file_idx].nb_streams; i++)
  2846. if (check_stream_specifier(input_files[sync_file_idx].ctx,
  2847. input_files[sync_file_idx].ctx->streams[i], sync) == 1) {
  2848. sync_stream_idx = i;
  2849. break;
  2850. }
  2851. if (i == input_files[sync_file_idx].nb_streams) {
  2852. av_log(NULL, AV_LOG_FATAL, "Sync stream specification in map %s does not "
  2853. "match any streams.\n", arg);
  2854. exit_program(1);
  2855. }
  2856. }
  2857. file_idx = strtol(map, &p, 0);
  2858. if (file_idx >= nb_input_files || file_idx < 0) {
  2859. av_log(NULL, AV_LOG_FATAL, "Invalid input file index: %d.\n", file_idx);
  2860. exit_program(1);
  2861. }
  2862. if (negative)
  2863. /* disable some already defined maps */
  2864. for (i = 0; i < o->nb_stream_maps; i++) {
  2865. m = &o->stream_maps[i];
  2866. if (file_idx == m->file_index &&
  2867. check_stream_specifier(input_files[m->file_index].ctx,
  2868. input_files[m->file_index].ctx->streams[m->stream_index],
  2869. *p == ':' ? p + 1 : p) > 0)
  2870. m->disabled = 1;
  2871. }
  2872. else
  2873. for (i = 0; i < input_files[file_idx].nb_streams; i++) {
  2874. if (check_stream_specifier(input_files[file_idx].ctx, input_files[file_idx].ctx->streams[i],
  2875. *p == ':' ? p + 1 : p) <= 0)
  2876. continue;
  2877. o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
  2878. &o->nb_stream_maps, o->nb_stream_maps + 1);
  2879. m = &o->stream_maps[o->nb_stream_maps - 1];
  2880. m->file_index = file_idx;
  2881. m->stream_index = i;
  2882. if (sync_file_idx >= 0) {
  2883. m->sync_file_index = sync_file_idx;
  2884. m->sync_stream_index = sync_stream_idx;
  2885. } else {
  2886. m->sync_file_index = file_idx;
  2887. m->sync_stream_index = i;
  2888. }
  2889. }
  2890. if (!m) {
  2891. av_log(NULL, AV_LOG_FATAL, "Stream map '%s' matches no streams.\n", arg);
  2892. exit_program(1);
  2893. }
  2894. av_freep(&map);
  2895. return 0;
  2896. }
  2897. static int opt_attach(OptionsContext *o, const char *opt, const char *arg)
  2898. {
  2899. o->attachments = grow_array(o->attachments, sizeof(*o->attachments),
  2900. &o->nb_attachments, o->nb_attachments + 1);
  2901. o->attachments[o->nb_attachments - 1] = arg;
  2902. return 0;
  2903. }
  2904. static int opt_map_channel(OptionsContext *o, const char *opt, const char *arg)
  2905. {
  2906. int n;
  2907. AVStream *st;
  2908. AudioChannelMap *m;
  2909. o->audio_channel_maps =
  2910. grow_array(o->audio_channel_maps, sizeof(*o->audio_channel_maps),
  2911. &o->nb_audio_channel_maps, o->nb_audio_channel_maps + 1);
  2912. m = &o->audio_channel_maps[o->nb_audio_channel_maps - 1];
  2913. /* muted channel syntax */
  2914. n = sscanf(arg, "%d:%d.%d", &m->channel_idx, &m->ofile_idx, &m->ostream_idx);
  2915. if ((n == 1 || n == 3) && m->channel_idx == -1) {
  2916. m->file_idx = m->stream_idx = -1;
  2917. if (n == 1)
  2918. m->ofile_idx = m->ostream_idx = -1;
  2919. return 0;
  2920. }
  2921. /* normal syntax */
  2922. n = sscanf(arg, "%d.%d.%d:%d.%d",
  2923. &m->file_idx, &m->stream_idx, &m->channel_idx,
  2924. &m->ofile_idx, &m->ostream_idx);
  2925. if (n != 3 && n != 5) {
  2926. av_log(NULL, AV_LOG_FATAL, "Syntax error, mapchan usage: "
  2927. "[file.stream.channel|-1][:syncfile:syncstream]\n");
  2928. exit_program(1);
  2929. }
  2930. if (n != 5) // only file.stream.channel specified
  2931. m->ofile_idx = m->ostream_idx = -1;
  2932. /* check input */
  2933. if (m->file_idx < 0 || m->file_idx >= nb_input_files) {
  2934. av_log(NULL, AV_LOG_FATAL, "mapchan: invalid input file index: %d\n",
  2935. m->file_idx);
  2936. exit_program(1);
  2937. }
  2938. if (m->stream_idx < 0 ||
  2939. m->stream_idx >= input_files[m->file_idx].nb_streams) {
  2940. av_log(NULL, AV_LOG_FATAL, "mapchan: invalid input file stream index #%d.%d\n",
  2941. m->file_idx, m->stream_idx);
  2942. exit_program(1);
  2943. }
  2944. st = input_files[m->file_idx].ctx->streams[m->stream_idx];
  2945. if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
  2946. av_log(NULL, AV_LOG_FATAL, "mapchan: stream #%d.%d is not an audio stream.\n",
  2947. m->file_idx, m->stream_idx);
  2948. exit_program(1);
  2949. }
  2950. if (m->channel_idx < 0 || m->channel_idx >= st->codec->channels) {
  2951. av_log(NULL, AV_LOG_FATAL, "mapchan: invalid audio channel #%d.%d.%d\n",
  2952. m->file_idx, m->stream_idx, m->channel_idx);
  2953. exit_program(1);
  2954. }
  2955. return 0;
  2956. }
  2957. /**
  2958. * Parse a metadata specifier in arg.
  2959. * @param type metadata type is written here -- g(lobal)/s(tream)/c(hapter)/p(rogram)
  2960. * @param index for type c/p, chapter/program index is written here
  2961. * @param stream_spec for type s, the stream specifier is written here
  2962. */
  2963. static void parse_meta_type(char *arg, char *type, int *index, const char **stream_spec)
  2964. {
  2965. if (*arg) {
  2966. *type = *arg;
  2967. switch (*arg) {
  2968. case 'g':
  2969. break;
  2970. case 's':
  2971. if (*(++arg) && *arg != ':') {
  2972. av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", arg);
  2973. exit_program(1);
  2974. }
  2975. *stream_spec = *arg == ':' ? arg + 1 : "";
  2976. break;
  2977. case 'c':
  2978. case 'p':
  2979. if (*(++arg) == ':')
  2980. *index = strtol(++arg, NULL, 0);
  2981. break;
  2982. default:
  2983. av_log(NULL, AV_LOG_FATAL, "Invalid metadata type %c.\n", *arg);
  2984. exit_program(1);
  2985. }
  2986. } else
  2987. *type = 'g';
  2988. }
  2989. static int copy_metadata(char *outspec, char *inspec, AVFormatContext *oc, AVFormatContext *ic, OptionsContext *o)
  2990. {
  2991. AVDictionary **meta_in = NULL;
  2992. AVDictionary **meta_out = NULL;
  2993. int i, ret = 0;
  2994. char type_in, type_out;
  2995. const char *istream_spec = NULL, *ostream_spec = NULL;
  2996. int idx_in = 0, idx_out = 0;
  2997. parse_meta_type(inspec, &type_in, &idx_in, &istream_spec);
  2998. parse_meta_type(outspec, &type_out, &idx_out, &ostream_spec);
  2999. if (type_in == 'g' || type_out == 'g')
  3000. o->metadata_global_manual = 1;
  3001. if (type_in == 's' || type_out == 's')
  3002. o->metadata_streams_manual = 1;
  3003. if (type_in == 'c' || type_out == 'c')
  3004. o->metadata_chapters_manual = 1;
  3005. #define METADATA_CHECK_INDEX(index, nb_elems, desc)\
  3006. if ((index) < 0 || (index) >= (nb_elems)) {\
  3007. av_log(NULL, AV_LOG_FATAL, "Invalid %s index %d while processing metadata maps.\n",\
  3008. (desc), (index));\
  3009. exit_program(1);\
  3010. }
  3011. #define SET_DICT(type, meta, context, index)\
  3012. switch (type) {\
  3013. case 'g':\
  3014. meta = &context->metadata;\
  3015. break;\
  3016. case 'c':\
  3017. METADATA_CHECK_INDEX(index, context->nb_chapters, "chapter")\
  3018. meta = &context->chapters[index]->metadata;\
  3019. break;\
  3020. case 'p':\
  3021. METADATA_CHECK_INDEX(index, context->nb_programs, "program")\
  3022. meta = &context->programs[index]->metadata;\
  3023. break;\
  3024. }\
  3025. SET_DICT(type_in, meta_in, ic, idx_in);
  3026. SET_DICT(type_out, meta_out, oc, idx_out);
  3027. /* for input streams choose first matching stream */
  3028. if (type_in == 's') {
  3029. for (i = 0; i < ic->nb_streams; i++) {
  3030. if ((ret = check_stream_specifier(ic, ic->streams[i], istream_spec)) > 0) {
  3031. meta_in = &ic->streams[i]->metadata;
  3032. break;
  3033. } else if (ret < 0)
  3034. exit_program(1);
  3035. }
  3036. if (!meta_in) {
  3037. av_log(NULL, AV_LOG_FATAL, "Stream specifier %s does not match any streams.\n", istream_spec);
  3038. exit_program(1);
  3039. }
  3040. }
  3041. if (type_out == 's') {
  3042. for (i = 0; i < oc->nb_streams; i++) {
  3043. if ((ret = check_stream_specifier(oc, oc->streams[i], ostream_spec)) > 0) {
  3044. meta_out = &oc->streams[i]->metadata;
  3045. av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
  3046. } else if (ret < 0)
  3047. exit_program(1);
  3048. }
  3049. } else
  3050. av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
  3051. return 0;
  3052. }
  3053. static int opt_recording_timestamp(OptionsContext *o, const char *opt, const char *arg)
  3054. {
  3055. char buf[128];
  3056. int64_t recording_timestamp = parse_time_or_die(opt, arg, 0) / 1E6;
  3057. struct tm time = *gmtime((time_t*)&recording_timestamp);
  3058. strftime(buf, sizeof(buf), "creation_time=%FT%T%z", &time);
  3059. parse_option(o, "metadata", buf, options);
  3060. av_log(NULL, AV_LOG_WARNING, "%s is deprecated, set the 'creation_time' metadata "
  3061. "tag instead.\n", opt);
  3062. return 0;
  3063. }
  3064. static AVCodec *find_codec_or_die(const char *name, enum AVMediaType type, int encoder)
  3065. {
  3066. const char *codec_string = encoder ? "encoder" : "decoder";
  3067. AVCodec *codec;
  3068. codec = encoder ?
  3069. avcodec_find_encoder_by_name(name) :
  3070. avcodec_find_decoder_by_name(name);
  3071. if (!codec) {
  3072. av_log(NULL, AV_LOG_FATAL, "Unknown %s '%s'\n", codec_string, name);
  3073. exit_program(1);
  3074. }
  3075. if (codec->type != type) {
  3076. av_log(NULL, AV_LOG_FATAL, "Invalid %s type '%s'\n", codec_string, name);
  3077. exit_program(1);
  3078. }
  3079. return codec;
  3080. }
  3081. static AVCodec *choose_decoder(OptionsContext *o, AVFormatContext *s, AVStream *st)
  3082. {
  3083. char *codec_name = NULL;
  3084. MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, st);
  3085. if (codec_name) {
  3086. AVCodec *codec = find_codec_or_die(codec_name, st->codec->codec_type, 0);
  3087. st->codec->codec_id = codec->id;
  3088. return codec;
  3089. } else
  3090. return avcodec_find_decoder(st->codec->codec_id);
  3091. }
  3092. /**
  3093. * Add all the streams from the given input file to the global
  3094. * list of input streams.
  3095. */
  3096. static void add_input_streams(OptionsContext *o, AVFormatContext *ic)
  3097. {
  3098. int i;
  3099. char *next, *codec_tag = NULL;
  3100. for (i = 0; i < ic->nb_streams; i++) {
  3101. AVStream *st = ic->streams[i];
  3102. AVCodecContext *dec = st->codec;
  3103. InputStream *ist;
  3104. input_streams = grow_array(input_streams, sizeof(*input_streams), &nb_input_streams, nb_input_streams + 1);
  3105. ist = &input_streams[nb_input_streams - 1];
  3106. ist->st = st;
  3107. ist->file_index = nb_input_files;
  3108. ist->discard = 1;
  3109. ist->opts = filter_codec_opts(codec_opts, choose_decoder(o, ic, st), ic, st);
  3110. ist->ts_scale = 1.0;
  3111. MATCH_PER_STREAM_OPT(ts_scale, dbl, ist->ts_scale, ic, st);
  3112. MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, ic, st);
  3113. if (codec_tag) {
  3114. uint32_t tag = strtol(codec_tag, &next, 0);
  3115. if (*next)
  3116. tag = AV_RL32(codec_tag);
  3117. st->codec->codec_tag = tag;
  3118. }
  3119. ist->dec = choose_decoder(o, ic, st);
  3120. switch (dec->codec_type) {
  3121. case AVMEDIA_TYPE_AUDIO:
  3122. if (!ist->dec)
  3123. ist->dec = avcodec_find_decoder(dec->codec_id);
  3124. if (o->audio_disable)
  3125. st->discard = AVDISCARD_ALL;
  3126. break;
  3127. case AVMEDIA_TYPE_VIDEO:
  3128. if(!ist->dec)
  3129. ist->dec = avcodec_find_decoder(dec->codec_id);
  3130. if (dec->lowres) {
  3131. dec->flags |= CODEC_FLAG_EMU_EDGE;
  3132. }
  3133. if (o->video_disable)
  3134. st->discard = AVDISCARD_ALL;
  3135. else if (video_discard)
  3136. st->discard = video_discard;
  3137. break;
  3138. case AVMEDIA_TYPE_DATA:
  3139. if (o->data_disable)
  3140. st->discard= AVDISCARD_ALL;
  3141. break;
  3142. case AVMEDIA_TYPE_SUBTITLE:
  3143. if(!ist->dec)
  3144. ist->dec = avcodec_find_decoder(dec->codec_id);
  3145. if(o->subtitle_disable)
  3146. st->discard = AVDISCARD_ALL;
  3147. break;
  3148. case AVMEDIA_TYPE_ATTACHMENT:
  3149. case AVMEDIA_TYPE_UNKNOWN:
  3150. break;
  3151. default:
  3152. abort();
  3153. }
  3154. }
  3155. }
  3156. static void assert_file_overwrite(const char *filename)
  3157. {
  3158. if ((!file_overwrite || no_file_overwrite) &&
  3159. (strchr(filename, ':') == NULL || filename[1] == ':' ||
  3160. av_strstart(filename, "file:", NULL))) {
  3161. if (avio_check(filename, 0) == 0) {
  3162. if (!using_stdin && (!no_file_overwrite || file_overwrite)) {
  3163. fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
  3164. fflush(stderr);
  3165. term_exit();
  3166. signal(SIGINT, SIG_DFL);
  3167. if (!read_yesno()) {
  3168. av_log(0, AV_LOG_FATAL, "Not overwriting - exiting\n");
  3169. exit_program(1);
  3170. }
  3171. term_init();
  3172. }
  3173. else {
  3174. av_log(0, AV_LOG_FATAL, "File '%s' already exists. Exiting.\n", filename);
  3175. exit_program(1);
  3176. }
  3177. }
  3178. }
  3179. }
  3180. static void dump_attachment(AVStream *st, const char *filename)
  3181. {
  3182. int ret;
  3183. AVIOContext *out = NULL;
  3184. AVDictionaryEntry *e;
  3185. if (!st->codec->extradata_size) {
  3186. av_log(NULL, AV_LOG_WARNING, "No extradata to dump in stream #%d:%d.\n",
  3187. nb_input_files - 1, st->index);
  3188. return;
  3189. }
  3190. if (!*filename && (e = av_dict_get(st->metadata, "filename", NULL, 0)))
  3191. filename = e->value;
  3192. if (!*filename) {
  3193. av_log(NULL, AV_LOG_FATAL, "No filename specified and no 'filename' tag"
  3194. "in stream #%d:%d.\n", nb_input_files - 1, st->index);
  3195. exit_program(1);
  3196. }
  3197. assert_file_overwrite(filename);
  3198. if ((ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, &int_cb, NULL)) < 0) {
  3199. av_log(NULL, AV_LOG_FATAL, "Could not open file %s for writing.\n",
  3200. filename);
  3201. exit_program(1);
  3202. }
  3203. avio_write(out, st->codec->extradata, st->codec->extradata_size);
  3204. avio_flush(out);
  3205. avio_close(out);
  3206. }
  3207. static int opt_input_file(OptionsContext *o, const char *opt, const char *filename)
  3208. {
  3209. AVFormatContext *ic;
  3210. AVInputFormat *file_iformat = NULL;
  3211. int err, i, ret;
  3212. int64_t timestamp;
  3213. uint8_t buf[128];
  3214. AVDictionary **opts;
  3215. int orig_nb_streams; // number of streams before avformat_find_stream_info
  3216. if (o->format) {
  3217. if (!(file_iformat = av_find_input_format(o->format))) {
  3218. av_log(NULL, AV_LOG_FATAL, "Unknown input format: '%s'\n", o->format);
  3219. exit_program(1);
  3220. }
  3221. }
  3222. if (!strcmp(filename, "-"))
  3223. filename = "pipe:";
  3224. using_stdin |= !strncmp(filename, "pipe:", 5) ||
  3225. !strcmp(filename, "/dev/stdin");
  3226. /* get default parameters from command line */
  3227. ic = avformat_alloc_context();
  3228. if (!ic) {
  3229. print_error(filename, AVERROR(ENOMEM));
  3230. exit_program(1);
  3231. }
  3232. if (o->nb_audio_sample_rate) {
  3233. snprintf(buf, sizeof(buf), "%d", o->audio_sample_rate[o->nb_audio_sample_rate - 1].u.i);
  3234. av_dict_set(&format_opts, "sample_rate", buf, 0);
  3235. }
  3236. if (o->nb_audio_channels) {
  3237. snprintf(buf, sizeof(buf), "%d", o->audio_channels[o->nb_audio_channels - 1].u.i);
  3238. av_dict_set(&format_opts, "channels", buf, 0);
  3239. }
  3240. if (o->nb_frame_rates) {
  3241. av_dict_set(&format_opts, "framerate", o->frame_rates[o->nb_frame_rates - 1].u.str, 0);
  3242. }
  3243. if (o->nb_frame_sizes) {
  3244. av_dict_set(&format_opts, "video_size", o->frame_sizes[o->nb_frame_sizes - 1].u.str, 0);
  3245. }
  3246. if (o->nb_frame_pix_fmts)
  3247. av_dict_set(&format_opts, "pixel_format", o->frame_pix_fmts[o->nb_frame_pix_fmts - 1].u.str, 0);
  3248. ic->video_codec_id = video_codec_name ?
  3249. find_codec_or_die(video_codec_name , AVMEDIA_TYPE_VIDEO , 0)->id : CODEC_ID_NONE;
  3250. ic->audio_codec_id = audio_codec_name ?
  3251. find_codec_or_die(audio_codec_name , AVMEDIA_TYPE_AUDIO , 0)->id : CODEC_ID_NONE;
  3252. ic->subtitle_codec_id= subtitle_codec_name ?
  3253. find_codec_or_die(subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, 0)->id : CODEC_ID_NONE;
  3254. ic->flags |= AVFMT_FLAG_NONBLOCK;
  3255. ic->interrupt_callback = int_cb;
  3256. if (loop_input) {
  3257. av_log(NULL, AV_LOG_WARNING,
  3258. "-loop_input is deprecated, use -loop 1\n"
  3259. "Note, both loop options only work with -f image2\n"
  3260. );
  3261. ic->loop_input = loop_input;
  3262. }
  3263. /* open the input file with generic avformat function */
  3264. err = avformat_open_input(&ic, filename, file_iformat, &format_opts);
  3265. if (err < 0) {
  3266. print_error(filename, err);
  3267. exit_program(1);
  3268. }
  3269. assert_avoptions(format_opts);
  3270. /* apply forced codec ids */
  3271. for (i = 0; i < ic->nb_streams; i++)
  3272. choose_decoder(o, ic, ic->streams[i]);
  3273. /* Set AVCodecContext options for avformat_find_stream_info */
  3274. opts = setup_find_stream_info_opts(ic, codec_opts);
  3275. orig_nb_streams = ic->nb_streams;
  3276. /* If not enough info to get the stream parameters, we decode the
  3277. first frames to get it. (used in mpeg case for example) */
  3278. ret = avformat_find_stream_info(ic, opts);
  3279. if (ret < 0) {
  3280. av_log(NULL, AV_LOG_FATAL, "%s: could not find codec parameters\n", filename);
  3281. avformat_close_input(&ic);
  3282. exit_program(1);
  3283. }
  3284. timestamp = o->start_time;
  3285. /* add the stream start time */
  3286. if (ic->start_time != AV_NOPTS_VALUE)
  3287. timestamp += ic->start_time;
  3288. /* if seeking requested, we execute it */
  3289. if (o->start_time != 0) {
  3290. ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
  3291. if (ret < 0) {
  3292. av_log(NULL, AV_LOG_WARNING, "%s: could not seek to position %0.3f\n",
  3293. filename, (double)timestamp / AV_TIME_BASE);
  3294. }
  3295. }
  3296. /* update the current parameters so that they match the one of the input stream */
  3297. add_input_streams(o, ic);
  3298. /* dump the file content */
  3299. av_dump_format(ic, nb_input_files, filename, 0);
  3300. input_files = grow_array(input_files, sizeof(*input_files), &nb_input_files, nb_input_files + 1);
  3301. input_files[nb_input_files - 1].ctx = ic;
  3302. input_files[nb_input_files - 1].ist_index = nb_input_streams - ic->nb_streams;
  3303. input_files[nb_input_files - 1].ts_offset = o->input_ts_offset - (copy_ts ? 0 : timestamp);
  3304. input_files[nb_input_files - 1].nb_streams = ic->nb_streams;
  3305. input_files[nb_input_files - 1].rate_emu = o->rate_emu;
  3306. for (i = 0; i < o->nb_dump_attachment; i++) {
  3307. int j;
  3308. for (j = 0; j < ic->nb_streams; j++) {
  3309. AVStream *st = ic->streams[j];
  3310. if (check_stream_specifier(ic, st, o->dump_attachment[i].specifier) == 1)
  3311. dump_attachment(st, o->dump_attachment[i].u.str);
  3312. }
  3313. }
  3314. for (i = 0; i < orig_nb_streams; i++)
  3315. av_dict_free(&opts[i]);
  3316. av_freep(&opts);
  3317. reset_options(o, 1);
  3318. return 0;
  3319. }
  3320. static void parse_forced_key_frames(char *kf, OutputStream *ost)
  3321. {
  3322. char *p;
  3323. int n = 1, i;
  3324. for (p = kf; *p; p++)
  3325. if (*p == ',')
  3326. n++;
  3327. ost->forced_kf_count = n;
  3328. ost->forced_kf_pts = av_malloc(sizeof(*ost->forced_kf_pts) * n);
  3329. if (!ost->forced_kf_pts) {
  3330. av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
  3331. exit_program(1);
  3332. }
  3333. for (i = 0; i < n; i++) {
  3334. p = i ? strchr(p, ',') + 1 : kf;
  3335. ost->forced_kf_pts[i] = parse_time_or_die("force_key_frames", p, 1);
  3336. }
  3337. }
  3338. static uint8_t *get_line(AVIOContext *s)
  3339. {
  3340. AVIOContext *line;
  3341. uint8_t *buf;
  3342. char c;
  3343. if (avio_open_dyn_buf(&line) < 0) {
  3344. av_log(NULL, AV_LOG_FATAL, "Could not alloc buffer for reading preset.\n");
  3345. exit_program(1);
  3346. }
  3347. while ((c = avio_r8(s)) && c != '\n')
  3348. avio_w8(line, c);
  3349. avio_w8(line, 0);
  3350. avio_close_dyn_buf(line, &buf);
  3351. return buf;
  3352. }
  3353. static int get_preset_file_2(const char *preset_name, const char *codec_name, AVIOContext **s)
  3354. {
  3355. int i, ret = 1;
  3356. char filename[1000];
  3357. const char *base[3] = { getenv("AVCONV_DATADIR"),
  3358. getenv("HOME"),
  3359. AVCONV_DATADIR,
  3360. };
  3361. for (i = 0; i < FF_ARRAY_ELEMS(base) && ret; i++) {
  3362. if (!base[i])
  3363. continue;
  3364. if (codec_name) {
  3365. snprintf(filename, sizeof(filename), "%s%s/%s-%s.avpreset", base[i],
  3366. i != 1 ? "" : "/.avconv", codec_name, preset_name);
  3367. ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
  3368. }
  3369. if (ret) {
  3370. snprintf(filename, sizeof(filename), "%s%s/%s.avpreset", base[i],
  3371. i != 1 ? "" : "/.avconv", preset_name);
  3372. ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
  3373. }
  3374. }
  3375. return ret;
  3376. }
  3377. static void choose_encoder(OptionsContext *o, AVFormatContext *s, OutputStream *ost)
  3378. {
  3379. char *codec_name = NULL;
  3380. MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, ost->st);
  3381. if (!codec_name) {
  3382. ost->st->codec->codec_id = av_guess_codec(s->oformat, NULL, s->filename,
  3383. NULL, ost->st->codec->codec_type);
  3384. ost->enc = avcodec_find_encoder(ost->st->codec->codec_id);
  3385. } else if (!strcmp(codec_name, "copy"))
  3386. ost->stream_copy = 1;
  3387. else {
  3388. ost->enc = find_codec_or_die(codec_name, ost->st->codec->codec_type, 1);
  3389. ost->st->codec->codec_id = ost->enc->id;
  3390. }
  3391. }
  3392. static OutputStream *new_output_stream(OptionsContext *o, AVFormatContext *oc, enum AVMediaType type)
  3393. {
  3394. OutputStream *ost;
  3395. AVStream *st = avformat_new_stream(oc, NULL);
  3396. int idx = oc->nb_streams - 1, ret = 0;
  3397. char *bsf = NULL, *next, *codec_tag = NULL;
  3398. AVBitStreamFilterContext *bsfc, *bsfc_prev = NULL;
  3399. double qscale = -1;
  3400. char *buf = NULL, *arg = NULL, *preset = NULL;
  3401. AVIOContext *s = NULL;
  3402. if (!st) {
  3403. av_log(NULL, AV_LOG_FATAL, "Could not alloc stream.\n");
  3404. exit_program(1);
  3405. }
  3406. if (oc->nb_streams - 1 < o->nb_streamid_map)
  3407. st->id = o->streamid_map[oc->nb_streams - 1];
  3408. output_streams = grow_array(output_streams, sizeof(*output_streams), &nb_output_streams,
  3409. nb_output_streams + 1);
  3410. ost = &output_streams[nb_output_streams - 1];
  3411. ost->file_index = nb_output_files;
  3412. ost->index = idx;
  3413. ost->st = st;
  3414. st->codec->codec_type = type;
  3415. choose_encoder(o, oc, ost);
  3416. if (ost->enc) {
  3417. ost->opts = filter_codec_opts(codec_opts, ost->enc, oc, st);
  3418. }
  3419. avcodec_get_context_defaults3(st->codec, ost->enc);
  3420. st->codec->codec_type = type; // XXX hack, avcodec_get_context_defaults2() sets type to unknown for stream copy
  3421. MATCH_PER_STREAM_OPT(presets, str, preset, oc, st);
  3422. if (preset && (!(ret = get_preset_file_2(preset, ost->enc->name, &s)))) {
  3423. do {
  3424. buf = get_line(s);
  3425. if (!buf[0] || buf[0] == '#') {
  3426. av_free(buf);
  3427. continue;
  3428. }
  3429. if (!(arg = strchr(buf, '='))) {
  3430. av_log(NULL, AV_LOG_FATAL, "Invalid line found in the preset file.\n");
  3431. exit_program(1);
  3432. }
  3433. *arg++ = 0;
  3434. av_dict_set(&ost->opts, buf, arg, AV_DICT_DONT_OVERWRITE);
  3435. av_free(buf);
  3436. } while (!s->eof_reached);
  3437. avio_close(s);
  3438. }
  3439. if (ret) {
  3440. av_log(NULL, AV_LOG_FATAL,
  3441. "Preset %s specified for stream %d:%d, but could not be opened.\n",
  3442. preset, ost->file_index, ost->index);
  3443. exit_program(1);
  3444. }
  3445. ost->max_frames = INT64_MAX;
  3446. MATCH_PER_STREAM_OPT(max_frames, i64, ost->max_frames, oc, st);
  3447. MATCH_PER_STREAM_OPT(bitstream_filters, str, bsf, oc, st);
  3448. while (bsf) {
  3449. if (next = strchr(bsf, ','))
  3450. *next++ = 0;
  3451. if (!(bsfc = av_bitstream_filter_init(bsf))) {
  3452. av_log(NULL, AV_LOG_FATAL, "Unknown bitstream filter %s\n", bsf);
  3453. exit_program(1);
  3454. }
  3455. if (bsfc_prev)
  3456. bsfc_prev->next = bsfc;
  3457. else
  3458. ost->bitstream_filters = bsfc;
  3459. bsfc_prev = bsfc;
  3460. bsf = next;
  3461. }
  3462. MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, oc, st);
  3463. if (codec_tag) {
  3464. uint32_t tag = strtol(codec_tag, &next, 0);
  3465. if (*next)
  3466. tag = AV_RL32(codec_tag);
  3467. st->codec->codec_tag = tag;
  3468. }
  3469. MATCH_PER_STREAM_OPT(qscale, dbl, qscale, oc, st);
  3470. if (qscale >= 0 || same_quant) {
  3471. st->codec->flags |= CODEC_FLAG_QSCALE;
  3472. st->codec->global_quality = FF_QP2LAMBDA * qscale;
  3473. }
  3474. if (oc->oformat->flags & AVFMT_GLOBALHEADER)
  3475. st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
  3476. av_opt_get_int(sws_opts, "sws_flags", 0, &ost->sws_flags);
  3477. return ost;
  3478. }
  3479. static void parse_matrix_coeffs(uint16_t *dest, const char *str)
  3480. {
  3481. int i;
  3482. const char *p = str;
  3483. for (i = 0;; i++) {
  3484. dest[i] = atoi(p);
  3485. if (i == 63)
  3486. break;
  3487. p = strchr(p, ',');
  3488. if (!p) {
  3489. av_log(NULL, AV_LOG_FATAL, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
  3490. exit_program(1);
  3491. }
  3492. p++;
  3493. }
  3494. }
  3495. static OutputStream *new_video_stream(OptionsContext *o, AVFormatContext *oc)
  3496. {
  3497. AVStream *st;
  3498. OutputStream *ost;
  3499. AVCodecContext *video_enc;
  3500. ost = new_output_stream(o, oc, AVMEDIA_TYPE_VIDEO);
  3501. st = ost->st;
  3502. video_enc = st->codec;
  3503. if (!ost->stream_copy) {
  3504. const char *p = NULL;
  3505. char *forced_key_frames = NULL, *frame_rate = NULL, *frame_size = NULL;
  3506. char *frame_aspect_ratio = NULL, *frame_pix_fmt = NULL;
  3507. char *intra_matrix = NULL, *inter_matrix = NULL, *filters = NULL;
  3508. int i;
  3509. MATCH_PER_STREAM_OPT(frame_rates, str, frame_rate, oc, st);
  3510. if (frame_rate && av_parse_video_rate(&ost->frame_rate, frame_rate) < 0) {
  3511. av_log(NULL, AV_LOG_FATAL, "Invalid framerate value: %s\n", frame_rate);
  3512. exit_program(1);
  3513. }
  3514. MATCH_PER_STREAM_OPT(frame_sizes, str, frame_size, oc, st);
  3515. if (frame_size && av_parse_video_size(&video_enc->width, &video_enc->height, frame_size) < 0) {
  3516. av_log(NULL, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
  3517. exit_program(1);
  3518. }
  3519. MATCH_PER_STREAM_OPT(frame_aspect_ratios, str, frame_aspect_ratio, oc, st);
  3520. if (frame_aspect_ratio)
  3521. ost->frame_aspect_ratio = parse_frame_aspect_ratio(frame_aspect_ratio);
  3522. video_enc->bits_per_raw_sample = frame_bits_per_raw_sample;
  3523. MATCH_PER_STREAM_OPT(frame_pix_fmts, str, frame_pix_fmt, oc, st);
  3524. if (frame_pix_fmt && (video_enc->pix_fmt = av_get_pix_fmt(frame_pix_fmt)) == PIX_FMT_NONE) {
  3525. av_log(NULL, AV_LOG_FATAL, "Unknown pixel format requested: %s.\n", frame_pix_fmt);
  3526. exit_program(1);
  3527. }
  3528. st->sample_aspect_ratio = video_enc->sample_aspect_ratio;
  3529. if (intra_only)
  3530. video_enc->gop_size = 0;
  3531. MATCH_PER_STREAM_OPT(intra_matrices, str, intra_matrix, oc, st);
  3532. if (intra_matrix) {
  3533. if (!(video_enc->intra_matrix = av_mallocz(sizeof(*video_enc->intra_matrix) * 64))) {
  3534. av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for intra matrix.\n");
  3535. exit_program(1);
  3536. }
  3537. parse_matrix_coeffs(video_enc->intra_matrix, intra_matrix);
  3538. }
  3539. MATCH_PER_STREAM_OPT(inter_matrices, str, inter_matrix, oc, st);
  3540. if (inter_matrix) {
  3541. if (!(video_enc->inter_matrix = av_mallocz(sizeof(*video_enc->inter_matrix) * 64))) {
  3542. av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for inter matrix.\n");
  3543. exit_program(1);
  3544. }
  3545. parse_matrix_coeffs(video_enc->inter_matrix, inter_matrix);
  3546. }
  3547. MATCH_PER_STREAM_OPT(rc_overrides, str, p, oc, st);
  3548. for (i = 0; p; i++) {
  3549. int start, end, q;
  3550. int e = sscanf(p, "%d,%d,%d", &start, &end, &q);
  3551. if (e != 3) {
  3552. av_log(NULL, AV_LOG_FATAL, "error parsing rc_override\n");
  3553. exit_program(1);
  3554. }
  3555. /* FIXME realloc failure */
  3556. video_enc->rc_override =
  3557. av_realloc(video_enc->rc_override,
  3558. sizeof(RcOverride) * (i + 1));
  3559. video_enc->rc_override[i].start_frame = start;
  3560. video_enc->rc_override[i].end_frame = end;
  3561. if (q > 0) {
  3562. video_enc->rc_override[i].qscale = q;
  3563. video_enc->rc_override[i].quality_factor = 1.0;
  3564. }
  3565. else {
  3566. video_enc->rc_override[i].qscale = 0;
  3567. video_enc->rc_override[i].quality_factor = -q/100.0;
  3568. }
  3569. p = strchr(p, '/');
  3570. if (p) p++;
  3571. }
  3572. video_enc->rc_override_count = i;
  3573. video_enc->intra_dc_precision = intra_dc_precision - 8;
  3574. if (do_psnr)
  3575. video_enc->flags|= CODEC_FLAG_PSNR;
  3576. /* two pass mode */
  3577. if (do_pass) {
  3578. if (do_pass & 1) {
  3579. video_enc->flags |= CODEC_FLAG_PASS1;
  3580. av_dict_set(&ost->opts, "flags", "+pass1", AV_DICT_APPEND);
  3581. }
  3582. if (do_pass & 2) {
  3583. video_enc->flags |= CODEC_FLAG_PASS2;
  3584. av_dict_set(&ost->opts, "flags", "+pass2", AV_DICT_APPEND);
  3585. }
  3586. }
  3587. MATCH_PER_STREAM_OPT(forced_key_frames, str, forced_key_frames, oc, st);
  3588. if (forced_key_frames)
  3589. parse_forced_key_frames(forced_key_frames, ost);
  3590. MATCH_PER_STREAM_OPT(force_fps, i, ost->force_fps, oc, st);
  3591. ost->top_field_first = -1;
  3592. MATCH_PER_STREAM_OPT(top_field_first, i, ost->top_field_first, oc, st);
  3593. #if CONFIG_AVFILTER
  3594. MATCH_PER_STREAM_OPT(filters, str, filters, oc, st);
  3595. if (filters)
  3596. ost->avfilter = av_strdup(filters);
  3597. #endif
  3598. } else {
  3599. MATCH_PER_STREAM_OPT(copy_initial_nonkeyframes, i, ost->copy_initial_nonkeyframes, oc ,st);
  3600. }
  3601. return ost;
  3602. }
  3603. static OutputStream *new_audio_stream(OptionsContext *o, AVFormatContext *oc)
  3604. {
  3605. int n;
  3606. AVStream *st;
  3607. OutputStream *ost;
  3608. AVCodecContext *audio_enc;
  3609. ost = new_output_stream(o, oc, AVMEDIA_TYPE_AUDIO);
  3610. st = ost->st;
  3611. audio_enc = st->codec;
  3612. audio_enc->codec_type = AVMEDIA_TYPE_AUDIO;
  3613. if (!ost->stream_copy) {
  3614. char *sample_fmt = NULL;
  3615. MATCH_PER_STREAM_OPT(audio_channels, i, audio_enc->channels, oc, st);
  3616. MATCH_PER_STREAM_OPT(sample_fmts, str, sample_fmt, oc, st);
  3617. if (sample_fmt &&
  3618. (audio_enc->sample_fmt = av_get_sample_fmt(sample_fmt)) == AV_SAMPLE_FMT_NONE) {
  3619. av_log(NULL, AV_LOG_FATAL, "Invalid sample format '%s'\n", sample_fmt);
  3620. exit_program(1);
  3621. }
  3622. MATCH_PER_STREAM_OPT(audio_sample_rate, i, audio_enc->sample_rate, oc, st);
  3623. ost->rematrix_volume=1.0;
  3624. MATCH_PER_STREAM_OPT(rematrix_volume, f, ost->rematrix_volume, oc, st);
  3625. }
  3626. /* check for channel mapping for this audio stream */
  3627. for (n = 0; n < o->nb_audio_channel_maps; n++) {
  3628. AudioChannelMap *map = &o->audio_channel_maps[n];
  3629. InputStream *ist = &input_streams[ost->source_index];
  3630. if ((map->channel_idx == -1 || (ist->file_index == map->file_idx && ist->st->index == map->stream_idx)) &&
  3631. (map->ofile_idx == -1 || ost->file_index == map->ofile_idx) &&
  3632. (map->ostream_idx == -1 || ost->st->index == map->ostream_idx)) {
  3633. if (ost->audio_channels_mapped < FF_ARRAY_ELEMS(ost->audio_channels_map))
  3634. ost->audio_channels_map[ost->audio_channels_mapped++] = map->channel_idx;
  3635. else
  3636. av_log(NULL, AV_LOG_FATAL, "Max channel mapping for output %d.%d reached\n",
  3637. ost->file_index, ost->st->index);
  3638. }
  3639. }
  3640. return ost;
  3641. }
  3642. static OutputStream *new_data_stream(OptionsContext *o, AVFormatContext *oc)
  3643. {
  3644. OutputStream *ost;
  3645. ost = new_output_stream(o, oc, AVMEDIA_TYPE_DATA);
  3646. if (!ost->stream_copy) {
  3647. av_log(NULL, AV_LOG_FATAL, "Data stream encoding not supported yet (only streamcopy)\n");
  3648. exit_program(1);
  3649. }
  3650. return ost;
  3651. }
  3652. static OutputStream *new_attachment_stream(OptionsContext *o, AVFormatContext *oc)
  3653. {
  3654. OutputStream *ost = new_output_stream(o, oc, AVMEDIA_TYPE_ATTACHMENT);
  3655. ost->stream_copy = 1;
  3656. return ost;
  3657. }
  3658. static OutputStream *new_subtitle_stream(OptionsContext *o, AVFormatContext *oc)
  3659. {
  3660. AVStream *st;
  3661. OutputStream *ost;
  3662. AVCodecContext *subtitle_enc;
  3663. ost = new_output_stream(o, oc, AVMEDIA_TYPE_SUBTITLE);
  3664. st = ost->st;
  3665. subtitle_enc = st->codec;
  3666. subtitle_enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
  3667. return ost;
  3668. }
  3669. /* arg format is "output-stream-index:streamid-value". */
  3670. static int opt_streamid(OptionsContext *o, const char *opt, const char *arg)
  3671. {
  3672. int idx;
  3673. char *p;
  3674. char idx_str[16];
  3675. av_strlcpy(idx_str, arg, sizeof(idx_str));
  3676. p = strchr(idx_str, ':');
  3677. if (!p) {
  3678. av_log(NULL, AV_LOG_FATAL,
  3679. "Invalid value '%s' for option '%s', required syntax is 'index:value'\n",
  3680. arg, opt);
  3681. exit_program(1);
  3682. }
  3683. *p++ = '\0';
  3684. idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, MAX_STREAMS-1);
  3685. o->streamid_map = grow_array(o->streamid_map, sizeof(*o->streamid_map), &o->nb_streamid_map, idx+1);
  3686. o->streamid_map[idx] = parse_number_or_die(opt, p, OPT_INT, 0, INT_MAX);
  3687. return 0;
  3688. }
  3689. static int copy_chapters(InputFile *ifile, OutputFile *ofile, int copy_metadata)
  3690. {
  3691. AVFormatContext *is = ifile->ctx;
  3692. AVFormatContext *os = ofile->ctx;
  3693. int i;
  3694. for (i = 0; i < is->nb_chapters; i++) {
  3695. AVChapter *in_ch = is->chapters[i], *out_ch;
  3696. int64_t ts_off = av_rescale_q(ofile->start_time - ifile->ts_offset,
  3697. AV_TIME_BASE_Q, in_ch->time_base);
  3698. int64_t rt = (ofile->recording_time == INT64_MAX) ? INT64_MAX :
  3699. av_rescale_q(ofile->recording_time, AV_TIME_BASE_Q, in_ch->time_base);
  3700. if (in_ch->end < ts_off)
  3701. continue;
  3702. if (rt != INT64_MAX && in_ch->start > rt + ts_off)
  3703. break;
  3704. out_ch = av_mallocz(sizeof(AVChapter));
  3705. if (!out_ch)
  3706. return AVERROR(ENOMEM);
  3707. out_ch->id = in_ch->id;
  3708. out_ch->time_base = in_ch->time_base;
  3709. out_ch->start = FFMAX(0, in_ch->start - ts_off);
  3710. out_ch->end = FFMIN(rt, in_ch->end - ts_off);
  3711. if (copy_metadata)
  3712. av_dict_copy(&out_ch->metadata, in_ch->metadata, 0);
  3713. os->nb_chapters++;
  3714. os->chapters = av_realloc_f(os->chapters, os->nb_chapters, sizeof(AVChapter));
  3715. if (!os->chapters)
  3716. return AVERROR(ENOMEM);
  3717. os->chapters[os->nb_chapters - 1] = out_ch;
  3718. }
  3719. return 0;
  3720. }
  3721. static int read_ffserver_streams(OptionsContext *o, AVFormatContext *s, const char *filename)
  3722. {
  3723. int i, err;
  3724. AVFormatContext *ic = avformat_alloc_context();
  3725. ic->interrupt_callback = int_cb;
  3726. err = avformat_open_input(&ic, filename, NULL, NULL);
  3727. if (err < 0)
  3728. return err;
  3729. /* copy stream format */
  3730. for(i=0;i<ic->nb_streams;i++) {
  3731. AVStream *st;
  3732. OutputStream *ost;
  3733. AVCodec *codec;
  3734. AVCodecContext *avctx;
  3735. codec = avcodec_find_encoder(ic->streams[i]->codec->codec_id);
  3736. ost = new_output_stream(o, s, codec->type);
  3737. st = ost->st;
  3738. avctx = st->codec;
  3739. ost->enc = codec;
  3740. // FIXME: a more elegant solution is needed
  3741. memcpy(st, ic->streams[i], sizeof(AVStream));
  3742. st->info = av_malloc(sizeof(*st->info));
  3743. memcpy(st->info, ic->streams[i]->info, sizeof(*st->info));
  3744. st->codec= avctx;
  3745. avcodec_copy_context(st->codec, ic->streams[i]->codec);
  3746. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && !ost->stream_copy)
  3747. choose_sample_fmt(st, codec);
  3748. else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && !ost->stream_copy)
  3749. choose_pixel_fmt(st, codec);
  3750. }
  3751. avformat_close_input(&ic);
  3752. return 0;
  3753. }
  3754. static void opt_output_file(void *optctx, const char *filename)
  3755. {
  3756. OptionsContext *o = optctx;
  3757. AVFormatContext *oc;
  3758. int i, err;
  3759. AVOutputFormat *file_oformat;
  3760. OutputStream *ost;
  3761. InputStream *ist;
  3762. if (!strcmp(filename, "-"))
  3763. filename = "pipe:";
  3764. err = avformat_alloc_output_context2(&oc, NULL, o->format, filename);
  3765. if (!oc) {
  3766. print_error(filename, err);
  3767. exit_program(1);
  3768. }
  3769. file_oformat= oc->oformat;
  3770. oc->interrupt_callback = int_cb;
  3771. if (!strcmp(file_oformat->name, "ffm") &&
  3772. av_strstart(filename, "http:", NULL)) {
  3773. int j;
  3774. /* special case for files sent to ffserver: we get the stream
  3775. parameters from ffserver */
  3776. int err = read_ffserver_streams(o, oc, filename);
  3777. if (err < 0) {
  3778. print_error(filename, err);
  3779. exit_program(1);
  3780. }
  3781. for(j = nb_output_streams - oc->nb_streams; j < nb_output_streams; j++) {
  3782. ost = &output_streams[j];
  3783. for (i = 0; i < nb_input_streams; i++) {
  3784. ist = &input_streams[i];
  3785. if(ist->st->codec->codec_type == ost->st->codec->codec_type){
  3786. ost->sync_ist= ist;
  3787. ost->source_index= i;
  3788. ist->discard = 0;
  3789. break;
  3790. }
  3791. }
  3792. if(!ost->sync_ist){
  3793. av_log(NULL, AV_LOG_FATAL, "Missing %s stream which is required by this ffm\n", av_get_media_type_string(ost->st->codec->codec_type));
  3794. exit_program(1);
  3795. }
  3796. }
  3797. } else if (!o->nb_stream_maps) {
  3798. /* pick the "best" stream of each type */
  3799. #define NEW_STREAM(type, index)\
  3800. if (index >= 0) {\
  3801. ost = new_ ## type ## _stream(o, oc);\
  3802. ost->source_index = index;\
  3803. ost->sync_ist = &input_streams[index];\
  3804. input_streams[index].discard = 0;\
  3805. }
  3806. /* video: highest resolution */
  3807. if (!o->video_disable && oc->oformat->video_codec != CODEC_ID_NONE) {
  3808. int area = 0, idx = -1;
  3809. for (i = 0; i < nb_input_streams; i++) {
  3810. ist = &input_streams[i];
  3811. if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
  3812. ist->st->codec->width * ist->st->codec->height > area) {
  3813. area = ist->st->codec->width * ist->st->codec->height;
  3814. idx = i;
  3815. }
  3816. }
  3817. NEW_STREAM(video, idx);
  3818. }
  3819. /* audio: most channels */
  3820. if (!o->audio_disable && oc->oformat->audio_codec != CODEC_ID_NONE) {
  3821. int channels = 0, idx = -1;
  3822. for (i = 0; i < nb_input_streams; i++) {
  3823. ist = &input_streams[i];
  3824. if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
  3825. ist->st->codec->channels > channels) {
  3826. channels = ist->st->codec->channels;
  3827. idx = i;
  3828. }
  3829. }
  3830. NEW_STREAM(audio, idx);
  3831. }
  3832. /* subtitles: pick first */
  3833. if (!o->subtitle_disable && (oc->oformat->subtitle_codec != CODEC_ID_NONE || subtitle_codec_name)) {
  3834. for (i = 0; i < nb_input_streams; i++)
  3835. if (input_streams[i].st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  3836. NEW_STREAM(subtitle, i);
  3837. break;
  3838. }
  3839. }
  3840. /* do something with data? */
  3841. } else {
  3842. for (i = 0; i < o->nb_stream_maps; i++) {
  3843. StreamMap *map = &o->stream_maps[i];
  3844. if (map->disabled)
  3845. continue;
  3846. ist = &input_streams[input_files[map->file_index].ist_index + map->stream_index];
  3847. if(o->subtitle_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
  3848. continue;
  3849. if(o-> audio_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
  3850. continue;
  3851. if(o-> video_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
  3852. continue;
  3853. if(o-> data_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_DATA)
  3854. continue;
  3855. switch (ist->st->codec->codec_type) {
  3856. case AVMEDIA_TYPE_VIDEO: ost = new_video_stream(o, oc); break;
  3857. case AVMEDIA_TYPE_AUDIO: ost = new_audio_stream(o, oc); break;
  3858. case AVMEDIA_TYPE_SUBTITLE: ost = new_subtitle_stream(o, oc); break;
  3859. case AVMEDIA_TYPE_DATA: ost = new_data_stream(o, oc); break;
  3860. case AVMEDIA_TYPE_ATTACHMENT: ost = new_attachment_stream(o, oc); break;
  3861. default:
  3862. av_log(NULL, AV_LOG_FATAL, "Cannot map stream #%d:%d - unsupported type.\n",
  3863. map->file_index, map->stream_index);
  3864. exit_program(1);
  3865. }
  3866. ost->source_index = input_files[map->file_index].ist_index + map->stream_index;
  3867. ost->sync_ist = &input_streams[input_files[map->sync_file_index].ist_index +
  3868. map->sync_stream_index];
  3869. ist->discard = 0;
  3870. }
  3871. }
  3872. /* handle attached files */
  3873. for (i = 0; i < o->nb_attachments; i++) {
  3874. AVIOContext *pb;
  3875. uint8_t *attachment;
  3876. const char *p;
  3877. int64_t len;
  3878. if ((err = avio_open2(&pb, o->attachments[i], AVIO_FLAG_READ, &int_cb, NULL)) < 0) {
  3879. av_log(NULL, AV_LOG_FATAL, "Could not open attachment file %s.\n",
  3880. o->attachments[i]);
  3881. exit_program(1);
  3882. }
  3883. if ((len = avio_size(pb)) <= 0) {
  3884. av_log(NULL, AV_LOG_FATAL, "Could not get size of the attachment %s.\n",
  3885. o->attachments[i]);
  3886. exit_program(1);
  3887. }
  3888. if (!(attachment = av_malloc(len))) {
  3889. av_log(NULL, AV_LOG_FATAL, "Attachment %s too large to fit into memory.\n",
  3890. o->attachments[i]);
  3891. exit_program(1);
  3892. }
  3893. avio_read(pb, attachment, len);
  3894. ost = new_attachment_stream(o, oc);
  3895. ost->stream_copy = 0;
  3896. ost->source_index = -1;
  3897. ost->attachment_filename = o->attachments[i];
  3898. ost->st->codec->extradata = attachment;
  3899. ost->st->codec->extradata_size = len;
  3900. p = strrchr(o->attachments[i], '/');
  3901. av_dict_set(&ost->st->metadata, "filename", (p && *p) ? p + 1 : o->attachments[i], AV_DICT_DONT_OVERWRITE);
  3902. avio_close(pb);
  3903. }
  3904. output_files = grow_array(output_files, sizeof(*output_files), &nb_output_files, nb_output_files + 1);
  3905. output_files[nb_output_files - 1].ctx = oc;
  3906. output_files[nb_output_files - 1].ost_index = nb_output_streams - oc->nb_streams;
  3907. output_files[nb_output_files - 1].recording_time = o->recording_time;
  3908. output_files[nb_output_files - 1].start_time = o->start_time;
  3909. output_files[nb_output_files - 1].limit_filesize = o->limit_filesize;
  3910. av_dict_copy(&output_files[nb_output_files - 1].opts, format_opts, 0);
  3911. /* check filename in case of an image number is expected */
  3912. if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
  3913. if (!av_filename_number_test(oc->filename)) {
  3914. print_error(oc->filename, AVERROR(EINVAL));
  3915. exit_program(1);
  3916. }
  3917. }
  3918. if (!(oc->oformat->flags & AVFMT_NOFILE)) {
  3919. /* test if it already exists to avoid losing precious files */
  3920. assert_file_overwrite(filename);
  3921. /* open the file */
  3922. if ((err = avio_open2(&oc->pb, filename, AVIO_FLAG_WRITE,
  3923. &oc->interrupt_callback,
  3924. &output_files[nb_output_files - 1].opts)) < 0) {
  3925. print_error(filename, err);
  3926. exit_program(1);
  3927. }
  3928. }
  3929. if (o->mux_preload) {
  3930. uint8_t buf[64];
  3931. snprintf(buf, sizeof(buf), "%d", (int)(o->mux_preload*AV_TIME_BASE));
  3932. av_dict_set(&output_files[nb_output_files - 1].opts, "preload", buf, 0);
  3933. }
  3934. oc->max_delay = (int)(o->mux_max_delay * AV_TIME_BASE);
  3935. if (loop_output >= 0) {
  3936. av_log(NULL, AV_LOG_WARNING, "-loop_output is deprecated, use -loop\n");
  3937. oc->loop_output = loop_output;
  3938. }
  3939. /* copy metadata */
  3940. for (i = 0; i < o->nb_metadata_map; i++) {
  3941. char *p;
  3942. int in_file_index = strtol(o->metadata_map[i].u.str, &p, 0);
  3943. if (in_file_index < 0)
  3944. continue;
  3945. if (in_file_index >= nb_input_files) {
  3946. av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d while processing metadata maps\n", in_file_index);
  3947. exit_program(1);
  3948. }
  3949. copy_metadata(o->metadata_map[i].specifier, *p ? p + 1 : p, oc, input_files[in_file_index].ctx, o);
  3950. }
  3951. /* copy chapters */
  3952. if (o->chapters_input_file >= nb_input_files) {
  3953. if (o->chapters_input_file == INT_MAX) {
  3954. /* copy chapters from the first input file that has them*/
  3955. o->chapters_input_file = -1;
  3956. for (i = 0; i < nb_input_files; i++)
  3957. if (input_files[i].ctx->nb_chapters) {
  3958. o->chapters_input_file = i;
  3959. break;
  3960. }
  3961. } else {
  3962. av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d in chapter mapping.\n",
  3963. o->chapters_input_file);
  3964. exit_program(1);
  3965. }
  3966. }
  3967. if (o->chapters_input_file >= 0)
  3968. copy_chapters(&input_files[o->chapters_input_file], &output_files[nb_output_files - 1],
  3969. !o->metadata_chapters_manual);
  3970. /* copy global metadata by default */
  3971. if (!o->metadata_global_manual && nb_input_files){
  3972. av_dict_copy(&oc->metadata, input_files[0].ctx->metadata,
  3973. AV_DICT_DONT_OVERWRITE);
  3974. if(o->recording_time != INT64_MAX)
  3975. av_dict_set(&oc->metadata, "duration", NULL, 0);
  3976. }
  3977. if (!o->metadata_streams_manual)
  3978. for (i = output_files[nb_output_files - 1].ost_index; i < nb_output_streams; i++) {
  3979. InputStream *ist;
  3980. if (output_streams[i].source_index < 0) /* this is true e.g. for attached files */
  3981. continue;
  3982. ist = &input_streams[output_streams[i].source_index];
  3983. av_dict_copy(&output_streams[i].st->metadata, ist->st->metadata, AV_DICT_DONT_OVERWRITE);
  3984. }
  3985. /* process manually set metadata */
  3986. for (i = 0; i < o->nb_metadata; i++) {
  3987. AVDictionary **m;
  3988. char type, *val;
  3989. const char *stream_spec;
  3990. int index = 0, j, ret = 0;
  3991. val = strchr(o->metadata[i].u.str, '=');
  3992. if (!val) {
  3993. av_log(NULL, AV_LOG_FATAL, "No '=' character in metadata string %s.\n",
  3994. o->metadata[i].u.str);
  3995. exit_program(1);
  3996. }
  3997. *val++ = 0;
  3998. parse_meta_type(o->metadata[i].specifier, &type, &index, &stream_spec);
  3999. if (type == 's') {
  4000. for (j = 0; j < oc->nb_streams; j++) {
  4001. if ((ret = check_stream_specifier(oc, oc->streams[j], stream_spec)) > 0) {
  4002. av_dict_set(&oc->streams[j]->metadata, o->metadata[i].u.str, *val ? val : NULL, 0);
  4003. } else if (ret < 0)
  4004. exit_program(1);
  4005. }
  4006. printf("ret %d, stream_spec %s\n", ret, stream_spec);
  4007. }
  4008. else {
  4009. switch (type) {
  4010. case 'g':
  4011. m = &oc->metadata;
  4012. break;
  4013. case 'c':
  4014. if (index < 0 || index >= oc->nb_chapters) {
  4015. av_log(NULL, AV_LOG_FATAL, "Invalid chapter index %d in metadata specifier.\n", index);
  4016. exit_program(1);
  4017. }
  4018. m = &oc->chapters[index]->metadata;
  4019. break;
  4020. default:
  4021. av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", o->metadata[i].specifier);
  4022. exit_program(1);
  4023. }
  4024. av_dict_set(m, o->metadata[i].u.str, *val ? val : NULL, 0);
  4025. }
  4026. }
  4027. reset_options(o, 0);
  4028. }
  4029. /* same option as mencoder */
  4030. static int opt_pass(const char *opt, const char *arg)
  4031. {
  4032. do_pass = parse_number_or_die(opt, arg, OPT_INT, 1, 3);
  4033. return 0;
  4034. }
  4035. static int64_t getutime(void)
  4036. {
  4037. #if HAVE_GETRUSAGE
  4038. struct rusage rusage;
  4039. getrusage(RUSAGE_SELF, &rusage);
  4040. return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
  4041. #elif HAVE_GETPROCESSTIMES
  4042. HANDLE proc;
  4043. FILETIME c, e, k, u;
  4044. proc = GetCurrentProcess();
  4045. GetProcessTimes(proc, &c, &e, &k, &u);
  4046. return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
  4047. #else
  4048. return av_gettime();
  4049. #endif
  4050. }
  4051. static int64_t getmaxrss(void)
  4052. {
  4053. #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
  4054. struct rusage rusage;
  4055. getrusage(RUSAGE_SELF, &rusage);
  4056. return (int64_t)rusage.ru_maxrss * 1024;
  4057. #elif HAVE_GETPROCESSMEMORYINFO
  4058. HANDLE proc;
  4059. PROCESS_MEMORY_COUNTERS memcounters;
  4060. proc = GetCurrentProcess();
  4061. memcounters.cb = sizeof(memcounters);
  4062. GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
  4063. return memcounters.PeakPagefileUsage;
  4064. #else
  4065. return 0;
  4066. #endif
  4067. }
  4068. static int opt_audio_qscale(OptionsContext *o, const char *opt, const char *arg)
  4069. {
  4070. return parse_option(o, "q:a", arg, options);
  4071. }
  4072. static void show_usage(void)
  4073. {
  4074. av_log(NULL, AV_LOG_INFO, "Hyper fast Audio and Video encoder\n");
  4075. av_log(NULL, AV_LOG_INFO, "usage: %s [options] [[infile options] -i infile]... {[outfile options] outfile}...\n", program_name);
  4076. av_log(NULL, AV_LOG_INFO, "\n");
  4077. }
  4078. static int opt_help(const char *opt, const char *arg)
  4079. {
  4080. int flags = AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_ENCODING_PARAM;
  4081. av_log_set_callback(log_callback_help);
  4082. show_usage();
  4083. show_help_options(options, "Main options:\n",
  4084. OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB, 0);
  4085. show_help_options(options, "\nAdvanced options:\n",
  4086. OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB,
  4087. OPT_EXPERT);
  4088. show_help_options(options, "\nVideo options:\n",
  4089. OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
  4090. OPT_VIDEO);
  4091. show_help_options(options, "\nAdvanced Video options:\n",
  4092. OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
  4093. OPT_VIDEO | OPT_EXPERT);
  4094. show_help_options(options, "\nAudio options:\n",
  4095. OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
  4096. OPT_AUDIO);
  4097. show_help_options(options, "\nAdvanced Audio options:\n",
  4098. OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
  4099. OPT_AUDIO | OPT_EXPERT);
  4100. show_help_options(options, "\nSubtitle options:\n",
  4101. OPT_SUBTITLE | OPT_GRAB,
  4102. OPT_SUBTITLE);
  4103. show_help_options(options, "\nAudio/Video grab options:\n",
  4104. OPT_GRAB,
  4105. OPT_GRAB);
  4106. printf("\n");
  4107. show_help_children(avcodec_get_class(), flags);
  4108. show_help_children(avformat_get_class(), flags);
  4109. show_help_children(sws_get_class(), flags);
  4110. return 0;
  4111. }
  4112. static int opt_target(OptionsContext *o, const char *opt, const char *arg)
  4113. {
  4114. enum { PAL, NTSC, FILM, UNKNOWN } norm = UNKNOWN;
  4115. static const char *const frame_rates[] = { "25", "30000/1001", "24000/1001" };
  4116. if (!strncmp(arg, "pal-", 4)) {
  4117. norm = PAL;
  4118. arg += 4;
  4119. } else if (!strncmp(arg, "ntsc-", 5)) {
  4120. norm = NTSC;
  4121. arg += 5;
  4122. } else if (!strncmp(arg, "film-", 5)) {
  4123. norm = FILM;
  4124. arg += 5;
  4125. } else {
  4126. /* Try to determine PAL/NTSC by peeking in the input files */
  4127. if (nb_input_files) {
  4128. int i, j, fr;
  4129. for (j = 0; j < nb_input_files; j++) {
  4130. for (i = 0; i < input_files[j].nb_streams; i++) {
  4131. AVCodecContext *c = input_files[j].ctx->streams[i]->codec;
  4132. if (c->codec_type != AVMEDIA_TYPE_VIDEO ||
  4133. !c->time_base.num)
  4134. continue;
  4135. fr = c->time_base.den * 1000 / c->time_base.num;
  4136. if (fr == 25000) {
  4137. norm = PAL;
  4138. break;
  4139. } else if ((fr == 29970) || (fr == 23976)) {
  4140. norm = NTSC;
  4141. break;
  4142. }
  4143. }
  4144. if (norm != UNKNOWN)
  4145. break;
  4146. }
  4147. }
  4148. if (norm != UNKNOWN)
  4149. av_log(NULL, AV_LOG_INFO, "Assuming %s for target.\n", norm == PAL ? "PAL" : "NTSC");
  4150. }
  4151. if (norm == UNKNOWN) {
  4152. av_log(NULL, AV_LOG_FATAL, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
  4153. av_log(NULL, AV_LOG_FATAL, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
  4154. av_log(NULL, AV_LOG_FATAL, "or set a framerate with \"-r xxx\".\n");
  4155. exit_program(1);
  4156. }
  4157. if (!strcmp(arg, "vcd")) {
  4158. opt_video_codec(o, "c:v", "mpeg1video");
  4159. opt_audio_codec(o, "c:a", "mp2");
  4160. parse_option(o, "f", "vcd", options);
  4161. parse_option(o, "s", norm == PAL ? "352x288" : "352x240", options);
  4162. parse_option(o, "r", frame_rates[norm], options);
  4163. opt_default("g", norm == PAL ? "15" : "18");
  4164. opt_default("b:v", "1150000");
  4165. opt_default("maxrate", "1150000");
  4166. opt_default("minrate", "1150000");
  4167. opt_default("bufsize", "327680"); // 40*1024*8;
  4168. opt_default("b:a", "224000");
  4169. parse_option(o, "ar", "44100", options);
  4170. parse_option(o, "ac", "2", options);
  4171. opt_default("packetsize", "2324");
  4172. opt_default("muxrate", "1411200"); // 2352 * 75 * 8;
  4173. /* We have to offset the PTS, so that it is consistent with the SCR.
  4174. SCR starts at 36000, but the first two packs contain only padding
  4175. and the first pack from the other stream, respectively, may also have
  4176. been written before.
  4177. So the real data starts at SCR 36000+3*1200. */
  4178. o->mux_preload = (36000 + 3 * 1200) / 90000.0; // 0.44
  4179. } else if (!strcmp(arg, "svcd")) {
  4180. opt_video_codec(o, "c:v", "mpeg2video");
  4181. opt_audio_codec(o, "c:a", "mp2");
  4182. parse_option(o, "f", "svcd", options);
  4183. parse_option(o, "s", norm == PAL ? "480x576" : "480x480", options);
  4184. parse_option(o, "r", frame_rates[norm], options);
  4185. parse_option(o, "pix_fmt", "yuv420p", options);
  4186. opt_default("g", norm == PAL ? "15" : "18");
  4187. opt_default("b:v", "2040000");
  4188. opt_default("maxrate", "2516000");
  4189. opt_default("minrate", "0"); // 1145000;
  4190. opt_default("bufsize", "1835008"); // 224*1024*8;
  4191. opt_default("flags", "+scan_offset");
  4192. opt_default("b:a", "224000");
  4193. parse_option(o, "ar", "44100", options);
  4194. opt_default("packetsize", "2324");
  4195. } else if (!strcmp(arg, "dvd")) {
  4196. opt_video_codec(o, "c:v", "mpeg2video");
  4197. opt_audio_codec(o, "c:a", "ac3");
  4198. parse_option(o, "f", "dvd", options);
  4199. parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
  4200. parse_option(o, "r", frame_rates[norm], options);
  4201. parse_option(o, "pix_fmt", "yuv420p", options);
  4202. opt_default("g", norm == PAL ? "15" : "18");
  4203. opt_default("b:v", "6000000");
  4204. opt_default("maxrate", "9000000");
  4205. opt_default("minrate", "0"); // 1500000;
  4206. opt_default("bufsize", "1835008"); // 224*1024*8;
  4207. opt_default("packetsize", "2048"); // from www.mpucoder.com: DVD sectors contain 2048 bytes of data, this is also the size of one pack.
  4208. opt_default("muxrate", "10080000"); // from mplex project: data_rate = 1260000. mux_rate = data_rate * 8
  4209. opt_default("b:a", "448000");
  4210. parse_option(o, "ar", "48000", options);
  4211. } else if (!strncmp(arg, "dv", 2)) {
  4212. parse_option(o, "f", "dv", options);
  4213. parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
  4214. parse_option(o, "pix_fmt", !strncmp(arg, "dv50", 4) ? "yuv422p" :
  4215. norm == PAL ? "yuv420p" : "yuv411p", options);
  4216. parse_option(o, "r", frame_rates[norm], options);
  4217. parse_option(o, "ar", "48000", options);
  4218. parse_option(o, "ac", "2", options);
  4219. } else {
  4220. av_log(NULL, AV_LOG_ERROR, "Unknown target: %s\n", arg);
  4221. return AVERROR(EINVAL);
  4222. }
  4223. return 0;
  4224. }
  4225. static int opt_vstats_file(const char *opt, const char *arg)
  4226. {
  4227. av_free (vstats_filename);
  4228. vstats_filename = av_strdup (arg);
  4229. return 0;
  4230. }
  4231. static int opt_vstats(const char *opt, const char *arg)
  4232. {
  4233. char filename[40];
  4234. time_t today2 = time(NULL);
  4235. struct tm *today = localtime(&today2);
  4236. snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour, today->tm_min,
  4237. today->tm_sec);
  4238. return opt_vstats_file(opt, filename);
  4239. }
  4240. static int opt_video_frames(OptionsContext *o, const char *opt, const char *arg)
  4241. {
  4242. return parse_option(o, "frames:v", arg, options);
  4243. }
  4244. static int opt_audio_frames(OptionsContext *o, const char *opt, const char *arg)
  4245. {
  4246. return parse_option(o, "frames:a", arg, options);
  4247. }
  4248. static int opt_data_frames(OptionsContext *o, const char *opt, const char *arg)
  4249. {
  4250. return parse_option(o, "frames:d", arg, options);
  4251. }
  4252. static int opt_preset(OptionsContext *o, const char *opt, const char *arg)
  4253. {
  4254. FILE *f=NULL;
  4255. char filename[1000], tmp[1000], tmp2[1000], line[1000];
  4256. const char *codec_name = *opt == 'v' ? video_codec_name :
  4257. *opt == 'a' ? audio_codec_name :
  4258. subtitle_codec_name;
  4259. if (!(f = get_preset_file(filename, sizeof(filename), arg, *opt == 'f', codec_name))) {
  4260. if(!strncmp(arg, "libx264-lossless", strlen("libx264-lossless"))){
  4261. av_log(0, AV_LOG_FATAL, "Please use -preset <speed> -qp 0\n");
  4262. }else
  4263. av_log(0, AV_LOG_FATAL, "File for preset '%s' not found\n", arg);
  4264. exit_program(1);
  4265. }
  4266. while(!feof(f)){
  4267. int e= fscanf(f, "%999[^\n]\n", line) - 1;
  4268. if(line[0] == '#' && !e)
  4269. continue;
  4270. e|= sscanf(line, "%999[^=]=%999[^\n]\n", tmp, tmp2) - 2;
  4271. if(e){
  4272. av_log(0, AV_LOG_FATAL, "%s: Invalid syntax: '%s'\n", filename, line);
  4273. exit_program(1);
  4274. }
  4275. if(!strcmp(tmp, "acodec")){
  4276. opt_audio_codec(o, tmp, tmp2);
  4277. }else if(!strcmp(tmp, "vcodec")){
  4278. opt_video_codec(o, tmp, tmp2);
  4279. }else if(!strcmp(tmp, "scodec")){
  4280. opt_subtitle_codec(o, tmp, tmp2);
  4281. }else if(!strcmp(tmp, "dcodec")){
  4282. opt_data_codec(o, tmp, tmp2);
  4283. }else if(opt_default(tmp, tmp2) < 0){
  4284. av_log(0, AV_LOG_FATAL, "%s: Invalid option or argument: '%s', parsed as '%s' = '%s'\n", filename, line, tmp, tmp2);
  4285. exit_program(1);
  4286. }
  4287. }
  4288. fclose(f);
  4289. return 0;
  4290. }
  4291. static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
  4292. {
  4293. }
  4294. static int opt_passlogfile(const char *opt, const char *arg)
  4295. {
  4296. pass_logfilename_prefix = arg;
  4297. #if CONFIG_LIBX264_ENCODER
  4298. return opt_default("passlogfile", arg);
  4299. #else
  4300. return 0;
  4301. #endif
  4302. }
  4303. static int opt_old2new(OptionsContext *o, const char *opt, const char *arg)
  4304. {
  4305. char *s = av_asprintf("%s:%c", opt + 1, *opt);
  4306. int ret = parse_option(o, s, arg, options);
  4307. av_free(s);
  4308. return ret;
  4309. }
  4310. static int opt_bitrate(OptionsContext *o, const char *opt, const char *arg)
  4311. {
  4312. if(!strcmp(opt, "b")){
  4313. av_log(0,AV_LOG_WARNING, "Please use -b:a or -b:v, -b is ambiguous\n");
  4314. return parse_option(o, "b:v", arg, options);
  4315. }
  4316. return opt_default(opt, arg);
  4317. }
  4318. static int opt_qscale(OptionsContext *o, const char *opt, const char *arg)
  4319. {
  4320. char *s;
  4321. int ret;
  4322. if(!strcmp(opt, "qscale")){
  4323. av_log(0,AV_LOG_WARNING, "Please use -q:a or -q:v, -qscale is ambiguous\n");
  4324. return parse_option(o, "q:v", arg, options);
  4325. }
  4326. s = av_asprintf("q%s", opt + 6);
  4327. ret = parse_option(o, s, arg, options);
  4328. av_free(s);
  4329. return ret;
  4330. }
  4331. static int opt_video_filters(OptionsContext *o, const char *opt, const char *arg)
  4332. {
  4333. return parse_option(o, "filter:v", arg, options);
  4334. }
  4335. static int opt_vsync(const char *opt, const char *arg)
  4336. {
  4337. if (!av_strcasecmp(arg, "cfr")) video_sync_method = VSYNC_CFR;
  4338. else if (!av_strcasecmp(arg, "vfr")) video_sync_method = VSYNC_VFR;
  4339. else if (!av_strcasecmp(arg, "passthrough")) video_sync_method = VSYNC_PASSTHROUGH;
  4340. if (video_sync_method == VSYNC_AUTO)
  4341. video_sync_method = parse_number_or_die("vsync", arg, OPT_INT, VSYNC_AUTO, VSYNC_VFR);
  4342. return 0;
  4343. }
  4344. #define OFFSET(x) offsetof(OptionsContext, x)
  4345. static const OptionDef options[] = {
  4346. /* main options */
  4347. #include "cmdutils_common_opts.h"
  4348. { "f", HAS_ARG | OPT_STRING | OPT_OFFSET, {.off = OFFSET(format)}, "force format", "fmt" },
  4349. { "i", HAS_ARG | OPT_FUNC2, {(void*)opt_input_file}, "input file name", "filename" },
  4350. { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
  4351. { "n", OPT_BOOL, {(void*)&no_file_overwrite}, "do not overwrite output files" },
  4352. { "c", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(codec_names)}, "codec name", "codec" },
  4353. { "codec", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(codec_names)}, "codec name", "codec" },
  4354. { "pre", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(presets)}, "preset name", "preset" },
  4355. { "map", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_map}, "set input stream mapping", "[-]input_file_id[:stream_specifier][,sync_file_id[:stream_specifier]]" },
  4356. { "map_channel", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_map_channel}, "map an audio channel from one stream to another", "file.stream.channel[:syncfile.syncstream]" },
  4357. { "map_metadata", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(metadata_map)}, "set metadata information of outfile from infile",
  4358. "outfile[,metadata]:infile[,metadata]" },
  4359. { "map_chapters", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(chapters_input_file)}, "set chapters mapping", "input_file_index" },
  4360. { "t", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(recording_time)}, "record or transcode \"duration\" seconds of audio/video", "duration" },
  4361. { "fs", HAS_ARG | OPT_INT64 | OPT_OFFSET, {.off = OFFSET(limit_filesize)}, "set the limit file size in bytes", "limit_size" }, //
  4362. { "ss", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(start_time)}, "set the start time offset", "time_off" },
  4363. { "itsoffset", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(input_ts_offset)}, "set the input ts offset", "time_off" },
  4364. { "itsscale", HAS_ARG | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(ts_scale)}, "set the input ts scale", "scale" },
  4365. { "timestamp", HAS_ARG | OPT_FUNC2, {(void*)opt_recording_timestamp}, "set the recording timestamp ('now' to set the current time)", "time" },
  4366. { "metadata", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(metadata)}, "add metadata", "string=string" },
  4367. { "dframes", HAS_ARG | OPT_FUNC2, {(void*)opt_data_frames}, "set the number of data frames to record", "number" },
  4368. { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
  4369. "add timings for benchmarking" },
  4370. { "timelimit", HAS_ARG, {(void*)opt_timelimit}, "set max runtime in seconds", "limit" },
  4371. { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump},
  4372. "dump each input packet" },
  4373. { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
  4374. "when dumping packets, also dump the payload" },
  4375. { "re", OPT_BOOL | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(rate_emu)}, "read input at native frame rate", "" },
  4376. { "loop_input", OPT_BOOL | OPT_EXPERT, {(void*)&loop_input}, "deprecated, use -loop" },
  4377. { "loop_output", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&loop_output}, "deprecated, use -loop", "" },
  4378. { "target", HAS_ARG | OPT_FUNC2, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\", \"dv50\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
  4379. { "vsync", HAS_ARG | OPT_EXPERT, {(void*)opt_vsync}, "video sync method", "" },
  4380. { "async", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&audio_sync_method}, "audio sync method", "" },
  4381. { "adrift_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&audio_drift_threshold}, "audio drift threshold", "threshold" },
  4382. { "copyts", OPT_BOOL | OPT_EXPERT, {(void*)&copy_ts}, "copy timestamps" },
  4383. { "copytb", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&copy_tb}, "copy input stream time base when stream copying", "source" },
  4384. { "shortest", OPT_BOOL | OPT_EXPERT, {(void*)&opt_shortest}, "finish encoding within shortest input" }, //
  4385. { "dts_delta_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&dts_delta_threshold}, "timestamp discontinuity delta threshold", "threshold" },
  4386. { "xerror", OPT_BOOL, {(void*)&exit_on_error}, "exit on error", "error" },
  4387. { "copyinkf", OPT_BOOL | OPT_EXPERT | OPT_SPEC, {.off = OFFSET(copy_initial_nonkeyframes)}, "copy initial non-keyframes" },
  4388. { "frames", OPT_INT64 | HAS_ARG | OPT_SPEC, {.off = OFFSET(max_frames)}, "set the number of frames to record", "number" },
  4389. { "tag", OPT_STRING | HAS_ARG | OPT_SPEC, {.off = OFFSET(codec_tags)}, "force codec tag/fourcc", "fourcc/tag" },
  4390. { "q", HAS_ARG | OPT_EXPERT | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(qscale)}, "use fixed quality scale (VBR)", "q" },
  4391. { "qscale", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_qscale}, "use fixed quality scale (VBR)", "q" },
  4392. #if CONFIG_AVFILTER
  4393. { "filter", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(filters)}, "set stream filterchain", "filter_list" },
  4394. #endif
  4395. { "stats", OPT_BOOL, {&print_stats}, "print progress report during encoding", },
  4396. { "attach", HAS_ARG | OPT_FUNC2, {(void*)opt_attach}, "add an attachment to the output file", "filename" },
  4397. { "dump_attachment", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(dump_attachment)}, "extract an attachment into a file", "filename" },
  4398. /* video options */
  4399. { "vframes", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_frames}, "set the number of video frames to record", "number" },
  4400. { "r", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_rates)}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
  4401. { "s", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_sizes)}, "set frame size (WxH or abbreviation)", "size" },
  4402. { "aspect", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_aspect_ratios)}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
  4403. { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_pix_fmts)}, "set pixel format", "format" },
  4404. { "bits_per_raw_sample", OPT_INT | HAS_ARG | OPT_VIDEO, {(void*)&frame_bits_per_raw_sample}, "set the number of bits per raw sample", "number" },
  4405. { "croptop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
  4406. { "cropbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
  4407. { "cropleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
  4408. { "cropright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
  4409. { "padtop", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
  4410. { "padbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
  4411. { "padleft", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
  4412. { "padright", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
  4413. { "padcolor", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "color" },
  4414. { "intra", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_only}, "use only intra frames"},
  4415. { "vn", OPT_BOOL | OPT_VIDEO | OPT_OFFSET, {.off = OFFSET(video_disable)}, "disable video" },
  4416. { "vdt", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&video_discard}, "discard threshold", "n" },
  4417. { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(rc_overrides)}, "rate control override for specific intervals", "override" },
  4418. { "vcodec", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
  4419. { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quant}, "use same quantizer as source (implies VBR)" },
  4420. { "same_quant", OPT_BOOL | OPT_VIDEO, {(void*)&same_quant},
  4421. "use same quantizer as source (implies VBR)" },
  4422. { "pass", HAS_ARG | OPT_VIDEO, {(void*)opt_pass}, "select the pass number (1 or 2)", "n" },
  4423. { "passlogfile", HAS_ARG | OPT_VIDEO, {(void*)&opt_passlogfile}, "select two pass log file name prefix", "prefix" },
  4424. { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace},
  4425. "deinterlace pictures" },
  4426. { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
  4427. { "vstats", OPT_EXPERT | OPT_VIDEO, {(void*)&opt_vstats}, "dump video coding statistics to file" },
  4428. { "vstats_file", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_vstats_file}, "dump video coding statistics to file", "file" },
  4429. #if CONFIG_AVFILTER
  4430. { "vf", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_filters}, "video filters", "filter list" },
  4431. #endif
  4432. { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(intra_matrices)}, "specify intra matrix coeffs", "matrix" },
  4433. { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(inter_matrices)}, "specify inter matrix coeffs", "matrix" },
  4434. { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_INT| OPT_SPEC, {.off = OFFSET(top_field_first)}, "top=1/bottom=0/auto=-1 field first", "" },
  4435. { "dc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_dc_precision}, "intra_dc_precision", "precision" },
  4436. { "vtag", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_FUNC2, {(void*)opt_old2new}, "force video tag/fourcc", "fourcc/tag" },
  4437. { "qphist", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, { (void *)&qp_hist }, "show QP histogram" },
  4438. { "force_fps", OPT_BOOL | OPT_EXPERT | OPT_VIDEO | OPT_SPEC, {.off = OFFSET(force_fps)}, "force the selected framerate, disable the best supported framerate selection" },
  4439. { "streamid", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_streamid}, "set the value of an outfile streamid", "streamIndex:value" },
  4440. { "force_key_frames", OPT_STRING | HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_SPEC, {.off = OFFSET(forced_key_frames)}, "force key frames at specified timestamps", "timestamps" },
  4441. { "b", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_bitrate}, "video bitrate (please use -b:v)", "bitrate" },
  4442. /* audio options */
  4443. { "aframes", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_frames}, "set the number of audio frames to record", "number" },
  4444. { "aq", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_qscale}, "set audio quality (codec-specific)", "quality", },
  4445. { "ar", HAS_ARG | OPT_AUDIO | OPT_INT | OPT_SPEC, {.off = OFFSET(audio_sample_rate)}, "set audio sampling rate (in Hz)", "rate" },
  4446. { "ac", HAS_ARG | OPT_AUDIO | OPT_INT | OPT_SPEC, {.off = OFFSET(audio_channels)}, "set number of audio channels", "channels" },
  4447. { "an", OPT_BOOL | OPT_AUDIO | OPT_OFFSET, {.off = OFFSET(audio_disable)}, "disable audio" },
  4448. { "acodec", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
  4449. { "atag", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_FUNC2, {(void*)opt_old2new}, "force audio tag/fourcc", "fourcc/tag" },
  4450. { "vol", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&audio_volume}, "change audio volume (256=normal)" , "volume" }, //
  4451. { "sample_fmt", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_SPEC | OPT_STRING, {.off = OFFSET(sample_fmts)}, "set sample format", "format" },
  4452. { "rmvol", HAS_ARG | OPT_AUDIO | OPT_FLOAT | OPT_SPEC, {.off = OFFSET(rematrix_volume)}, "rematrix volume (as factor)", "volume" },
  4453. /* subtitle options */
  4454. { "sn", OPT_BOOL | OPT_SUBTITLE | OPT_OFFSET, {.off = OFFSET(subtitle_disable)}, "disable subtitle" },
  4455. { "scodec", HAS_ARG | OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_subtitle_codec}, "force subtitle codec ('copy' to copy stream)", "codec" },
  4456. { "stag", HAS_ARG | OPT_EXPERT | OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_old2new}, "force subtitle tag/fourcc", "fourcc/tag" },
  4457. /* grab options */
  4458. { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "deprecated, use -channel", "channel" },
  4459. { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "deprecated, use -standard", "standard" },
  4460. { "isync", OPT_BOOL | OPT_EXPERT | OPT_GRAB, {(void*)&input_sync}, "sync read on input", "" },
  4461. /* muxer options */
  4462. { "muxdelay", OPT_FLOAT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(mux_max_delay)}, "set the maximum demux-decode delay", "seconds" },
  4463. { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(mux_preload)}, "set the initial demux-decode delay", "seconds" },
  4464. { "bsf", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(bitstream_filters)}, "A comma-separated list of bitstream filters", "bitstream_filters" },
  4465. { "absf", HAS_ARG | OPT_AUDIO | OPT_EXPERT| OPT_FUNC2, {(void*)opt_old2new}, "deprecated", "audio bitstream_filters" },
  4466. { "vbsf", HAS_ARG | OPT_VIDEO | OPT_EXPERT| OPT_FUNC2, {(void*)opt_old2new}, "deprecated", "video bitstream_filters" },
  4467. { "apre", HAS_ARG | OPT_AUDIO | OPT_EXPERT| OPT_FUNC2, {(void*)opt_preset}, "set the audio options to the indicated preset", "preset" },
  4468. { "vpre", HAS_ARG | OPT_VIDEO | OPT_EXPERT| OPT_FUNC2, {(void*)opt_preset}, "set the video options to the indicated preset", "preset" },
  4469. { "spre", HAS_ARG | OPT_SUBTITLE | OPT_EXPERT| OPT_FUNC2, {(void*)opt_preset}, "set the subtitle options to the indicated preset", "preset" },
  4470. { "fpre", HAS_ARG | OPT_EXPERT| OPT_FUNC2, {(void*)opt_preset}, "set options from indicated preset file", "filename" },
  4471. /* data codec support */
  4472. { "dcodec", HAS_ARG | OPT_DATA | OPT_FUNC2, {(void*)opt_data_codec}, "force data codec ('copy' to copy stream)", "codec" },
  4473. { "dn", OPT_BOOL | OPT_VIDEO | OPT_OFFSET, {.off = OFFSET(data_disable)}, "disable data" },
  4474. { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
  4475. { NULL, },
  4476. };
  4477. int main(int argc, char **argv)
  4478. {
  4479. OptionsContext o = { 0 };
  4480. int64_t ti;
  4481. reset_options(&o, 0);
  4482. av_log_set_flags(AV_LOG_SKIP_REPEATED);
  4483. parse_loglevel(argc, argv, options);
  4484. if(argc>1 && !strcmp(argv[1], "-d")){
  4485. run_as_daemon=1;
  4486. av_log_set_callback(log_callback_null);
  4487. argc--;
  4488. argv++;
  4489. }
  4490. avcodec_register_all();
  4491. #if CONFIG_AVDEVICE
  4492. avdevice_register_all();
  4493. #endif
  4494. #if CONFIG_AVFILTER
  4495. avfilter_register_all();
  4496. #endif
  4497. av_register_all();
  4498. avformat_network_init();
  4499. show_banner(argc, argv, options);
  4500. term_init();
  4501. /* parse options */
  4502. parse_options(&o, argc, argv, options, opt_output_file);
  4503. if (nb_output_files <= 0 && nb_input_files == 0) {
  4504. show_usage();
  4505. av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
  4506. exit_program(1);
  4507. }
  4508. /* file converter / grab */
  4509. if (nb_output_files <= 0) {
  4510. av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
  4511. exit_program(1);
  4512. }
  4513. if (nb_input_files == 0) {
  4514. av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
  4515. exit_program(1);
  4516. }
  4517. ti = getutime();
  4518. if (transcode(output_files, nb_output_files, input_files, nb_input_files) < 0)
  4519. exit_program(1);
  4520. ti = getutime() - ti;
  4521. if (do_benchmark) {
  4522. int maxrss = getmaxrss() / 1024;
  4523. printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);
  4524. }
  4525. exit_program(0);
  4526. return 0;
  4527. }