ffmpeg.c 137 KB

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