ffmpeg.c 158 KB

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