ffmpeg.c 147 KB

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