ffmpeg.c 117 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358
  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. #if HAVE_ISATTY
  32. #if HAVE_IO_H
  33. #include <io.h>
  34. #endif
  35. #if HAVE_UNISTD_H
  36. #include <unistd.h>
  37. #endif
  38. #endif
  39. #include "libavformat/avformat.h"
  40. #include "libavdevice/avdevice.h"
  41. #include "libswscale/swscale.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/colorspace.h"
  48. #include "libavutil/fifo.h"
  49. #include "libavutil/intreadwrite.h"
  50. #include "libavutil/dict.h"
  51. #include "libavutil/mathematics.h"
  52. #include "libavutil/pixdesc.h"
  53. #include "libavutil/avstring.h"
  54. #include "libavutil/libm.h"
  55. #include "libavutil/imgutils.h"
  56. #include "libavutil/timestamp.h"
  57. #include "libavutil/bprint.h"
  58. #include "libavutil/time.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/avfiltergraph.h"
  64. # include "libavfilter/buffersrc.h"
  65. # include "libavfilter/buffersink.h"
  66. #if HAVE_SYS_RESOURCE_H
  67. #include <sys/time.h>
  68. #include <sys/types.h>
  69. #include <sys/resource.h>
  70. #elif HAVE_GETPROCESSTIMES
  71. #include <windows.h>
  72. #endif
  73. #if HAVE_GETPROCESSMEMORYINFO
  74. #include <windows.h>
  75. #include <psapi.h>
  76. #endif
  77. #if HAVE_SYS_SELECT_H
  78. #include <sys/select.h>
  79. #endif
  80. #if HAVE_TERMIOS_H
  81. #include <fcntl.h>
  82. #include <sys/ioctl.h>
  83. #include <sys/time.h>
  84. #include <termios.h>
  85. #elif HAVE_KBHIT
  86. #include <conio.h>
  87. #endif
  88. #if HAVE_PTHREADS
  89. #include <pthread.h>
  90. #endif
  91. #include <time.h>
  92. #include "ffmpeg.h"
  93. #include "cmdutils.h"
  94. #include "libavutil/avassert.h"
  95. const char program_name[] = "ffmpeg";
  96. const int program_birth_year = 2000;
  97. static FILE *vstats_file;
  98. const char *const forced_keyframes_const_names[] = {
  99. "n",
  100. "n_forced",
  101. "prev_forced_n",
  102. "prev_forced_t",
  103. "t",
  104. NULL
  105. };
  106. static void do_video_stats(OutputStream *ost, int frame_size);
  107. static int64_t getutime(void);
  108. static int64_t getmaxrss(void);
  109. static int run_as_daemon = 0;
  110. static int64_t video_size = 0;
  111. static int64_t audio_size = 0;
  112. static int64_t subtitle_size = 0;
  113. static int64_t extra_size = 0;
  114. static int nb_frames_dup = 0;
  115. static int nb_frames_drop = 0;
  116. static int current_time;
  117. AVIOContext *progress_avio = NULL;
  118. static uint8_t *subtitle_out;
  119. #if HAVE_PTHREADS
  120. /* signal to input threads that they should exit; set by the main thread */
  121. static int transcoding_finished;
  122. #endif
  123. #define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
  124. InputStream **input_streams = NULL;
  125. int nb_input_streams = 0;
  126. InputFile **input_files = NULL;
  127. int nb_input_files = 0;
  128. OutputStream **output_streams = NULL;
  129. int nb_output_streams = 0;
  130. OutputFile **output_files = NULL;
  131. int nb_output_files = 0;
  132. FilterGraph **filtergraphs;
  133. int nb_filtergraphs;
  134. #if HAVE_TERMIOS_H
  135. /* init terminal so that we can grab keys */
  136. static struct termios oldtty;
  137. static int restore_tty;
  138. #endif
  139. static void free_input_threads(void);
  140. /* sub2video hack:
  141. Convert subtitles to video with alpha to insert them in filter graphs.
  142. This is a temporary solution until libavfilter gets real subtitles support.
  143. */
  144. static void sub2video_copy_rect(uint8_t *dst, int dst_linesize, int w, int h,
  145. AVSubtitleRect *r)
  146. {
  147. uint32_t *pal, *dst2;
  148. uint8_t *src, *src2;
  149. int x, y;
  150. if (r->type != SUBTITLE_BITMAP) {
  151. av_log(NULL, AV_LOG_WARNING, "sub2video: non-bitmap subtitle\n");
  152. return;
  153. }
  154. if (r->x < 0 || r->x + r->w > w || r->y < 0 || r->y + r->h > h) {
  155. av_log(NULL, AV_LOG_WARNING, "sub2video: rectangle overflowing\n");
  156. return;
  157. }
  158. dst += r->y * dst_linesize + r->x * 4;
  159. src = r->pict.data[0];
  160. pal = (uint32_t *)r->pict.data[1];
  161. for (y = 0; y < r->h; y++) {
  162. dst2 = (uint32_t *)dst;
  163. src2 = src;
  164. for (x = 0; x < r->w; x++)
  165. *(dst2++) = pal[*(src2++)];
  166. dst += dst_linesize;
  167. src += r->pict.linesize[0];
  168. }
  169. }
  170. static void sub2video_push_ref(InputStream *ist, int64_t pts)
  171. {
  172. AVFilterBufferRef *ref = ist->sub2video.ref;
  173. int i;
  174. ist->sub2video.last_pts = ref->pts = pts;
  175. for (i = 0; i < ist->nb_filters; i++)
  176. av_buffersrc_add_ref(ist->filters[i]->filter,
  177. avfilter_ref_buffer(ref, ~0),
  178. AV_BUFFERSRC_FLAG_NO_CHECK_FORMAT |
  179. AV_BUFFERSRC_FLAG_NO_COPY |
  180. AV_BUFFERSRC_FLAG_PUSH);
  181. }
  182. static void sub2video_update(InputStream *ist, AVSubtitle *sub)
  183. {
  184. int w = ist->sub2video.w, h = ist->sub2video.h;
  185. AVFilterBufferRef *ref = ist->sub2video.ref;
  186. int8_t *dst;
  187. int dst_linesize;
  188. int num_rects, i;
  189. int64_t pts, end_pts;
  190. if (!ref)
  191. return;
  192. if (sub) {
  193. pts = av_rescale_q(sub->pts + sub->start_display_time * 1000,
  194. AV_TIME_BASE_Q, ist->st->time_base);
  195. end_pts = av_rescale_q(sub->pts + sub->end_display_time * 1000,
  196. AV_TIME_BASE_Q, ist->st->time_base);
  197. num_rects = sub->num_rects;
  198. } else {
  199. pts = ist->sub2video.end_pts;
  200. end_pts = INT64_MAX;
  201. num_rects = 0;
  202. }
  203. dst = ref->data [0];
  204. dst_linesize = ref->linesize[0];
  205. memset(dst, 0, h * dst_linesize);
  206. for (i = 0; i < num_rects; i++)
  207. sub2video_copy_rect(dst, dst_linesize, w, h, sub->rects[i]);
  208. sub2video_push_ref(ist, pts);
  209. ist->sub2video.end_pts = end_pts;
  210. }
  211. static void sub2video_heartbeat(InputStream *ist, int64_t pts)
  212. {
  213. InputFile *infile = input_files[ist->file_index];
  214. int i, j, nb_reqs;
  215. int64_t pts2;
  216. /* When a frame is read from a file, examine all sub2video streams in
  217. the same file and send the sub2video frame again. Otherwise, decoded
  218. video frames could be accumulating in the filter graph while a filter
  219. (possibly overlay) is desperately waiting for a subtitle frame. */
  220. for (i = 0; i < infile->nb_streams; i++) {
  221. InputStream *ist2 = input_streams[infile->ist_index + i];
  222. if (!ist2->sub2video.ref)
  223. continue;
  224. /* subtitles seem to be usually muxed ahead of other streams;
  225. if not, substracting a larger time here is necessary */
  226. pts2 = av_rescale_q(pts, ist->st->time_base, ist2->st->time_base) - 1;
  227. /* do not send the heartbeat frame if the subtitle is already ahead */
  228. if (pts2 <= ist2->sub2video.last_pts)
  229. continue;
  230. if (pts2 >= ist2->sub2video.end_pts)
  231. sub2video_update(ist2, NULL);
  232. for (j = 0, nb_reqs = 0; j < ist2->nb_filters; j++)
  233. nb_reqs += av_buffersrc_get_nb_failed_requests(ist2->filters[j]->filter);
  234. if (nb_reqs)
  235. sub2video_push_ref(ist2, pts2);
  236. }
  237. }
  238. static void sub2video_flush(InputStream *ist)
  239. {
  240. int i;
  241. for (i = 0; i < ist->nb_filters; i++)
  242. av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
  243. }
  244. /* end of sub2video hack */
  245. void term_exit(void)
  246. {
  247. av_log(NULL, AV_LOG_QUIET, "%s", "");
  248. #if HAVE_TERMIOS_H
  249. if(restore_tty)
  250. tcsetattr (0, TCSANOW, &oldtty);
  251. #endif
  252. }
  253. static volatile int received_sigterm = 0;
  254. static volatile int received_nb_signals = 0;
  255. static void
  256. sigterm_handler(int sig)
  257. {
  258. received_sigterm = sig;
  259. received_nb_signals++;
  260. term_exit();
  261. if(received_nb_signals > 3)
  262. exit(123);
  263. }
  264. void term_init(void)
  265. {
  266. #if HAVE_TERMIOS_H
  267. if(!run_as_daemon){
  268. struct termios tty;
  269. int istty = 1;
  270. #if HAVE_ISATTY
  271. istty = isatty(0) && isatty(2);
  272. #endif
  273. if (istty && tcgetattr (0, &tty) == 0) {
  274. oldtty = tty;
  275. restore_tty = 1;
  276. atexit(term_exit);
  277. tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
  278. |INLCR|IGNCR|ICRNL|IXON);
  279. tty.c_oflag |= OPOST;
  280. tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
  281. tty.c_cflag &= ~(CSIZE|PARENB);
  282. tty.c_cflag |= CS8;
  283. tty.c_cc[VMIN] = 1;
  284. tty.c_cc[VTIME] = 0;
  285. tcsetattr (0, TCSANOW, &tty);
  286. }
  287. signal(SIGQUIT, sigterm_handler); /* Quit (POSIX). */
  288. }
  289. #endif
  290. avformat_network_deinit();
  291. signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
  292. signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
  293. #ifdef SIGXCPU
  294. signal(SIGXCPU, sigterm_handler);
  295. #endif
  296. }
  297. /* read a key without blocking */
  298. static int read_key(void)
  299. {
  300. unsigned char ch;
  301. #if HAVE_TERMIOS_H
  302. int n = 1;
  303. struct timeval tv;
  304. fd_set rfds;
  305. FD_ZERO(&rfds);
  306. FD_SET(0, &rfds);
  307. tv.tv_sec = 0;
  308. tv.tv_usec = 0;
  309. n = select(1, &rfds, NULL, NULL, &tv);
  310. if (n > 0) {
  311. n = read(0, &ch, 1);
  312. if (n == 1)
  313. return ch;
  314. return n;
  315. }
  316. #elif HAVE_KBHIT
  317. # if HAVE_PEEKNAMEDPIPE
  318. static int is_pipe;
  319. static HANDLE input_handle;
  320. DWORD dw, nchars;
  321. if(!input_handle){
  322. input_handle = GetStdHandle(STD_INPUT_HANDLE);
  323. is_pipe = !GetConsoleMode(input_handle, &dw);
  324. }
  325. if (stdin->_cnt > 0) {
  326. read(0, &ch, 1);
  327. return ch;
  328. }
  329. if (is_pipe) {
  330. /* When running under a GUI, you will end here. */
  331. if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL)) {
  332. // input pipe may have been closed by the program that ran ffmpeg
  333. return -1;
  334. }
  335. //Read it
  336. if(nchars != 0) {
  337. read(0, &ch, 1);
  338. return ch;
  339. }else{
  340. return -1;
  341. }
  342. }
  343. # endif
  344. if(kbhit())
  345. return(getch());
  346. #endif
  347. return -1;
  348. }
  349. static int decode_interrupt_cb(void *ctx)
  350. {
  351. return received_nb_signals > 1;
  352. }
  353. const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
  354. static void exit_program(void)
  355. {
  356. int i, j;
  357. if (do_benchmark) {
  358. int maxrss = getmaxrss() / 1024;
  359. printf("bench: maxrss=%ikB\n", maxrss);
  360. }
  361. for (i = 0; i < nb_filtergraphs; i++) {
  362. avfilter_graph_free(&filtergraphs[i]->graph);
  363. for (j = 0; j < filtergraphs[i]->nb_inputs; j++) {
  364. av_freep(&filtergraphs[i]->inputs[j]->name);
  365. av_freep(&filtergraphs[i]->inputs[j]);
  366. }
  367. av_freep(&filtergraphs[i]->inputs);
  368. for (j = 0; j < filtergraphs[i]->nb_outputs; j++) {
  369. av_freep(&filtergraphs[i]->outputs[j]->name);
  370. av_freep(&filtergraphs[i]->outputs[j]);
  371. }
  372. av_freep(&filtergraphs[i]->outputs);
  373. av_freep(&filtergraphs[i]);
  374. }
  375. av_freep(&filtergraphs);
  376. av_freep(&subtitle_out);
  377. /* close files */
  378. for (i = 0; i < nb_output_files; i++) {
  379. AVFormatContext *s = output_files[i]->ctx;
  380. if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
  381. avio_close(s->pb);
  382. avformat_free_context(s);
  383. av_dict_free(&output_files[i]->opts);
  384. av_freep(&output_files[i]);
  385. }
  386. for (i = 0; i < nb_output_streams; i++) {
  387. AVBitStreamFilterContext *bsfc = output_streams[i]->bitstream_filters;
  388. while (bsfc) {
  389. AVBitStreamFilterContext *next = bsfc->next;
  390. av_bitstream_filter_close(bsfc);
  391. bsfc = next;
  392. }
  393. output_streams[i]->bitstream_filters = NULL;
  394. avcodec_free_frame(&output_streams[i]->filtered_frame);
  395. av_freep(&output_streams[i]->forced_keyframes);
  396. av_expr_free(output_streams[i]->forced_keyframes_pexpr);
  397. av_freep(&output_streams[i]->avfilter);
  398. av_freep(&output_streams[i]->logfile_prefix);
  399. av_freep(&output_streams[i]);
  400. }
  401. #if HAVE_PTHREADS
  402. free_input_threads();
  403. #endif
  404. for (i = 0; i < nb_input_files; i++) {
  405. avformat_close_input(&input_files[i]->ctx);
  406. av_freep(&input_files[i]);
  407. }
  408. for (i = 0; i < nb_input_streams; i++) {
  409. avcodec_free_frame(&input_streams[i]->decoded_frame);
  410. av_dict_free(&input_streams[i]->opts);
  411. free_buffer_pool(&input_streams[i]->buffer_pool);
  412. avsubtitle_free(&input_streams[i]->prev_sub.subtitle);
  413. avfilter_unref_bufferp(&input_streams[i]->sub2video.ref);
  414. av_freep(&input_streams[i]->filters);
  415. av_freep(&input_streams[i]);
  416. }
  417. if (vstats_file)
  418. fclose(vstats_file);
  419. av_free(vstats_filename);
  420. av_freep(&input_streams);
  421. av_freep(&input_files);
  422. av_freep(&output_streams);
  423. av_freep(&output_files);
  424. uninit_opts();
  425. avfilter_uninit();
  426. avformat_network_deinit();
  427. if (received_sigterm) {
  428. av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
  429. (int) received_sigterm);
  430. }
  431. }
  432. void assert_avoptions(AVDictionary *m)
  433. {
  434. AVDictionaryEntry *t;
  435. if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
  436. av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
  437. exit(1);
  438. }
  439. }
  440. static void abort_codec_experimental(AVCodec *c, int encoder)
  441. {
  442. exit(1);
  443. }
  444. static void update_benchmark(const char *fmt, ...)
  445. {
  446. if (do_benchmark_all) {
  447. int64_t t = getutime();
  448. va_list va;
  449. char buf[1024];
  450. if (fmt) {
  451. va_start(va, fmt);
  452. vsnprintf(buf, sizeof(buf), fmt, va);
  453. va_end(va);
  454. printf("bench: %8"PRIu64" %s \n", t - current_time, buf);
  455. }
  456. current_time = t;
  457. }
  458. }
  459. static void write_frame(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)
  460. {
  461. AVBitStreamFilterContext *bsfc = ost->bitstream_filters;
  462. AVCodecContext *avctx = ost->st->codec;
  463. int ret;
  464. if ((avctx->codec_type == AVMEDIA_TYPE_VIDEO && video_sync_method == VSYNC_DROP) ||
  465. (avctx->codec_type == AVMEDIA_TYPE_AUDIO && audio_sync_method < 0))
  466. pkt->pts = pkt->dts = AV_NOPTS_VALUE;
  467. if ((avctx->codec_type == AVMEDIA_TYPE_AUDIO || avctx->codec_type == AVMEDIA_TYPE_VIDEO) && pkt->dts != AV_NOPTS_VALUE) {
  468. int64_t max = ost->st->cur_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);
  469. if (ost->st->cur_dts && ost->st->cur_dts != AV_NOPTS_VALUE && max > pkt->dts) {
  470. av_log(s, max - pkt->dts > 2 || avctx->codec_type == AVMEDIA_TYPE_VIDEO ? AV_LOG_WARNING : AV_LOG_DEBUG,
  471. "st:%d PTS: %"PRId64" DTS: %"PRId64" < %"PRId64" invalid, clipping\n", pkt->stream_index, pkt->pts, pkt->dts, max);
  472. if(pkt->pts >= pkt->dts)
  473. pkt->pts = FFMAX(pkt->pts, max);
  474. pkt->dts = max;
  475. }
  476. }
  477. /*
  478. * Audio encoders may split the packets -- #frames in != #packets out.
  479. * But there is no reordering, so we can limit the number of output packets
  480. * by simply dropping them here.
  481. * Counting encoded video frames needs to be done separately because of
  482. * reordering, see do_video_out()
  483. */
  484. if (!(avctx->codec_type == AVMEDIA_TYPE_VIDEO && avctx->codec)) {
  485. if (ost->frame_number >= ost->max_frames) {
  486. av_free_packet(pkt);
  487. return;
  488. }
  489. ost->frame_number++;
  490. }
  491. while (bsfc) {
  492. AVPacket new_pkt = *pkt;
  493. int a = av_bitstream_filter_filter(bsfc, avctx, NULL,
  494. &new_pkt.data, &new_pkt.size,
  495. pkt->data, pkt->size,
  496. pkt->flags & AV_PKT_FLAG_KEY);
  497. if(a == 0 && new_pkt.data != pkt->data && new_pkt.destruct) {
  498. 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
  499. if(t) {
  500. memcpy(t, new_pkt.data, new_pkt.size);
  501. memset(t + new_pkt.size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  502. new_pkt.data = t;
  503. a = 1;
  504. } else
  505. a = AVERROR(ENOMEM);
  506. }
  507. if (a > 0) {
  508. av_free_packet(pkt);
  509. new_pkt.destruct = av_destruct_packet;
  510. } else if (a < 0) {
  511. av_log(NULL, AV_LOG_ERROR, "Failed to open bitstream filter %s for stream %d with codec %s",
  512. bsfc->filter->name, pkt->stream_index,
  513. avctx->codec ? avctx->codec->name : "copy");
  514. print_error("", a);
  515. if (exit_on_error)
  516. exit(1);
  517. }
  518. *pkt = new_pkt;
  519. bsfc = bsfc->next;
  520. }
  521. pkt->stream_index = ost->index;
  522. if (debug_ts) {
  523. av_log(NULL, AV_LOG_INFO, "muxer <- type:%s "
  524. "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s size:%d\n",
  525. av_get_media_type_string(ost->st->codec->codec_type),
  526. av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &ost->st->time_base),
  527. av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &ost->st->time_base),
  528. pkt->size
  529. );
  530. }
  531. ret = av_interleaved_write_frame(s, pkt);
  532. if (ret < 0) {
  533. print_error("av_interleaved_write_frame()", ret);
  534. exit(1);
  535. }
  536. }
  537. static void close_output_stream(OutputStream *ost)
  538. {
  539. OutputFile *of = output_files[ost->file_index];
  540. ost->finished = 1;
  541. if (of->shortest) {
  542. int64_t end = av_rescale_q(ost->sync_opts - ost->first_pts, ost->st->codec->time_base, AV_TIME_BASE_Q);
  543. of->recording_time = FFMIN(of->recording_time, end);
  544. }
  545. }
  546. static int check_recording_time(OutputStream *ost)
  547. {
  548. OutputFile *of = output_files[ost->file_index];
  549. if (of->recording_time != INT64_MAX &&
  550. av_compare_ts(ost->sync_opts - ost->first_pts, ost->st->codec->time_base, of->recording_time,
  551. AV_TIME_BASE_Q) >= 0) {
  552. close_output_stream(ost);
  553. return 0;
  554. }
  555. return 1;
  556. }
  557. static void do_audio_out(AVFormatContext *s, OutputStream *ost,
  558. AVFrame *frame)
  559. {
  560. AVCodecContext *enc = ost->st->codec;
  561. AVPacket pkt;
  562. int got_packet = 0;
  563. av_init_packet(&pkt);
  564. pkt.data = NULL;
  565. pkt.size = 0;
  566. if (!check_recording_time(ost))
  567. return;
  568. if (frame->pts == AV_NOPTS_VALUE || audio_sync_method < 0)
  569. frame->pts = ost->sync_opts;
  570. ost->sync_opts = frame->pts + frame->nb_samples;
  571. av_assert0(pkt.size || !pkt.data);
  572. update_benchmark(NULL);
  573. if (avcodec_encode_audio2(enc, &pkt, frame, &got_packet) < 0) {
  574. av_log(NULL, AV_LOG_FATAL, "Audio encoding failed (avcodec_encode_audio2)\n");
  575. exit(1);
  576. }
  577. update_benchmark("encode_audio %d.%d", ost->file_index, ost->index);
  578. if (got_packet) {
  579. if (pkt.pts != AV_NOPTS_VALUE)
  580. pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
  581. if (pkt.dts != AV_NOPTS_VALUE)
  582. pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
  583. if (pkt.duration > 0)
  584. pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
  585. if (debug_ts) {
  586. av_log(NULL, AV_LOG_INFO, "encoder -> type:audio "
  587. "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
  588. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
  589. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
  590. }
  591. audio_size += pkt.size;
  592. write_frame(s, &pkt, ost);
  593. av_free_packet(&pkt);
  594. }
  595. }
  596. #if FF_API_DEINTERLACE
  597. static void pre_process_video_frame(InputStream *ist, AVPicture *picture, void **bufp)
  598. {
  599. AVCodecContext *dec;
  600. AVPicture *picture2;
  601. AVPicture picture_tmp;
  602. uint8_t *buf = 0;
  603. dec = ist->st->codec;
  604. /* deinterlace : must be done before any resize */
  605. if (FF_API_DEINTERLACE && do_deinterlace) {
  606. int size;
  607. /* create temporary picture */
  608. size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
  609. if (size < 0)
  610. return;
  611. buf = av_malloc(size);
  612. if (!buf)
  613. return;
  614. picture2 = &picture_tmp;
  615. avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
  616. if (avpicture_deinterlace(picture2, picture,
  617. dec->pix_fmt, dec->width, dec->height) < 0) {
  618. /* if error, do not deinterlace */
  619. av_log(NULL, AV_LOG_WARNING, "Deinterlacing failed\n");
  620. av_free(buf);
  621. buf = NULL;
  622. picture2 = picture;
  623. }
  624. } else {
  625. picture2 = picture;
  626. }
  627. if (picture != picture2)
  628. *picture = *picture2;
  629. *bufp = buf;
  630. }
  631. #endif
  632. static void do_subtitle_out(AVFormatContext *s,
  633. OutputStream *ost,
  634. InputStream *ist,
  635. AVSubtitle *sub)
  636. {
  637. int subtitle_out_max_size = 1024 * 1024;
  638. int subtitle_out_size, nb, i;
  639. AVCodecContext *enc;
  640. AVPacket pkt;
  641. int64_t pts;
  642. if (sub->pts == AV_NOPTS_VALUE) {
  643. av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
  644. if (exit_on_error)
  645. exit(1);
  646. return;
  647. }
  648. enc = ost->st->codec;
  649. if (!subtitle_out) {
  650. subtitle_out = av_malloc(subtitle_out_max_size);
  651. }
  652. /* Note: DVB subtitle need one packet to draw them and one other
  653. packet to clear them */
  654. /* XXX: signal it in the codec context ? */
  655. if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
  656. nb = 2;
  657. else
  658. nb = 1;
  659. /* shift timestamp to honor -ss and make check_recording_time() work with -t */
  660. pts = sub->pts - output_files[ost->file_index]->start_time;
  661. for (i = 0; i < nb; i++) {
  662. ost->sync_opts = av_rescale_q(pts, AV_TIME_BASE_Q, enc->time_base);
  663. if (!check_recording_time(ost))
  664. return;
  665. sub->pts = pts;
  666. // start_display_time is required to be 0
  667. sub->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
  668. sub->end_display_time -= sub->start_display_time;
  669. sub->start_display_time = 0;
  670. if (i == 1)
  671. sub->num_rects = 0;
  672. subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
  673. subtitle_out_max_size, sub);
  674. if (subtitle_out_size < 0) {
  675. av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
  676. exit(1);
  677. }
  678. av_init_packet(&pkt);
  679. pkt.data = subtitle_out;
  680. pkt.size = subtitle_out_size;
  681. pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
  682. pkt.duration = av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, ost->st->time_base);
  683. if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
  684. /* XXX: the pts correction is handled here. Maybe handling
  685. it in the codec would be better */
  686. if (i == 0)
  687. pkt.pts += 90 * sub->start_display_time;
  688. else
  689. pkt.pts += 90 * sub->end_display_time;
  690. }
  691. subtitle_size += pkt.size;
  692. write_frame(s, &pkt, ost);
  693. }
  694. }
  695. static void do_video_out(AVFormatContext *s,
  696. OutputStream *ost,
  697. AVFrame *in_picture)
  698. {
  699. int ret, format_video_sync;
  700. AVPacket pkt;
  701. AVCodecContext *enc = ost->st->codec;
  702. int nb_frames, i;
  703. double sync_ipts, delta;
  704. double duration = 0;
  705. int frame_size = 0;
  706. InputStream *ist = NULL;
  707. if (ost->source_index >= 0)
  708. ist = input_streams[ost->source_index];
  709. if(ist && ist->st->start_time != AV_NOPTS_VALUE && ist->st->first_dts != AV_NOPTS_VALUE && ost->frame_rate.num)
  710. duration = 1/(av_q2d(ost->frame_rate) * av_q2d(enc->time_base));
  711. sync_ipts = in_picture->pts;
  712. delta = sync_ipts - ost->sync_opts + duration;
  713. /* by default, we output a single frame */
  714. nb_frames = 1;
  715. format_video_sync = video_sync_method;
  716. if (format_video_sync == VSYNC_AUTO)
  717. format_video_sync = (s->oformat->flags & AVFMT_VARIABLE_FPS) ? ((s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH : VSYNC_VFR) : VSYNC_CFR;
  718. switch (format_video_sync) {
  719. case VSYNC_CFR:
  720. // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
  721. if (delta < -1.1)
  722. nb_frames = 0;
  723. else if (delta > 1.1)
  724. nb_frames = lrintf(delta);
  725. break;
  726. case VSYNC_VFR:
  727. if (delta <= -0.6)
  728. nb_frames = 0;
  729. else if (delta > 0.6)
  730. ost->sync_opts = lrint(sync_ipts);
  731. break;
  732. case VSYNC_DROP:
  733. case VSYNC_PASSTHROUGH:
  734. ost->sync_opts = lrint(sync_ipts);
  735. break;
  736. default:
  737. av_assert0(0);
  738. }
  739. nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
  740. if (nb_frames == 0) {
  741. nb_frames_drop++;
  742. av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");
  743. return;
  744. } else if (nb_frames > 1) {
  745. if (nb_frames > dts_error_threshold * 30) {
  746. av_log(NULL, AV_LOG_ERROR, "%d frame duplication too large, skipping\n", nb_frames - 1);
  747. nb_frames_drop++;
  748. return;
  749. }
  750. nb_frames_dup += nb_frames - 1;
  751. av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);
  752. }
  753. /* duplicates frame if needed */
  754. for (i = 0; i < nb_frames; i++) {
  755. av_init_packet(&pkt);
  756. pkt.data = NULL;
  757. pkt.size = 0;
  758. in_picture->pts = ost->sync_opts;
  759. if (!check_recording_time(ost))
  760. return;
  761. if (s->oformat->flags & AVFMT_RAWPICTURE &&
  762. enc->codec->id == AV_CODEC_ID_RAWVIDEO) {
  763. /* raw pictures are written as AVPicture structure to
  764. avoid any copies. We support temporarily the older
  765. method. */
  766. enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
  767. enc->coded_frame->top_field_first = in_picture->top_field_first;
  768. if (enc->coded_frame->interlaced_frame)
  769. enc->field_order = enc->coded_frame->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
  770. else
  771. enc->field_order = AV_FIELD_PROGRESSIVE;
  772. pkt.data = (uint8_t *)in_picture;
  773. pkt.size = sizeof(AVPicture);
  774. pkt.pts = av_rescale_q(in_picture->pts, enc->time_base, ost->st->time_base);
  775. pkt.flags |= AV_PKT_FLAG_KEY;
  776. video_size += pkt.size;
  777. write_frame(s, &pkt, ost);
  778. } else {
  779. int got_packet, forced_keyframe = 0;
  780. AVFrame big_picture;
  781. double pts_time;
  782. big_picture = *in_picture;
  783. /* better than nothing: use input picture interlaced
  784. settings */
  785. big_picture.interlaced_frame = in_picture->interlaced_frame;
  786. if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)) {
  787. if (ost->top_field_first == -1)
  788. big_picture.top_field_first = in_picture->top_field_first;
  789. else
  790. big_picture.top_field_first = !!ost->top_field_first;
  791. }
  792. if (big_picture.interlaced_frame) {
  793. if (enc->codec->id == AV_CODEC_ID_MJPEG)
  794. enc->field_order = big_picture.top_field_first ? AV_FIELD_TT:AV_FIELD_BB;
  795. else
  796. enc->field_order = big_picture.top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
  797. } else
  798. enc->field_order = AV_FIELD_PROGRESSIVE;
  799. big_picture.quality = ost->st->codec->global_quality;
  800. if (!enc->me_threshold)
  801. big_picture.pict_type = 0;
  802. pts_time = big_picture.pts != AV_NOPTS_VALUE ?
  803. big_picture.pts * av_q2d(enc->time_base) : NAN;
  804. if (ost->forced_kf_index < ost->forced_kf_count &&
  805. big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
  806. ost->forced_kf_index++;
  807. forced_keyframe = 1;
  808. } else if (ost->forced_keyframes_pexpr) {
  809. double res;
  810. ost->forced_keyframes_expr_const_values[FKF_T] = pts_time;
  811. res = av_expr_eval(ost->forced_keyframes_pexpr,
  812. ost->forced_keyframes_expr_const_values, NULL);
  813. av_dlog(NULL, "force_key_frame: n:%f n_forced:%f prev_forced_n:%f t:%f prev_forced_t:%f -> res:%f\n",
  814. ost->forced_keyframes_expr_const_values[FKF_N],
  815. ost->forced_keyframes_expr_const_values[FKF_N_FORCED],
  816. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N],
  817. ost->forced_keyframes_expr_const_values[FKF_T],
  818. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T],
  819. res);
  820. if (res) {
  821. forced_keyframe = 1;
  822. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] =
  823. ost->forced_keyframes_expr_const_values[FKF_N];
  824. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] =
  825. ost->forced_keyframes_expr_const_values[FKF_T];
  826. ost->forced_keyframes_expr_const_values[FKF_N_FORCED] += 1;
  827. }
  828. ost->forced_keyframes_expr_const_values[FKF_N] += 1;
  829. }
  830. if (forced_keyframe) {
  831. big_picture.pict_type = AV_PICTURE_TYPE_I;
  832. av_log(NULL, AV_LOG_DEBUG, "Forced keyframe at time %f\n", pts_time);
  833. }
  834. update_benchmark(NULL);
  835. ret = avcodec_encode_video2(enc, &pkt, &big_picture, &got_packet);
  836. update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
  837. if (ret < 0) {
  838. av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
  839. exit(1);
  840. }
  841. if (got_packet) {
  842. if (pkt.pts == AV_NOPTS_VALUE && !(enc->codec->capabilities & CODEC_CAP_DELAY))
  843. pkt.pts = ost->sync_opts;
  844. if (pkt.pts != AV_NOPTS_VALUE)
  845. pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
  846. if (pkt.dts != AV_NOPTS_VALUE)
  847. pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
  848. if (debug_ts) {
  849. av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
  850. "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
  851. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
  852. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
  853. }
  854. frame_size = pkt.size;
  855. video_size += pkt.size;
  856. write_frame(s, &pkt, ost);
  857. av_free_packet(&pkt);
  858. /* if two pass, output log */
  859. if (ost->logfile && enc->stats_out) {
  860. fprintf(ost->logfile, "%s", enc->stats_out);
  861. }
  862. }
  863. }
  864. ost->sync_opts++;
  865. /*
  866. * For video, number of frames in == number of packets out.
  867. * But there may be reordering, so we can't throw away frames on encoder
  868. * flush, we need to limit them here, before they go into encoder.
  869. */
  870. ost->frame_number++;
  871. }
  872. if (vstats_filename && frame_size)
  873. do_video_stats(ost, frame_size);
  874. }
  875. static double psnr(double d)
  876. {
  877. return -10.0 * log(d) / log(10.0);
  878. }
  879. static void do_video_stats(OutputStream *ost, int frame_size)
  880. {
  881. AVCodecContext *enc;
  882. int frame_number;
  883. double ti1, bitrate, avg_bitrate;
  884. /* this is executed just the first time do_video_stats is called */
  885. if (!vstats_file) {
  886. vstats_file = fopen(vstats_filename, "w");
  887. if (!vstats_file) {
  888. perror("fopen");
  889. exit(1);
  890. }
  891. }
  892. enc = ost->st->codec;
  893. if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  894. frame_number = ost->st->nb_frames;
  895. fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality / (float)FF_QP2LAMBDA);
  896. if (enc->flags&CODEC_FLAG_PSNR)
  897. fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
  898. fprintf(vstats_file,"f_size= %6d ", frame_size);
  899. /* compute pts value */
  900. ti1 = ost->st->pts.val * av_q2d(enc->time_base);
  901. if (ti1 < 0.01)
  902. ti1 = 0.01;
  903. bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
  904. avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
  905. fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
  906. (double)video_size / 1024, ti1, bitrate, avg_bitrate);
  907. fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
  908. }
  909. }
  910. /**
  911. * Get and encode new output from any of the filtergraphs, without causing
  912. * activity.
  913. *
  914. * @return 0 for success, <0 for severe errors
  915. */
  916. static int reap_filters(void)
  917. {
  918. AVFilterBufferRef *picref;
  919. AVFrame *filtered_frame = NULL;
  920. int i;
  921. int64_t frame_pts;
  922. /* Reap all buffers present in the buffer sinks */
  923. for (i = 0; i < nb_output_streams; i++) {
  924. OutputStream *ost = output_streams[i];
  925. OutputFile *of = output_files[ost->file_index];
  926. int ret = 0;
  927. if (!ost->filter)
  928. continue;
  929. if (!ost->filtered_frame && !(ost->filtered_frame = avcodec_alloc_frame())) {
  930. return AVERROR(ENOMEM);
  931. } else
  932. avcodec_get_frame_defaults(ost->filtered_frame);
  933. filtered_frame = ost->filtered_frame;
  934. while (1) {
  935. ret = av_buffersink_get_buffer_ref(ost->filter->filter, &picref,
  936. AV_BUFFERSINK_FLAG_NO_REQUEST);
  937. if (ret < 0) {
  938. if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) {
  939. char buf[256];
  940. av_strerror(ret, buf, sizeof(buf));
  941. av_log(NULL, AV_LOG_WARNING,
  942. "Error in av_buffersink_get_buffer_ref(): %s\n", buf);
  943. }
  944. break;
  945. }
  946. frame_pts = AV_NOPTS_VALUE;
  947. if (picref->pts != AV_NOPTS_VALUE) {
  948. filtered_frame->pts = frame_pts = av_rescale_q(picref->pts,
  949. ost->filter->filter->inputs[0]->time_base,
  950. ost->st->codec->time_base) -
  951. av_rescale_q(of->start_time,
  952. AV_TIME_BASE_Q,
  953. ost->st->codec->time_base);
  954. if (of->start_time && filtered_frame->pts < 0) {
  955. avfilter_unref_buffer(picref);
  956. continue;
  957. }
  958. }
  959. //if (ost->source_index >= 0)
  960. // *filtered_frame= *input_streams[ost->source_index]->decoded_frame; //for me_threshold
  961. switch (ost->filter->filter->inputs[0]->type) {
  962. case AVMEDIA_TYPE_VIDEO:
  963. avfilter_copy_buf_props(filtered_frame, picref);
  964. filtered_frame->pts = frame_pts;
  965. if (!ost->frame_aspect_ratio)
  966. ost->st->codec->sample_aspect_ratio = picref->video->sample_aspect_ratio;
  967. do_video_out(of->ctx, ost, filtered_frame);
  968. break;
  969. case AVMEDIA_TYPE_AUDIO:
  970. avfilter_copy_buf_props(filtered_frame, picref);
  971. filtered_frame->pts = frame_pts;
  972. if (!(ost->st->codec->codec->capabilities & CODEC_CAP_PARAM_CHANGE) &&
  973. ost->st->codec->channels != av_frame_get_channels(filtered_frame)) {
  974. av_log(NULL, AV_LOG_ERROR,
  975. "Audio filter graph output is not normalized and encoder does not support parameter changes\n");
  976. break;
  977. }
  978. do_audio_out(of->ctx, ost, filtered_frame);
  979. break;
  980. default:
  981. // TODO support subtitle filters
  982. av_assert0(0);
  983. }
  984. avfilter_unref_buffer(picref);
  985. }
  986. }
  987. return 0;
  988. }
  989. static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
  990. {
  991. char buf[1024];
  992. AVBPrint buf_script;
  993. OutputStream *ost;
  994. AVFormatContext *oc;
  995. int64_t total_size;
  996. AVCodecContext *enc;
  997. int frame_number, vid, i;
  998. double bitrate;
  999. int64_t pts = INT64_MIN;
  1000. static int64_t last_time = -1;
  1001. static int qp_histogram[52];
  1002. int hours, mins, secs, us;
  1003. if (!print_stats && !is_last_report && !progress_avio)
  1004. return;
  1005. if (!is_last_report) {
  1006. if (last_time == -1) {
  1007. last_time = cur_time;
  1008. return;
  1009. }
  1010. if ((cur_time - last_time) < 500000)
  1011. return;
  1012. last_time = cur_time;
  1013. }
  1014. oc = output_files[0]->ctx;
  1015. total_size = avio_size(oc->pb);
  1016. if (total_size <= 0) // FIXME improve avio_size() so it works with non seekable output too
  1017. total_size = avio_tell(oc->pb);
  1018. buf[0] = '\0';
  1019. vid = 0;
  1020. av_bprint_init(&buf_script, 0, 1);
  1021. for (i = 0; i < nb_output_streams; i++) {
  1022. float q = -1;
  1023. ost = output_streams[i];
  1024. enc = ost->st->codec;
  1025. if (!ost->stream_copy && enc->coded_frame)
  1026. q = enc->coded_frame->quality / (float)FF_QP2LAMBDA;
  1027. if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  1028. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
  1029. av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
  1030. ost->file_index, ost->index, q);
  1031. }
  1032. if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  1033. float fps, t = (cur_time-timer_start) / 1000000.0;
  1034. frame_number = ost->frame_number;
  1035. fps = t > 1 ? frame_number / t : 0;
  1036. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3.*f q=%3.1f ",
  1037. frame_number, fps < 9.95, fps, q);
  1038. av_bprintf(&buf_script, "frame=%d\n", frame_number);
  1039. av_bprintf(&buf_script, "fps=%.1f\n", fps);
  1040. av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
  1041. ost->file_index, ost->index, q);
  1042. if (is_last_report)
  1043. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
  1044. if (qp_hist) {
  1045. int j;
  1046. int qp = lrintf(q);
  1047. if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
  1048. qp_histogram[qp]++;
  1049. for (j = 0; j < 32; j++)
  1050. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log2(qp_histogram[j] + 1)));
  1051. }
  1052. if ((enc->flags&CODEC_FLAG_PSNR) && (enc->coded_frame || is_last_report)) {
  1053. int j;
  1054. double error, error_sum = 0;
  1055. double scale, scale_sum = 0;
  1056. double p;
  1057. char type[3] = { 'Y','U','V' };
  1058. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
  1059. for (j = 0; j < 3; j++) {
  1060. if (is_last_report) {
  1061. error = enc->error[j];
  1062. scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
  1063. } else {
  1064. error = enc->coded_frame->error[j];
  1065. scale = enc->width * enc->height * 255.0 * 255.0;
  1066. }
  1067. if (j)
  1068. scale /= 4;
  1069. error_sum += error;
  1070. scale_sum += scale;
  1071. p = psnr(error / scale);
  1072. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], p);
  1073. av_bprintf(&buf_script, "stream_%d_%d_psnr_%c=%2.2f\n",
  1074. ost->file_index, ost->index, type[j] | 32, p);
  1075. }
  1076. p = psnr(error_sum / scale_sum);
  1077. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
  1078. av_bprintf(&buf_script, "stream_%d_%d_psnr_all=%2.2f\n",
  1079. ost->file_index, ost->index, p);
  1080. }
  1081. vid = 1;
  1082. }
  1083. /* compute min output value */
  1084. if ((is_last_report || !ost->finished) && ost->st->pts.val != AV_NOPTS_VALUE)
  1085. pts = FFMAX(pts, av_rescale_q(ost->st->pts.val,
  1086. ost->st->time_base, AV_TIME_BASE_Q));
  1087. }
  1088. secs = pts / AV_TIME_BASE;
  1089. us = pts % AV_TIME_BASE;
  1090. mins = secs / 60;
  1091. secs %= 60;
  1092. hours = mins / 60;
  1093. mins %= 60;
  1094. bitrate = pts && total_size >= 0 ? total_size * 8 / (pts / 1000.0) : -1;
  1095. if (total_size < 0) snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  1096. "size=N/A time=");
  1097. else snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  1098. "size=%8.0fkB time=", total_size / 1024.0);
  1099. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  1100. "%02d:%02d:%02d.%02d ", hours, mins, secs,
  1101. (100 * us) / AV_TIME_BASE);
  1102. if (bitrate < 0) snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  1103. "bitrate=N/A");
  1104. else snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  1105. "bitrate=%6.1fkbits/s", bitrate);
  1106. if (total_size < 0) av_bprintf(&buf_script, "total_size=N/A\n");
  1107. else av_bprintf(&buf_script, "total_size=%"PRId64"\n", total_size);
  1108. av_bprintf(&buf_script, "out_time_ms=%"PRId64"\n", pts);
  1109. av_bprintf(&buf_script, "out_time=%02d:%02d:%02d.%06d\n",
  1110. hours, mins, secs, us);
  1111. if (nb_frames_dup || nb_frames_drop)
  1112. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
  1113. nb_frames_dup, nb_frames_drop);
  1114. av_bprintf(&buf_script, "dup_frames=%d\n", nb_frames_dup);
  1115. av_bprintf(&buf_script, "drop_frames=%d\n", nb_frames_drop);
  1116. if (print_stats || is_last_report) {
  1117. if (print_stats==1 && AV_LOG_INFO > av_log_get_level()) {
  1118. fprintf(stderr, "%s \r", buf);
  1119. } else
  1120. av_log(NULL, AV_LOG_INFO, "%s \r", buf);
  1121. fflush(stderr);
  1122. }
  1123. if (progress_avio) {
  1124. av_bprintf(&buf_script, "progress=%s\n",
  1125. is_last_report ? "end" : "continue");
  1126. avio_write(progress_avio, buf_script.str,
  1127. FFMIN(buf_script.len, buf_script.size - 1));
  1128. avio_flush(progress_avio);
  1129. av_bprint_finalize(&buf_script, NULL);
  1130. if (is_last_report) {
  1131. avio_close(progress_avio);
  1132. progress_avio = NULL;
  1133. }
  1134. }
  1135. if (is_last_report) {
  1136. int64_t raw= audio_size + video_size + subtitle_size + extra_size;
  1137. av_log(NULL, AV_LOG_INFO, "\n");
  1138. av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB subtitle:%1.0f global headers:%1.0fkB muxing overhead %f%%\n",
  1139. video_size / 1024.0,
  1140. audio_size / 1024.0,
  1141. subtitle_size / 1024.0,
  1142. extra_size / 1024.0,
  1143. 100.0 * (total_size - raw) / raw
  1144. );
  1145. if(video_size + audio_size + subtitle_size + extra_size == 0){
  1146. av_log(NULL, AV_LOG_WARNING, "Output file is empty, nothing was encoded (check -ss / -t / -frames parameters if used)\n");
  1147. }
  1148. }
  1149. }
  1150. static void flush_encoders(void)
  1151. {
  1152. int i, ret;
  1153. for (i = 0; i < nb_output_streams; i++) {
  1154. OutputStream *ost = output_streams[i];
  1155. AVCodecContext *enc = ost->st->codec;
  1156. AVFormatContext *os = output_files[ost->file_index]->ctx;
  1157. int stop_encoding = 0;
  1158. if (!ost->encoding_needed)
  1159. continue;
  1160. if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
  1161. continue;
  1162. if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == AV_CODEC_ID_RAWVIDEO)
  1163. continue;
  1164. for (;;) {
  1165. int (*encode)(AVCodecContext*, AVPacket*, const AVFrame*, int*) = NULL;
  1166. const char *desc;
  1167. int64_t *size;
  1168. switch (ost->st->codec->codec_type) {
  1169. case AVMEDIA_TYPE_AUDIO:
  1170. encode = avcodec_encode_audio2;
  1171. desc = "Audio";
  1172. size = &audio_size;
  1173. break;
  1174. case AVMEDIA_TYPE_VIDEO:
  1175. encode = avcodec_encode_video2;
  1176. desc = "Video";
  1177. size = &video_size;
  1178. break;
  1179. default:
  1180. stop_encoding = 1;
  1181. }
  1182. if (encode) {
  1183. AVPacket pkt;
  1184. int got_packet;
  1185. av_init_packet(&pkt);
  1186. pkt.data = NULL;
  1187. pkt.size = 0;
  1188. update_benchmark(NULL);
  1189. ret = encode(enc, &pkt, NULL, &got_packet);
  1190. update_benchmark("flush %s %d.%d", desc, ost->file_index, ost->index);
  1191. if (ret < 0) {
  1192. av_log(NULL, AV_LOG_FATAL, "%s encoding failed\n", desc);
  1193. exit(1);
  1194. }
  1195. *size += pkt.size;
  1196. if (ost->logfile && enc->stats_out) {
  1197. fprintf(ost->logfile, "%s", enc->stats_out);
  1198. }
  1199. if (!got_packet) {
  1200. stop_encoding = 1;
  1201. break;
  1202. }
  1203. if (pkt.pts != AV_NOPTS_VALUE)
  1204. pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
  1205. if (pkt.dts != AV_NOPTS_VALUE)
  1206. pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
  1207. if (pkt.duration > 0)
  1208. pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
  1209. write_frame(os, &pkt, ost);
  1210. if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && vstats_filename) {
  1211. do_video_stats(ost, pkt.size);
  1212. }
  1213. }
  1214. if (stop_encoding)
  1215. break;
  1216. }
  1217. }
  1218. }
  1219. /*
  1220. * Check whether a packet from ist should be written into ost at this time
  1221. */
  1222. static int check_output_constraints(InputStream *ist, OutputStream *ost)
  1223. {
  1224. OutputFile *of = output_files[ost->file_index];
  1225. int ist_index = input_files[ist->file_index]->ist_index + ist->st->index;
  1226. if (ost->source_index != ist_index)
  1227. return 0;
  1228. if (of->start_time && ist->pts < of->start_time)
  1229. return 0;
  1230. return 1;
  1231. }
  1232. static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
  1233. {
  1234. OutputFile *of = output_files[ost->file_index];
  1235. int64_t ost_tb_start_time = av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);
  1236. AVPicture pict;
  1237. AVPacket opkt;
  1238. av_init_packet(&opkt);
  1239. if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
  1240. !ost->copy_initial_nonkeyframes)
  1241. return;
  1242. if (!ost->frame_number && ist->pts < of->start_time &&
  1243. !ost->copy_prior_start)
  1244. return;
  1245. if (of->recording_time != INT64_MAX &&
  1246. ist->pts >= of->recording_time + of->start_time) {
  1247. close_output_stream(ost);
  1248. return;
  1249. }
  1250. /* force the input stream PTS */
  1251. if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
  1252. audio_size += pkt->size;
  1253. else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  1254. video_size += pkt->size;
  1255. ost->sync_opts++;
  1256. } else if (ost->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  1257. subtitle_size += pkt->size;
  1258. }
  1259. if (pkt->pts != AV_NOPTS_VALUE)
  1260. opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
  1261. else
  1262. opkt.pts = AV_NOPTS_VALUE;
  1263. if (pkt->dts == AV_NOPTS_VALUE)
  1264. opkt.dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ost->st->time_base);
  1265. else
  1266. opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
  1267. opkt.dts -= ost_tb_start_time;
  1268. if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->dts != AV_NOPTS_VALUE) {
  1269. int duration = av_get_audio_frame_duration(ist->st->codec, pkt->size);
  1270. if(!duration)
  1271. duration = ist->st->codec->frame_size;
  1272. opkt.dts = opkt.pts = av_rescale_delta(ist->st->time_base, pkt->dts,
  1273. (AVRational){1, ist->st->codec->sample_rate}, duration, &ist->filter_in_rescale_delta_last,
  1274. ost->st->time_base) - ost_tb_start_time;
  1275. }
  1276. opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
  1277. opkt.flags = pkt->flags;
  1278. // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
  1279. if ( ost->st->codec->codec_id != AV_CODEC_ID_H264
  1280. && ost->st->codec->codec_id != AV_CODEC_ID_MPEG1VIDEO
  1281. && ost->st->codec->codec_id != AV_CODEC_ID_MPEG2VIDEO
  1282. && ost->st->codec->codec_id != AV_CODEC_ID_VC1
  1283. ) {
  1284. if (av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY))
  1285. opkt.destruct = av_destruct_packet;
  1286. } else {
  1287. opkt.data = pkt->data;
  1288. opkt.size = pkt->size;
  1289. }
  1290. if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (of->ctx->oformat->flags & AVFMT_RAWPICTURE)) {
  1291. /* store AVPicture in AVPacket, as expected by the output format */
  1292. avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
  1293. opkt.data = (uint8_t *)&pict;
  1294. opkt.size = sizeof(AVPicture);
  1295. opkt.flags |= AV_PKT_FLAG_KEY;
  1296. }
  1297. write_frame(of->ctx, &opkt, ost);
  1298. ost->st->codec->frame_number++;
  1299. }
  1300. static void rate_emu_sleep(InputStream *ist)
  1301. {
  1302. if (input_files[ist->file_index]->rate_emu) {
  1303. int64_t pts = av_rescale(ist->dts, 1000000, AV_TIME_BASE);
  1304. int64_t now = av_gettime() - ist->start;
  1305. if (pts > now)
  1306. av_usleep(pts - now);
  1307. }
  1308. }
  1309. int guess_input_channel_layout(InputStream *ist)
  1310. {
  1311. AVCodecContext *dec = ist->st->codec;
  1312. if (!dec->channel_layout) {
  1313. char layout_name[256];
  1314. if (dec->channels > ist->guess_layout_max)
  1315. return 0;
  1316. dec->channel_layout = av_get_default_channel_layout(dec->channels);
  1317. if (!dec->channel_layout)
  1318. return 0;
  1319. av_get_channel_layout_string(layout_name, sizeof(layout_name),
  1320. dec->channels, dec->channel_layout);
  1321. av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Input Stream "
  1322. "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
  1323. }
  1324. return 1;
  1325. }
  1326. static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
  1327. {
  1328. AVFrame *decoded_frame;
  1329. AVCodecContext *avctx = ist->st->codec;
  1330. int i, ret, resample_changed;
  1331. AVRational decoded_frame_tb;
  1332. if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
  1333. return AVERROR(ENOMEM);
  1334. decoded_frame = ist->decoded_frame;
  1335. update_benchmark(NULL);
  1336. ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
  1337. update_benchmark("decode_audio %d.%d", ist->file_index, ist->st->index);
  1338. if (ret >= 0 && avctx->sample_rate <= 0) {
  1339. av_log(avctx, AV_LOG_ERROR, "Sample rate %d invalid\n", avctx->sample_rate);
  1340. ret = AVERROR_INVALIDDATA;
  1341. }
  1342. if (!*got_output || ret < 0) {
  1343. if (!pkt->size) {
  1344. for (i = 0; i < ist->nb_filters; i++)
  1345. av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
  1346. }
  1347. return ret;
  1348. }
  1349. #if 1
  1350. /* increment next_dts to use for the case where the input stream does not
  1351. have timestamps or there are multiple frames in the packet */
  1352. ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
  1353. avctx->sample_rate;
  1354. ist->next_dts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
  1355. avctx->sample_rate;
  1356. #endif
  1357. rate_emu_sleep(ist);
  1358. resample_changed = ist->resample_sample_fmt != decoded_frame->format ||
  1359. ist->resample_channels != avctx->channels ||
  1360. ist->resample_channel_layout != decoded_frame->channel_layout ||
  1361. ist->resample_sample_rate != decoded_frame->sample_rate;
  1362. if (resample_changed) {
  1363. char layout1[64], layout2[64];
  1364. if (!guess_input_channel_layout(ist)) {
  1365. av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
  1366. "layout for Input Stream #%d.%d\n", ist->file_index,
  1367. ist->st->index);
  1368. exit(1);
  1369. }
  1370. decoded_frame->channel_layout = avctx->channel_layout;
  1371. av_get_channel_layout_string(layout1, sizeof(layout1), ist->resample_channels,
  1372. ist->resample_channel_layout);
  1373. av_get_channel_layout_string(layout2, sizeof(layout2), avctx->channels,
  1374. decoded_frame->channel_layout);
  1375. av_log(NULL, AV_LOG_INFO,
  1376. "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",
  1377. ist->file_index, ist->st->index,
  1378. ist->resample_sample_rate, av_get_sample_fmt_name(ist->resample_sample_fmt),
  1379. ist->resample_channels, layout1,
  1380. decoded_frame->sample_rate, av_get_sample_fmt_name(decoded_frame->format),
  1381. avctx->channels, layout2);
  1382. ist->resample_sample_fmt = decoded_frame->format;
  1383. ist->resample_sample_rate = decoded_frame->sample_rate;
  1384. ist->resample_channel_layout = decoded_frame->channel_layout;
  1385. ist->resample_channels = avctx->channels;
  1386. for (i = 0; i < nb_filtergraphs; i++)
  1387. if (ist_in_filtergraph(filtergraphs[i], ist)) {
  1388. FilterGraph *fg = filtergraphs[i];
  1389. int j;
  1390. if (configure_filtergraph(fg) < 0) {
  1391. av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
  1392. exit(1);
  1393. }
  1394. for (j = 0; j < fg->nb_outputs; j++) {
  1395. OutputStream *ost = fg->outputs[j]->ost;
  1396. if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
  1397. !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
  1398. av_buffersink_set_frame_size(ost->filter->filter,
  1399. ost->st->codec->frame_size);
  1400. }
  1401. }
  1402. }
  1403. /* if the decoder provides a pts, use it instead of the last packet pts.
  1404. the decoder could be delaying output by a packet or more. */
  1405. if (decoded_frame->pts != AV_NOPTS_VALUE) {
  1406. ist->dts = ist->next_dts = ist->pts = ist->next_pts = av_rescale_q(decoded_frame->pts, avctx->time_base, AV_TIME_BASE_Q);
  1407. decoded_frame_tb = avctx->time_base;
  1408. } else if (decoded_frame->pkt_pts != AV_NOPTS_VALUE) {
  1409. decoded_frame->pts = decoded_frame->pkt_pts;
  1410. pkt->pts = AV_NOPTS_VALUE;
  1411. decoded_frame_tb = ist->st->time_base;
  1412. } else if (pkt->pts != AV_NOPTS_VALUE) {
  1413. decoded_frame->pts = pkt->pts;
  1414. pkt->pts = AV_NOPTS_VALUE;
  1415. decoded_frame_tb = ist->st->time_base;
  1416. }else {
  1417. decoded_frame->pts = ist->dts;
  1418. decoded_frame_tb = AV_TIME_BASE_Q;
  1419. }
  1420. if (decoded_frame->pts != AV_NOPTS_VALUE)
  1421. decoded_frame->pts = av_rescale_delta(decoded_frame_tb, decoded_frame->pts,
  1422. (AVRational){1, ist->st->codec->sample_rate}, decoded_frame->nb_samples, &ist->filter_in_rescale_delta_last,
  1423. (AVRational){1, ist->st->codec->sample_rate});
  1424. for (i = 0; i < ist->nb_filters; i++)
  1425. av_buffersrc_add_frame(ist->filters[i]->filter, decoded_frame,
  1426. AV_BUFFERSRC_FLAG_PUSH);
  1427. decoded_frame->pts = AV_NOPTS_VALUE;
  1428. return ret;
  1429. }
  1430. static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output)
  1431. {
  1432. AVFrame *decoded_frame;
  1433. void *buffer_to_free = NULL;
  1434. int i, ret = 0, resample_changed;
  1435. int64_t best_effort_timestamp;
  1436. AVRational *frame_sample_aspect;
  1437. if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
  1438. return AVERROR(ENOMEM);
  1439. decoded_frame = ist->decoded_frame;
  1440. pkt->dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ist->st->time_base);
  1441. update_benchmark(NULL);
  1442. ret = avcodec_decode_video2(ist->st->codec,
  1443. decoded_frame, got_output, pkt);
  1444. update_benchmark("decode_video %d.%d", ist->file_index, ist->st->index);
  1445. if (!*got_output || ret < 0) {
  1446. if (!pkt->size) {
  1447. for (i = 0; i < ist->nb_filters; i++)
  1448. av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
  1449. }
  1450. return ret;
  1451. }
  1452. if(ist->top_field_first>=0)
  1453. decoded_frame->top_field_first = ist->top_field_first;
  1454. best_effort_timestamp= av_frame_get_best_effort_timestamp(decoded_frame);
  1455. if(best_effort_timestamp != AV_NOPTS_VALUE)
  1456. ist->next_pts = ist->pts = av_rescale_q(decoded_frame->pts = best_effort_timestamp, ist->st->time_base, AV_TIME_BASE_Q);
  1457. if (debug_ts) {
  1458. av_log(NULL, AV_LOG_INFO, "decoder -> ist_index:%d type:video "
  1459. "frame_pts:%s frame_pts_time:%s best_effort_ts:%"PRId64" best_effort_ts_time:%s keyframe:%d frame_type:%d \n",
  1460. ist->st->index, av_ts2str(decoded_frame->pts),
  1461. av_ts2timestr(decoded_frame->pts, &ist->st->time_base),
  1462. best_effort_timestamp,
  1463. av_ts2timestr(best_effort_timestamp, &ist->st->time_base),
  1464. decoded_frame->key_frame, decoded_frame->pict_type);
  1465. }
  1466. pkt->size = 0;
  1467. #if FF_API_DEINTERLACE
  1468. pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);
  1469. #endif
  1470. rate_emu_sleep(ist);
  1471. if (ist->st->sample_aspect_ratio.num)
  1472. decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
  1473. resample_changed = ist->resample_width != decoded_frame->width ||
  1474. ist->resample_height != decoded_frame->height ||
  1475. ist->resample_pix_fmt != decoded_frame->format;
  1476. if (resample_changed) {
  1477. av_log(NULL, AV_LOG_INFO,
  1478. "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
  1479. ist->file_index, ist->st->index,
  1480. ist->resample_width, ist->resample_height, av_get_pix_fmt_name(ist->resample_pix_fmt),
  1481. decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
  1482. ist->resample_width = decoded_frame->width;
  1483. ist->resample_height = decoded_frame->height;
  1484. ist->resample_pix_fmt = decoded_frame->format;
  1485. for (i = 0; i < nb_filtergraphs; i++) {
  1486. if (ist_in_filtergraph(filtergraphs[i], ist) && ist->reinit_filters &&
  1487. configure_filtergraph(filtergraphs[i]) < 0) {
  1488. av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
  1489. exit(1);
  1490. }
  1491. }
  1492. }
  1493. frame_sample_aspect= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "sample_aspect_ratio");
  1494. for (i = 0; i < ist->nb_filters; i++) {
  1495. int changed = ist->st->codec->width != ist->filters[i]->filter->outputs[0]->w
  1496. || ist->st->codec->height != ist->filters[i]->filter->outputs[0]->h
  1497. || ist->st->codec->pix_fmt != ist->filters[i]->filter->outputs[0]->format;
  1498. if (!frame_sample_aspect->num)
  1499. *frame_sample_aspect = ist->st->sample_aspect_ratio;
  1500. if (ist->dr1 && decoded_frame->type==FF_BUFFER_TYPE_USER && !changed) {
  1501. FrameBuffer *buf = decoded_frame->opaque;
  1502. AVFilterBufferRef *fb = avfilter_get_video_buffer_ref_from_arrays(
  1503. decoded_frame->data, decoded_frame->linesize,
  1504. AV_PERM_READ | AV_PERM_PRESERVE,
  1505. ist->st->codec->width, ist->st->codec->height,
  1506. ist->st->codec->pix_fmt);
  1507. avfilter_copy_frame_props(fb, decoded_frame);
  1508. fb->buf->priv = buf;
  1509. fb->buf->free = filter_release_buffer;
  1510. av_assert0(buf->refcount>0);
  1511. buf->refcount++;
  1512. av_buffersrc_add_ref(ist->filters[i]->filter, fb,
  1513. AV_BUFFERSRC_FLAG_NO_CHECK_FORMAT |
  1514. AV_BUFFERSRC_FLAG_NO_COPY |
  1515. AV_BUFFERSRC_FLAG_PUSH);
  1516. } else
  1517. if(av_buffersrc_add_frame(ist->filters[i]->filter, decoded_frame, AV_BUFFERSRC_FLAG_PUSH)<0) {
  1518. av_log(NULL, AV_LOG_FATAL, "Failed to inject frame into filter network\n");
  1519. exit(1);
  1520. }
  1521. }
  1522. av_free(buffer_to_free);
  1523. return ret;
  1524. }
  1525. static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
  1526. {
  1527. AVSubtitle subtitle;
  1528. int i, ret = avcodec_decode_subtitle2(ist->st->codec,
  1529. &subtitle, got_output, pkt);
  1530. if (ret < 0 || !*got_output) {
  1531. if (!pkt->size)
  1532. sub2video_flush(ist);
  1533. return ret;
  1534. }
  1535. if (ist->fix_sub_duration) {
  1536. if (ist->prev_sub.got_output) {
  1537. int end = av_rescale(subtitle.pts - ist->prev_sub.subtitle.pts,
  1538. 1000, AV_TIME_BASE);
  1539. if (end < ist->prev_sub.subtitle.end_display_time) {
  1540. av_log(ist->st->codec, AV_LOG_DEBUG,
  1541. "Subtitle duration reduced from %d to %d\n",
  1542. ist->prev_sub.subtitle.end_display_time, end);
  1543. ist->prev_sub.subtitle.end_display_time = end;
  1544. }
  1545. }
  1546. FFSWAP(int, *got_output, ist->prev_sub.got_output);
  1547. FFSWAP(int, ret, ist->prev_sub.ret);
  1548. FFSWAP(AVSubtitle, subtitle, ist->prev_sub.subtitle);
  1549. }
  1550. sub2video_update(ist, &subtitle);
  1551. if (!*got_output || !subtitle.num_rects)
  1552. return ret;
  1553. rate_emu_sleep(ist);
  1554. for (i = 0; i < nb_output_streams; i++) {
  1555. OutputStream *ost = output_streams[i];
  1556. if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
  1557. continue;
  1558. do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle);
  1559. }
  1560. avsubtitle_free(&subtitle);
  1561. return ret;
  1562. }
  1563. /* pkt = NULL means EOF (needed to flush decoder buffers) */
  1564. static int output_packet(InputStream *ist, const AVPacket *pkt)
  1565. {
  1566. int ret = 0, i;
  1567. int got_output;
  1568. AVPacket avpkt;
  1569. if (!ist->saw_first_ts) {
  1570. ist->dts = ist->st->avg_frame_rate.num ? - ist->st->codec->has_b_frames * AV_TIME_BASE / av_q2d(ist->st->avg_frame_rate) : 0;
  1571. ist->pts = 0;
  1572. if (pkt != NULL && pkt->pts != AV_NOPTS_VALUE && !ist->decoding_needed) {
  1573. ist->dts += av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
  1574. ist->pts = ist->dts; //unused but better to set it to a value thats not totally wrong
  1575. }
  1576. ist->saw_first_ts = 1;
  1577. }
  1578. if (ist->next_dts == AV_NOPTS_VALUE)
  1579. ist->next_dts = ist->dts;
  1580. if (ist->next_pts == AV_NOPTS_VALUE)
  1581. ist->next_pts = ist->pts;
  1582. if (pkt == NULL) {
  1583. /* EOF handling */
  1584. av_init_packet(&avpkt);
  1585. avpkt.data = NULL;
  1586. avpkt.size = 0;
  1587. goto handle_eof;
  1588. } else {
  1589. avpkt = *pkt;
  1590. }
  1591. if (pkt->dts != AV_NOPTS_VALUE) {
  1592. ist->next_dts = ist->dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
  1593. if (ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)
  1594. ist->next_pts = ist->pts = ist->dts;
  1595. }
  1596. // while we have more to decode or while the decoder did output something on EOF
  1597. while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
  1598. int duration;
  1599. handle_eof:
  1600. ist->pts = ist->next_pts;
  1601. ist->dts = ist->next_dts;
  1602. if (avpkt.size && avpkt.size != pkt->size) {
  1603. av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
  1604. "Multiple frames in a packet from stream %d\n", pkt->stream_index);
  1605. ist->showed_multi_packet_warning = 1;
  1606. }
  1607. switch (ist->st->codec->codec_type) {
  1608. case AVMEDIA_TYPE_AUDIO:
  1609. ret = decode_audio (ist, &avpkt, &got_output);
  1610. break;
  1611. case AVMEDIA_TYPE_VIDEO:
  1612. ret = decode_video (ist, &avpkt, &got_output);
  1613. if (avpkt.duration) {
  1614. duration = av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
  1615. } else if(ist->st->codec->time_base.num != 0 && ist->st->codec->time_base.den != 0) {
  1616. int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
  1617. duration = ((int64_t)AV_TIME_BASE *
  1618. ist->st->codec->time_base.num * ticks) /
  1619. ist->st->codec->time_base.den;
  1620. } else
  1621. duration = 0;
  1622. if(ist->dts != AV_NOPTS_VALUE && duration) {
  1623. ist->next_dts += duration;
  1624. }else
  1625. ist->next_dts = AV_NOPTS_VALUE;
  1626. if (got_output)
  1627. ist->next_pts += duration; //FIXME the duration is not correct in some cases
  1628. break;
  1629. case AVMEDIA_TYPE_SUBTITLE:
  1630. ret = transcode_subtitles(ist, &avpkt, &got_output);
  1631. break;
  1632. default:
  1633. return -1;
  1634. }
  1635. if (ret < 0)
  1636. return ret;
  1637. avpkt.dts=
  1638. avpkt.pts= AV_NOPTS_VALUE;
  1639. // touch data and size only if not EOF
  1640. if (pkt) {
  1641. if(ist->st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
  1642. ret = avpkt.size;
  1643. avpkt.data += ret;
  1644. avpkt.size -= ret;
  1645. }
  1646. if (!got_output) {
  1647. continue;
  1648. }
  1649. }
  1650. /* handle stream copy */
  1651. if (!ist->decoding_needed) {
  1652. rate_emu_sleep(ist);
  1653. ist->dts = ist->next_dts;
  1654. switch (ist->st->codec->codec_type) {
  1655. case AVMEDIA_TYPE_AUDIO:
  1656. ist->next_dts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
  1657. ist->st->codec->sample_rate;
  1658. break;
  1659. case AVMEDIA_TYPE_VIDEO:
  1660. if (ist->framerate.num) {
  1661. int64_t next_dts = av_rescale_q(ist->next_dts, AV_TIME_BASE_Q, av_inv_q(ist->framerate));
  1662. ist->next_dts = av_rescale_q(next_dts + 1, av_inv_q(ist->framerate), AV_TIME_BASE_Q);
  1663. } else if (pkt->duration) {
  1664. ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
  1665. } else if(ist->st->codec->time_base.num != 0) {
  1666. int ticks= ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
  1667. ist->next_dts += ((int64_t)AV_TIME_BASE *
  1668. ist->st->codec->time_base.num * ticks) /
  1669. ist->st->codec->time_base.den;
  1670. }
  1671. break;
  1672. }
  1673. ist->pts = ist->dts;
  1674. ist->next_pts = ist->next_dts;
  1675. }
  1676. for (i = 0; pkt && i < nb_output_streams; i++) {
  1677. OutputStream *ost = output_streams[i];
  1678. if (!check_output_constraints(ist, ost) || ost->encoding_needed)
  1679. continue;
  1680. do_streamcopy(ist, ost, pkt);
  1681. }
  1682. return 0;
  1683. }
  1684. static void print_sdp(void)
  1685. {
  1686. char sdp[16384];
  1687. int i;
  1688. AVFormatContext **avc = av_malloc(sizeof(*avc) * nb_output_files);
  1689. if (!avc)
  1690. exit(1);
  1691. for (i = 0; i < nb_output_files; i++)
  1692. avc[i] = output_files[i]->ctx;
  1693. av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
  1694. printf("SDP:\n%s\n", sdp);
  1695. fflush(stdout);
  1696. av_freep(&avc);
  1697. }
  1698. static int init_input_stream(int ist_index, char *error, int error_len)
  1699. {
  1700. int ret;
  1701. InputStream *ist = input_streams[ist_index];
  1702. if (ist->decoding_needed) {
  1703. AVCodec *codec = ist->dec;
  1704. if (!codec) {
  1705. snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
  1706. avcodec_get_name(ist->st->codec->codec_id), ist->file_index, ist->st->index);
  1707. return AVERROR(EINVAL);
  1708. }
  1709. ist->dr1 = (codec->capabilities & CODEC_CAP_DR1) && !(FF_API_DEINTERLACE && do_deinterlace);
  1710. if (codec->type == AVMEDIA_TYPE_VIDEO && ist->dr1) {
  1711. ist->st->codec->get_buffer = codec_get_buffer;
  1712. ist->st->codec->release_buffer = codec_release_buffer;
  1713. ist->st->codec->opaque = &ist->buffer_pool;
  1714. }
  1715. if (!av_dict_get(ist->opts, "threads", NULL, 0))
  1716. av_dict_set(&ist->opts, "threads", "auto", 0);
  1717. if ((ret = avcodec_open2(ist->st->codec, codec, &ist->opts)) < 0) {
  1718. if (ret == AVERROR_EXPERIMENTAL)
  1719. abort_codec_experimental(codec, 0);
  1720. snprintf(error, error_len, "Error while opening decoder for input stream #%d:%d",
  1721. ist->file_index, ist->st->index);
  1722. return ret;
  1723. }
  1724. assert_avoptions(ist->opts);
  1725. }
  1726. ist->next_pts = AV_NOPTS_VALUE;
  1727. ist->next_dts = AV_NOPTS_VALUE;
  1728. ist->is_start = 1;
  1729. return 0;
  1730. }
  1731. static InputStream *get_input_stream(OutputStream *ost)
  1732. {
  1733. if (ost->source_index >= 0)
  1734. return input_streams[ost->source_index];
  1735. return NULL;
  1736. }
  1737. static int compare_int64(const void *a, const void *b)
  1738. {
  1739. int64_t va = *(int64_t *)a, vb = *(int64_t *)b;
  1740. return va < vb ? -1 : va > vb ? +1 : 0;
  1741. }
  1742. static void parse_forced_key_frames(char *kf, OutputStream *ost,
  1743. AVCodecContext *avctx)
  1744. {
  1745. char *p;
  1746. int n = 1, i, size, index = 0;
  1747. int64_t t, *pts;
  1748. for (p = kf; *p; p++)
  1749. if (*p == ',')
  1750. n++;
  1751. size = n;
  1752. pts = av_malloc(sizeof(*pts) * size);
  1753. if (!pts) {
  1754. av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
  1755. exit(1);
  1756. }
  1757. p = kf;
  1758. for (i = 0; i < n; i++) {
  1759. char *next = strchr(p, ',');
  1760. if (next)
  1761. *next++ = 0;
  1762. if (!memcmp(p, "chapters", 8)) {
  1763. AVFormatContext *avf = output_files[ost->file_index]->ctx;
  1764. int j;
  1765. if (avf->nb_chapters > INT_MAX - size ||
  1766. !(pts = av_realloc_f(pts, size += avf->nb_chapters - 1,
  1767. sizeof(*pts)))) {
  1768. av_log(NULL, AV_LOG_FATAL,
  1769. "Could not allocate forced key frames array.\n");
  1770. exit(1);
  1771. }
  1772. t = p[8] ? parse_time_or_die("force_key_frames", p + 8, 1) : 0;
  1773. t = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
  1774. for (j = 0; j < avf->nb_chapters; j++) {
  1775. AVChapter *c = avf->chapters[j];
  1776. av_assert1(index < size);
  1777. pts[index++] = av_rescale_q(c->start, c->time_base,
  1778. avctx->time_base) + t;
  1779. }
  1780. } else {
  1781. t = parse_time_or_die("force_key_frames", p, 1);
  1782. av_assert1(index < size);
  1783. pts[index++] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
  1784. }
  1785. p = next;
  1786. }
  1787. av_assert0(index == size);
  1788. qsort(pts, size, sizeof(*pts), compare_int64);
  1789. ost->forced_kf_count = size;
  1790. ost->forced_kf_pts = pts;
  1791. }
  1792. static void report_new_stream(int input_index, AVPacket *pkt)
  1793. {
  1794. InputFile *file = input_files[input_index];
  1795. AVStream *st = file->ctx->streams[pkt->stream_index];
  1796. if (pkt->stream_index < file->nb_streams_warn)
  1797. return;
  1798. av_log(file->ctx, AV_LOG_WARNING,
  1799. "New %s stream %d:%d at pos:%"PRId64" and DTS:%ss\n",
  1800. av_get_media_type_string(st->codec->codec_type),
  1801. input_index, pkt->stream_index,
  1802. pkt->pos, av_ts2timestr(pkt->dts, &st->time_base));
  1803. file->nb_streams_warn = pkt->stream_index + 1;
  1804. }
  1805. static int transcode_init(void)
  1806. {
  1807. int ret = 0, i, j, k;
  1808. AVFormatContext *oc;
  1809. AVCodecContext *codec;
  1810. OutputStream *ost;
  1811. InputStream *ist;
  1812. char error[1024] = {0};
  1813. int want_sdp = 1;
  1814. /* init framerate emulation */
  1815. for (i = 0; i < nb_input_files; i++) {
  1816. InputFile *ifile = input_files[i];
  1817. if (ifile->rate_emu)
  1818. for (j = 0; j < ifile->nb_streams; j++)
  1819. input_streams[j + ifile->ist_index]->start = av_gettime();
  1820. }
  1821. /* output stream init */
  1822. for (i = 0; i < nb_output_files; i++) {
  1823. oc = output_files[i]->ctx;
  1824. if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
  1825. av_dump_format(oc, i, oc->filename, 1);
  1826. av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
  1827. return AVERROR(EINVAL);
  1828. }
  1829. }
  1830. /* init complex filtergraphs */
  1831. for (i = 0; i < nb_filtergraphs; i++)
  1832. if ((ret = avfilter_graph_config(filtergraphs[i]->graph, NULL)) < 0)
  1833. return ret;
  1834. /* for each output stream, we compute the right encoding parameters */
  1835. for (i = 0; i < nb_output_streams; i++) {
  1836. AVCodecContext *icodec = NULL;
  1837. ost = output_streams[i];
  1838. oc = output_files[ost->file_index]->ctx;
  1839. ist = get_input_stream(ost);
  1840. if (ost->attachment_filename)
  1841. continue;
  1842. codec = ost->st->codec;
  1843. if (ist) {
  1844. icodec = ist->st->codec;
  1845. ost->st->disposition = ist->st->disposition;
  1846. codec->bits_per_raw_sample = icodec->bits_per_raw_sample;
  1847. codec->chroma_sample_location = icodec->chroma_sample_location;
  1848. }
  1849. if (ost->stream_copy) {
  1850. uint64_t extra_size;
  1851. av_assert0(ist && !ost->filter);
  1852. extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
  1853. if (extra_size > INT_MAX) {
  1854. return AVERROR(EINVAL);
  1855. }
  1856. /* if stream_copy is selected, no need to decode or encode */
  1857. codec->codec_id = icodec->codec_id;
  1858. codec->codec_type = icodec->codec_type;
  1859. if (!codec->codec_tag) {
  1860. unsigned int codec_tag;
  1861. if (!oc->oformat->codec_tag ||
  1862. av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
  1863. !av_codec_get_tag2(oc->oformat->codec_tag, icodec->codec_id, &codec_tag))
  1864. codec->codec_tag = icodec->codec_tag;
  1865. }
  1866. codec->bit_rate = icodec->bit_rate;
  1867. codec->rc_max_rate = icodec->rc_max_rate;
  1868. codec->rc_buffer_size = icodec->rc_buffer_size;
  1869. codec->field_order = icodec->field_order;
  1870. codec->extradata = av_mallocz(extra_size);
  1871. if (!codec->extradata) {
  1872. return AVERROR(ENOMEM);
  1873. }
  1874. memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
  1875. codec->extradata_size= icodec->extradata_size;
  1876. codec->bits_per_coded_sample = icodec->bits_per_coded_sample;
  1877. codec->time_base = ist->st->time_base;
  1878. /*
  1879. * Avi is a special case here because it supports variable fps but
  1880. * having the fps and timebase differe significantly adds quite some
  1881. * overhead
  1882. */
  1883. if(!strcmp(oc->oformat->name, "avi")) {
  1884. if ( copy_tb<0 && av_q2d(ist->st->r_frame_rate) >= av_q2d(ist->st->avg_frame_rate)
  1885. && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(ist->st->time_base)
  1886. && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(icodec->time_base)
  1887. && av_q2d(ist->st->time_base) < 1.0/500 && av_q2d(icodec->time_base) < 1.0/500
  1888. || copy_tb==2){
  1889. codec->time_base.num = ist->st->r_frame_rate.den;
  1890. codec->time_base.den = 2*ist->st->r_frame_rate.num;
  1891. codec->ticks_per_frame = 2;
  1892. } else if ( copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > 2*av_q2d(ist->st->time_base)
  1893. && av_q2d(ist->st->time_base) < 1.0/500
  1894. || copy_tb==0){
  1895. codec->time_base = icodec->time_base;
  1896. codec->time_base.num *= icodec->ticks_per_frame;
  1897. codec->time_base.den *= 2;
  1898. codec->ticks_per_frame = 2;
  1899. }
  1900. } else if(!(oc->oformat->flags & AVFMT_VARIABLE_FPS)
  1901. && strcmp(oc->oformat->name, "mov") && strcmp(oc->oformat->name, "mp4") && strcmp(oc->oformat->name, "3gp")
  1902. && strcmp(oc->oformat->name, "3g2") && strcmp(oc->oformat->name, "psp") && strcmp(oc->oformat->name, "ipod")
  1903. && strcmp(oc->oformat->name, "f4v")
  1904. ) {
  1905. if( copy_tb<0 && icodec->time_base.den
  1906. && av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base)
  1907. && av_q2d(ist->st->time_base) < 1.0/500
  1908. || copy_tb==0){
  1909. codec->time_base = icodec->time_base;
  1910. codec->time_base.num *= icodec->ticks_per_frame;
  1911. }
  1912. }
  1913. if ( codec->codec_tag == AV_RL32("tmcd")
  1914. && icodec->time_base.num < icodec->time_base.den
  1915. && icodec->time_base.num > 0
  1916. && 121LL*icodec->time_base.num > icodec->time_base.den) {
  1917. codec->time_base = icodec->time_base;
  1918. }
  1919. if (ist && !ost->frame_rate.num)
  1920. ost->frame_rate = ist->framerate;
  1921. if(ost->frame_rate.num)
  1922. codec->time_base = av_inv_q(ost->frame_rate);
  1923. av_reduce(&codec->time_base.num, &codec->time_base.den,
  1924. codec->time_base.num, codec->time_base.den, INT_MAX);
  1925. switch (codec->codec_type) {
  1926. case AVMEDIA_TYPE_AUDIO:
  1927. if (audio_volume != 256) {
  1928. av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
  1929. exit(1);
  1930. }
  1931. codec->channel_layout = icodec->channel_layout;
  1932. codec->sample_rate = icodec->sample_rate;
  1933. codec->channels = icodec->channels;
  1934. codec->frame_size = icodec->frame_size;
  1935. codec->audio_service_type = icodec->audio_service_type;
  1936. codec->block_align = icodec->block_align;
  1937. if((codec->block_align == 1 || codec->block_align == 1152 || codec->block_align == 576) && codec->codec_id == AV_CODEC_ID_MP3)
  1938. codec->block_align= 0;
  1939. if(codec->codec_id == AV_CODEC_ID_AC3)
  1940. codec->block_align= 0;
  1941. break;
  1942. case AVMEDIA_TYPE_VIDEO:
  1943. codec->pix_fmt = icodec->pix_fmt;
  1944. codec->width = icodec->width;
  1945. codec->height = icodec->height;
  1946. codec->has_b_frames = icodec->has_b_frames;
  1947. if (!codec->sample_aspect_ratio.num) {
  1948. codec->sample_aspect_ratio =
  1949. ost->st->sample_aspect_ratio =
  1950. ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
  1951. ist->st->codec->sample_aspect_ratio.num ?
  1952. ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};
  1953. }
  1954. ost->st->avg_frame_rate = ist->st->avg_frame_rate;
  1955. break;
  1956. case AVMEDIA_TYPE_SUBTITLE:
  1957. codec->width = icodec->width;
  1958. codec->height = icodec->height;
  1959. break;
  1960. case AVMEDIA_TYPE_DATA:
  1961. case AVMEDIA_TYPE_ATTACHMENT:
  1962. break;
  1963. default:
  1964. abort();
  1965. }
  1966. } else {
  1967. if (!ost->enc)
  1968. ost->enc = avcodec_find_encoder(codec->codec_id);
  1969. if (!ost->enc) {
  1970. /* should only happen when a default codec is not present. */
  1971. snprintf(error, sizeof(error), "Encoder (codec %s) not found for output stream #%d:%d",
  1972. avcodec_get_name(ost->st->codec->codec_id), ost->file_index, ost->index);
  1973. ret = AVERROR(EINVAL);
  1974. goto dump_format;
  1975. }
  1976. if (ist)
  1977. ist->decoding_needed++;
  1978. ost->encoding_needed = 1;
  1979. if (!ost->filter &&
  1980. (codec->codec_type == AVMEDIA_TYPE_VIDEO ||
  1981. codec->codec_type == AVMEDIA_TYPE_AUDIO)) {
  1982. FilterGraph *fg;
  1983. fg = init_simple_filtergraph(ist, ost);
  1984. if (configure_filtergraph(fg)) {
  1985. av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
  1986. exit(1);
  1987. }
  1988. }
  1989. if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  1990. if (ost->filter && !ost->frame_rate.num)
  1991. ost->frame_rate = av_buffersink_get_frame_rate(ost->filter->filter);
  1992. if (ist && !ost->frame_rate.num)
  1993. ost->frame_rate = ist->framerate;
  1994. if (ist && !ost->frame_rate.num)
  1995. ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational){25, 1};
  1996. // ost->frame_rate = ist->st->avg_frame_rate.num ? ist->st->avg_frame_rate : (AVRational){25, 1};
  1997. if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
  1998. int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
  1999. ost->frame_rate = ost->enc->supported_framerates[idx];
  2000. }
  2001. }
  2002. switch (codec->codec_type) {
  2003. case AVMEDIA_TYPE_AUDIO:
  2004. codec->sample_fmt = ost->filter->filter->inputs[0]->format;
  2005. codec->sample_rate = ost->filter->filter->inputs[0]->sample_rate;
  2006. codec->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
  2007. codec->channels = avfilter_link_get_channels(ost->filter->filter->inputs[0]);
  2008. codec->time_base = (AVRational){ 1, codec->sample_rate };
  2009. break;
  2010. case AVMEDIA_TYPE_VIDEO:
  2011. codec->time_base = av_inv_q(ost->frame_rate);
  2012. if (ost->filter && !(codec->time_base.num && codec->time_base.den))
  2013. codec->time_base = ost->filter->filter->inputs[0]->time_base;
  2014. if ( av_q2d(codec->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH
  2015. && (video_sync_method == VSYNC_CFR || (video_sync_method == VSYNC_AUTO && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
  2016. av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"
  2017. "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
  2018. }
  2019. for (j = 0; j < ost->forced_kf_count; j++)
  2020. ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
  2021. AV_TIME_BASE_Q,
  2022. codec->time_base);
  2023. codec->width = ost->filter->filter->inputs[0]->w;
  2024. codec->height = ost->filter->filter->inputs[0]->h;
  2025. codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
  2026. ost->frame_aspect_ratio ? // overridden by the -aspect cli option
  2027. av_d2q(ost->frame_aspect_ratio * codec->height/codec->width, 255) :
  2028. ost->filter->filter->inputs[0]->sample_aspect_ratio;
  2029. codec->pix_fmt = ost->filter->filter->inputs[0]->format;
  2030. if (!icodec ||
  2031. codec->width != icodec->width ||
  2032. codec->height != icodec->height ||
  2033. codec->pix_fmt != icodec->pix_fmt) {
  2034. codec->bits_per_raw_sample = frame_bits_per_raw_sample;
  2035. }
  2036. if (ost->forced_keyframes) {
  2037. if (!strncmp(ost->forced_keyframes, "expr:", 5)) {
  2038. ret = av_expr_parse(&ost->forced_keyframes_pexpr, ost->forced_keyframes+5,
  2039. forced_keyframes_const_names, NULL, NULL, NULL, NULL, 0, NULL);
  2040. if (ret < 0) {
  2041. av_log(NULL, AV_LOG_ERROR,
  2042. "Invalid force_key_frames expression '%s'\n", ost->forced_keyframes+5);
  2043. return ret;
  2044. }
  2045. ost->forced_keyframes_expr_const_values[FKF_N] = 0;
  2046. ost->forced_keyframes_expr_const_values[FKF_N_FORCED] = 0;
  2047. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] = NAN;
  2048. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] = NAN;
  2049. } else {
  2050. parse_forced_key_frames(ost->forced_keyframes, ost, ost->st->codec);
  2051. }
  2052. }
  2053. break;
  2054. case AVMEDIA_TYPE_SUBTITLE:
  2055. codec->time_base = (AVRational){1, 1000};
  2056. if (!codec->width) {
  2057. codec->width = input_streams[ost->source_index]->st->codec->width;
  2058. codec->height = input_streams[ost->source_index]->st->codec->height;
  2059. }
  2060. break;
  2061. default:
  2062. abort();
  2063. break;
  2064. }
  2065. /* two pass mode */
  2066. if (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2)) {
  2067. char logfilename[1024];
  2068. FILE *f;
  2069. snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
  2070. ost->logfile_prefix ? ost->logfile_prefix :
  2071. DEFAULT_PASS_LOGFILENAME_PREFIX,
  2072. i);
  2073. if (!strcmp(ost->enc->name, "libx264")) {
  2074. av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
  2075. } else {
  2076. if (codec->flags & CODEC_FLAG_PASS2) {
  2077. char *logbuffer;
  2078. size_t logbuffer_size;
  2079. if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
  2080. av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
  2081. logfilename);
  2082. exit(1);
  2083. }
  2084. codec->stats_in = logbuffer;
  2085. }
  2086. if (codec->flags & CODEC_FLAG_PASS1) {
  2087. f = fopen(logfilename, "wb");
  2088. if (!f) {
  2089. av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
  2090. logfilename, strerror(errno));
  2091. exit(1);
  2092. }
  2093. ost->logfile = f;
  2094. }
  2095. }
  2096. }
  2097. }
  2098. }
  2099. /* open each encoder */
  2100. for (i = 0; i < nb_output_streams; i++) {
  2101. ost = output_streams[i];
  2102. if (ost->encoding_needed) {
  2103. AVCodec *codec = ost->enc;
  2104. AVCodecContext *dec = NULL;
  2105. if ((ist = get_input_stream(ost)))
  2106. dec = ist->st->codec;
  2107. if (dec && dec->subtitle_header) {
  2108. /* ASS code assumes this buffer is null terminated so add extra byte. */
  2109. ost->st->codec->subtitle_header = av_mallocz(dec->subtitle_header_size + 1);
  2110. if (!ost->st->codec->subtitle_header) {
  2111. ret = AVERROR(ENOMEM);
  2112. goto dump_format;
  2113. }
  2114. memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
  2115. ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
  2116. }
  2117. if (!av_dict_get(ost->opts, "threads", NULL, 0))
  2118. av_dict_set(&ost->opts, "threads", "auto", 0);
  2119. if ((ret = avcodec_open2(ost->st->codec, codec, &ost->opts)) < 0) {
  2120. if (ret == AVERROR_EXPERIMENTAL)
  2121. abort_codec_experimental(codec, 1);
  2122. snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
  2123. ost->file_index, ost->index);
  2124. goto dump_format;
  2125. }
  2126. if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
  2127. !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
  2128. av_buffersink_set_frame_size(ost->filter->filter,
  2129. ost->st->codec->frame_size);
  2130. assert_avoptions(ost->opts);
  2131. if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
  2132. av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
  2133. " It takes bits/s as argument, not kbits/s\n");
  2134. extra_size += ost->st->codec->extradata_size;
  2135. if (ost->st->codec->me_threshold)
  2136. input_streams[ost->source_index]->st->codec->debug |= FF_DEBUG_MV;
  2137. } else {
  2138. av_opt_set_dict(ost->st->codec, &ost->opts);
  2139. }
  2140. }
  2141. /* init input streams */
  2142. for (i = 0; i < nb_input_streams; i++)
  2143. if ((ret = init_input_stream(i, error, sizeof(error))) < 0) {
  2144. for (i = 0; i < nb_output_streams; i++) {
  2145. ost = output_streams[i];
  2146. avcodec_close(ost->st->codec);
  2147. }
  2148. goto dump_format;
  2149. }
  2150. /* discard unused programs */
  2151. for (i = 0; i < nb_input_files; i++) {
  2152. InputFile *ifile = input_files[i];
  2153. for (j = 0; j < ifile->ctx->nb_programs; j++) {
  2154. AVProgram *p = ifile->ctx->programs[j];
  2155. int discard = AVDISCARD_ALL;
  2156. for (k = 0; k < p->nb_stream_indexes; k++)
  2157. if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
  2158. discard = AVDISCARD_DEFAULT;
  2159. break;
  2160. }
  2161. p->discard = discard;
  2162. }
  2163. }
  2164. /* open files and write file headers */
  2165. for (i = 0; i < nb_output_files; i++) {
  2166. oc = output_files[i]->ctx;
  2167. oc->interrupt_callback = int_cb;
  2168. if ((ret = avformat_write_header(oc, &output_files[i]->opts)) < 0) {
  2169. char errbuf[128];
  2170. const char *errbuf_ptr = errbuf;
  2171. if (av_strerror(ret, errbuf, sizeof(errbuf)) < 0)
  2172. errbuf_ptr = strerror(AVUNERROR(ret));
  2173. snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?): %s", i, errbuf_ptr);
  2174. ret = AVERROR(EINVAL);
  2175. goto dump_format;
  2176. }
  2177. // assert_avoptions(output_files[i]->opts);
  2178. if (strcmp(oc->oformat->name, "rtp")) {
  2179. want_sdp = 0;
  2180. }
  2181. }
  2182. dump_format:
  2183. /* dump the file output parameters - cannot be done before in case
  2184. of stream copy */
  2185. for (i = 0; i < nb_output_files; i++) {
  2186. av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
  2187. }
  2188. /* dump the stream mapping */
  2189. av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
  2190. for (i = 0; i < nb_input_streams; i++) {
  2191. ist = input_streams[i];
  2192. for (j = 0; j < ist->nb_filters; j++) {
  2193. if (ist->filters[j]->graph->graph_desc) {
  2194. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
  2195. ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
  2196. ist->filters[j]->name);
  2197. if (nb_filtergraphs > 1)
  2198. av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
  2199. av_log(NULL, AV_LOG_INFO, "\n");
  2200. }
  2201. }
  2202. }
  2203. for (i = 0; i < nb_output_streams; i++) {
  2204. ost = output_streams[i];
  2205. if (ost->attachment_filename) {
  2206. /* an attached file */
  2207. av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
  2208. ost->attachment_filename, ost->file_index, ost->index);
  2209. continue;
  2210. }
  2211. if (ost->filter && ost->filter->graph->graph_desc) {
  2212. /* output from a complex graph */
  2213. av_log(NULL, AV_LOG_INFO, " %s", ost->filter->name);
  2214. if (nb_filtergraphs > 1)
  2215. av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
  2216. av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
  2217. ost->index, ost->enc ? ost->enc->name : "?");
  2218. continue;
  2219. }
  2220. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
  2221. input_streams[ost->source_index]->file_index,
  2222. input_streams[ost->source_index]->st->index,
  2223. ost->file_index,
  2224. ost->index);
  2225. if (ost->sync_ist != input_streams[ost->source_index])
  2226. av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
  2227. ost->sync_ist->file_index,
  2228. ost->sync_ist->st->index);
  2229. if (ost->stream_copy)
  2230. av_log(NULL, AV_LOG_INFO, " (copy)");
  2231. else
  2232. av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index]->dec ?
  2233. input_streams[ost->source_index]->dec->name : "?",
  2234. ost->enc ? ost->enc->name : "?");
  2235. av_log(NULL, AV_LOG_INFO, "\n");
  2236. }
  2237. if (ret) {
  2238. av_log(NULL, AV_LOG_ERROR, "%s\n", error);
  2239. return ret;
  2240. }
  2241. if (want_sdp) {
  2242. print_sdp();
  2243. }
  2244. return 0;
  2245. }
  2246. /* Return 1 if there remain streams where more output is wanted, 0 otherwise. */
  2247. static int need_output(void)
  2248. {
  2249. int i;
  2250. for (i = 0; i < nb_output_streams; i++) {
  2251. OutputStream *ost = output_streams[i];
  2252. OutputFile *of = output_files[ost->file_index];
  2253. AVFormatContext *os = output_files[ost->file_index]->ctx;
  2254. if (ost->finished ||
  2255. (os->pb && avio_tell(os->pb) >= of->limit_filesize))
  2256. continue;
  2257. if (ost->frame_number >= ost->max_frames) {
  2258. int j;
  2259. for (j = 0; j < of->ctx->nb_streams; j++)
  2260. close_output_stream(output_streams[of->ost_index + j]);
  2261. continue;
  2262. }
  2263. return 1;
  2264. }
  2265. return 0;
  2266. }
  2267. /**
  2268. * Select the output stream to process.
  2269. *
  2270. * @return selected output stream, or NULL if none available
  2271. */
  2272. static OutputStream *choose_output(void)
  2273. {
  2274. int i;
  2275. int64_t opts_min = INT64_MAX;
  2276. OutputStream *ost_min = NULL;
  2277. for (i = 0; i < nb_output_streams; i++) {
  2278. OutputStream *ost = output_streams[i];
  2279. int64_t opts = av_rescale_q(ost->st->cur_dts, ost->st->time_base,
  2280. AV_TIME_BASE_Q);
  2281. if (!ost->unavailable && !ost->finished && opts < opts_min) {
  2282. opts_min = opts;
  2283. ost_min = ost;
  2284. }
  2285. }
  2286. return ost_min;
  2287. }
  2288. static int check_keyboard_interaction(int64_t cur_time)
  2289. {
  2290. int i, ret, key;
  2291. static int64_t last_time;
  2292. if (received_nb_signals)
  2293. return AVERROR_EXIT;
  2294. /* read_key() returns 0 on EOF */
  2295. if(cur_time - last_time >= 100000 && !run_as_daemon){
  2296. key = read_key();
  2297. last_time = cur_time;
  2298. }else
  2299. key = -1;
  2300. if (key == 'q')
  2301. return AVERROR_EXIT;
  2302. if (key == '+') av_log_set_level(av_log_get_level()+10);
  2303. if (key == '-') av_log_set_level(av_log_get_level()-10);
  2304. if (key == 's') qp_hist ^= 1;
  2305. if (key == 'h'){
  2306. if (do_hex_dump){
  2307. do_hex_dump = do_pkt_dump = 0;
  2308. } else if(do_pkt_dump){
  2309. do_hex_dump = 1;
  2310. } else
  2311. do_pkt_dump = 1;
  2312. av_log_set_level(AV_LOG_DEBUG);
  2313. }
  2314. if (key == 'c' || key == 'C'){
  2315. char buf[4096], target[64], command[256], arg[256] = {0};
  2316. double time;
  2317. int k, n = 0;
  2318. fprintf(stderr, "\nEnter command: <target> <time> <command>[ <argument>]\n");
  2319. i = 0;
  2320. while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
  2321. if (k > 0)
  2322. buf[i++] = k;
  2323. buf[i] = 0;
  2324. if (k > 0 &&
  2325. (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
  2326. av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
  2327. target, time, command, arg);
  2328. for (i = 0; i < nb_filtergraphs; i++) {
  2329. FilterGraph *fg = filtergraphs[i];
  2330. if (fg->graph) {
  2331. if (time < 0) {
  2332. ret = avfilter_graph_send_command(fg->graph, target, command, arg, buf, sizeof(buf),
  2333. key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
  2334. fprintf(stderr, "Command reply for stream %d: ret:%d res:%s\n", i, ret, buf);
  2335. } else {
  2336. ret = avfilter_graph_queue_command(fg->graph, target, command, arg, 0, time);
  2337. }
  2338. }
  2339. }
  2340. } else {
  2341. av_log(NULL, AV_LOG_ERROR,
  2342. "Parse error, at least 3 arguments were expected, "
  2343. "only %d given in string '%s'\n", n, buf);
  2344. }
  2345. }
  2346. if (key == 'd' || key == 'D'){
  2347. int debug=0;
  2348. if(key == 'D') {
  2349. debug = input_streams[0]->st->codec->debug<<1;
  2350. if(!debug) debug = 1;
  2351. while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
  2352. debug += debug;
  2353. }else
  2354. if(scanf("%d", &debug)!=1)
  2355. fprintf(stderr,"error parsing debug value\n");
  2356. for(i=0;i<nb_input_streams;i++) {
  2357. input_streams[i]->st->codec->debug = debug;
  2358. }
  2359. for(i=0;i<nb_output_streams;i++) {
  2360. OutputStream *ost = output_streams[i];
  2361. ost->st->codec->debug = debug;
  2362. }
  2363. if(debug) av_log_set_level(AV_LOG_DEBUG);
  2364. fprintf(stderr,"debug=%d\n", debug);
  2365. }
  2366. if (key == '?'){
  2367. fprintf(stderr, "key function\n"
  2368. "? show this help\n"
  2369. "+ increase verbosity\n"
  2370. "- decrease verbosity\n"
  2371. "c Send command to filtergraph\n"
  2372. "D cycle through available debug modes\n"
  2373. "h dump packets/hex press to cycle through the 3 states\n"
  2374. "q quit\n"
  2375. "s Show QP histogram\n"
  2376. );
  2377. }
  2378. return 0;
  2379. }
  2380. #if HAVE_PTHREADS
  2381. static void *input_thread(void *arg)
  2382. {
  2383. InputFile *f = arg;
  2384. int ret = 0;
  2385. while (!transcoding_finished && ret >= 0) {
  2386. AVPacket pkt;
  2387. ret = av_read_frame(f->ctx, &pkt);
  2388. if (ret == AVERROR(EAGAIN)) {
  2389. av_usleep(10000);
  2390. ret = 0;
  2391. continue;
  2392. } else if (ret < 0)
  2393. break;
  2394. pthread_mutex_lock(&f->fifo_lock);
  2395. while (!av_fifo_space(f->fifo))
  2396. pthread_cond_wait(&f->fifo_cond, &f->fifo_lock);
  2397. av_dup_packet(&pkt);
  2398. av_fifo_generic_write(f->fifo, &pkt, sizeof(pkt), NULL);
  2399. pthread_mutex_unlock(&f->fifo_lock);
  2400. }
  2401. f->finished = 1;
  2402. return NULL;
  2403. }
  2404. static void free_input_threads(void)
  2405. {
  2406. int i;
  2407. if (nb_input_files == 1)
  2408. return;
  2409. transcoding_finished = 1;
  2410. for (i = 0; i < nb_input_files; i++) {
  2411. InputFile *f = input_files[i];
  2412. AVPacket pkt;
  2413. if (!f->fifo || f->joined)
  2414. continue;
  2415. pthread_mutex_lock(&f->fifo_lock);
  2416. while (av_fifo_size(f->fifo)) {
  2417. av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
  2418. av_free_packet(&pkt);
  2419. }
  2420. pthread_cond_signal(&f->fifo_cond);
  2421. pthread_mutex_unlock(&f->fifo_lock);
  2422. pthread_join(f->thread, NULL);
  2423. f->joined = 1;
  2424. while (av_fifo_size(f->fifo)) {
  2425. av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
  2426. av_free_packet(&pkt);
  2427. }
  2428. av_fifo_free(f->fifo);
  2429. }
  2430. }
  2431. static int init_input_threads(void)
  2432. {
  2433. int i, ret;
  2434. if (nb_input_files == 1)
  2435. return 0;
  2436. for (i = 0; i < nb_input_files; i++) {
  2437. InputFile *f = input_files[i];
  2438. if (!(f->fifo = av_fifo_alloc(8*sizeof(AVPacket))))
  2439. return AVERROR(ENOMEM);
  2440. pthread_mutex_init(&f->fifo_lock, NULL);
  2441. pthread_cond_init (&f->fifo_cond, NULL);
  2442. if ((ret = pthread_create(&f->thread, NULL, input_thread, f)))
  2443. return AVERROR(ret);
  2444. }
  2445. return 0;
  2446. }
  2447. static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
  2448. {
  2449. int ret = 0;
  2450. pthread_mutex_lock(&f->fifo_lock);
  2451. if (av_fifo_size(f->fifo)) {
  2452. av_fifo_generic_read(f->fifo, pkt, sizeof(*pkt), NULL);
  2453. pthread_cond_signal(&f->fifo_cond);
  2454. } else {
  2455. if (f->finished)
  2456. ret = AVERROR_EOF;
  2457. else
  2458. ret = AVERROR(EAGAIN);
  2459. }
  2460. pthread_mutex_unlock(&f->fifo_lock);
  2461. return ret;
  2462. }
  2463. #endif
  2464. static int get_input_packet(InputFile *f, AVPacket *pkt)
  2465. {
  2466. #if HAVE_PTHREADS
  2467. if (nb_input_files > 1)
  2468. return get_input_packet_mt(f, pkt);
  2469. #endif
  2470. return av_read_frame(f->ctx, pkt);
  2471. }
  2472. static int got_eagain(void)
  2473. {
  2474. int i;
  2475. for (i = 0; i < nb_output_streams; i++)
  2476. if (output_streams[i]->unavailable)
  2477. return 1;
  2478. return 0;
  2479. }
  2480. static void reset_eagain(void)
  2481. {
  2482. int i;
  2483. for (i = 0; i < nb_input_files; i++)
  2484. input_files[i]->eagain = 0;
  2485. for (i = 0; i < nb_output_streams; i++)
  2486. output_streams[i]->unavailable = 0;
  2487. }
  2488. /*
  2489. * Return
  2490. * - 0 -- one packet was read and processed
  2491. * - AVERROR(EAGAIN) -- no packets were available for selected file,
  2492. * this function should be called again
  2493. * - AVERROR_EOF -- this function should not be called again
  2494. */
  2495. static int process_input(int file_index)
  2496. {
  2497. InputFile *ifile = input_files[file_index];
  2498. AVFormatContext *is;
  2499. InputStream *ist;
  2500. AVPacket pkt;
  2501. int ret, i, j;
  2502. is = ifile->ctx;
  2503. ret = get_input_packet(ifile, &pkt);
  2504. if (ret == AVERROR(EAGAIN)) {
  2505. ifile->eagain = 1;
  2506. return ret;
  2507. }
  2508. if (ret < 0) {
  2509. if (ret != AVERROR_EOF) {
  2510. print_error(is->filename, ret);
  2511. if (exit_on_error)
  2512. exit(1);
  2513. }
  2514. ifile->eof_reached = 1;
  2515. for (i = 0; i < ifile->nb_streams; i++) {
  2516. ist = input_streams[ifile->ist_index + i];
  2517. if (ist->decoding_needed)
  2518. output_packet(ist, NULL);
  2519. /* mark all outputs that don't go through lavfi as finished */
  2520. for (j = 0; j < nb_output_streams; j++) {
  2521. OutputStream *ost = output_streams[j];
  2522. if (ost->source_index == ifile->ist_index + i &&
  2523. (ost->stream_copy || ost->enc->type == AVMEDIA_TYPE_SUBTITLE))
  2524. close_output_stream(ost);
  2525. }
  2526. }
  2527. return AVERROR(EAGAIN);
  2528. }
  2529. reset_eagain();
  2530. if (do_pkt_dump) {
  2531. av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
  2532. is->streams[pkt.stream_index]);
  2533. }
  2534. /* the following test is needed in case new streams appear
  2535. dynamically in stream : we ignore them */
  2536. if (pkt.stream_index >= ifile->nb_streams) {
  2537. report_new_stream(file_index, &pkt);
  2538. goto discard_packet;
  2539. }
  2540. ist = input_streams[ifile->ist_index + pkt.stream_index];
  2541. if (ist->discard)
  2542. goto discard_packet;
  2543. if (debug_ts) {
  2544. av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
  2545. "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",
  2546. ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->st->codec->codec_type),
  2547. av_ts2str(ist->next_dts), av_ts2timestr(ist->next_dts, &AV_TIME_BASE_Q),
  2548. av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &AV_TIME_BASE_Q),
  2549. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
  2550. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
  2551. av_ts2str(input_files[ist->file_index]->ts_offset),
  2552. av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
  2553. }
  2554. if(!ist->wrap_correction_done && is->start_time != AV_NOPTS_VALUE && ist->st->pts_wrap_bits < 64){
  2555. int64_t stime, stime2;
  2556. // Correcting starttime based on the enabled streams
  2557. // 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.
  2558. // so we instead do it here as part of discontinuity handling
  2559. if ( ist->next_dts == AV_NOPTS_VALUE
  2560. && ifile->ts_offset == -is->start_time
  2561. && (is->iformat->flags & AVFMT_TS_DISCONT)) {
  2562. int64_t new_start_time = INT64_MAX;
  2563. for (i=0; i<is->nb_streams; i++) {
  2564. AVStream *st = is->streams[i];
  2565. if(st->discard == AVDISCARD_ALL || st->start_time == AV_NOPTS_VALUE)
  2566. continue;
  2567. new_start_time = FFMIN(new_start_time, av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q));
  2568. }
  2569. if (new_start_time > is->start_time) {
  2570. av_log(is, AV_LOG_VERBOSE, "Correcting start time by %"PRId64"\n", new_start_time - is->start_time);
  2571. ifile->ts_offset = -new_start_time;
  2572. }
  2573. }
  2574. stime = av_rescale_q(is->start_time, AV_TIME_BASE_Q, ist->st->time_base);
  2575. stime2= stime + (1ULL<<ist->st->pts_wrap_bits);
  2576. ist->wrap_correction_done = 1;
  2577. if(stime2 > stime && pkt.dts != AV_NOPTS_VALUE && pkt.dts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
  2578. pkt.dts -= 1ULL<<ist->st->pts_wrap_bits;
  2579. ist->wrap_correction_done = 0;
  2580. }
  2581. if(stime2 > stime && pkt.pts != AV_NOPTS_VALUE && pkt.pts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
  2582. pkt.pts -= 1ULL<<ist->st->pts_wrap_bits;
  2583. ist->wrap_correction_done = 0;
  2584. }
  2585. }
  2586. if (pkt.dts != AV_NOPTS_VALUE)
  2587. pkt.dts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
  2588. if (pkt.pts != AV_NOPTS_VALUE)
  2589. pkt.pts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
  2590. if (pkt.pts != AV_NOPTS_VALUE)
  2591. pkt.pts *= ist->ts_scale;
  2592. if (pkt.dts != AV_NOPTS_VALUE)
  2593. pkt.dts *= ist->ts_scale;
  2594. if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE &&
  2595. !copy_ts) {
  2596. int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
  2597. int64_t delta = pkt_dts - ist->next_dts;
  2598. if (is->iformat->flags & AVFMT_TS_DISCONT) {
  2599. if(delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
  2600. (delta > 1LL*dts_delta_threshold*AV_TIME_BASE &&
  2601. ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
  2602. pkt_dts+1<ist->pts){
  2603. ifile->ts_offset -= delta;
  2604. av_log(NULL, AV_LOG_DEBUG,
  2605. "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
  2606. delta, ifile->ts_offset);
  2607. pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  2608. if (pkt.pts != AV_NOPTS_VALUE)
  2609. pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  2610. }
  2611. } else {
  2612. if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
  2613. (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)
  2614. ) {
  2615. av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);
  2616. pkt.dts = AV_NOPTS_VALUE;
  2617. }
  2618. if (pkt.pts != AV_NOPTS_VALUE){
  2619. int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);
  2620. delta = pkt_pts - ist->next_dts;
  2621. if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
  2622. (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)
  2623. ) {
  2624. av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);
  2625. pkt.pts = AV_NOPTS_VALUE;
  2626. }
  2627. }
  2628. }
  2629. }
  2630. if (debug_ts) {
  2631. 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",
  2632. ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->st->codec->codec_type),
  2633. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
  2634. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
  2635. av_ts2str(input_files[ist->file_index]->ts_offset),
  2636. av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
  2637. }
  2638. sub2video_heartbeat(ist, pkt.pts);
  2639. ret = output_packet(ist, &pkt);
  2640. if (ret < 0) {
  2641. char buf[128];
  2642. av_strerror(ret, buf, sizeof(buf));
  2643. av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d: %s\n",
  2644. ist->file_index, ist->st->index, buf);
  2645. if (exit_on_error)
  2646. exit(1);
  2647. }
  2648. discard_packet:
  2649. av_free_packet(&pkt);
  2650. return 0;
  2651. }
  2652. /**
  2653. * Perform a step of transcoding for the specified filter graph.
  2654. *
  2655. * @param[in] graph filter graph to consider
  2656. * @param[out] best_ist input stream where a frame would allow to continue
  2657. * @return 0 for success, <0 for error
  2658. */
  2659. static int transcode_from_filter(FilterGraph *graph, InputStream **best_ist)
  2660. {
  2661. int i, ret;
  2662. int nb_requests, nb_requests_max = 0;
  2663. InputFilter *ifilter;
  2664. InputStream *ist;
  2665. *best_ist = NULL;
  2666. ret = avfilter_graph_request_oldest(graph->graph);
  2667. if (ret >= 0)
  2668. return reap_filters();
  2669. if (ret == AVERROR_EOF) {
  2670. ret = reap_filters();
  2671. for (i = 0; i < graph->nb_outputs; i++)
  2672. close_output_stream(graph->outputs[i]->ost);
  2673. return ret;
  2674. }
  2675. if (ret != AVERROR(EAGAIN))
  2676. return ret;
  2677. for (i = 0; i < graph->nb_inputs; i++) {
  2678. ifilter = graph->inputs[i];
  2679. ist = ifilter->ist;
  2680. if (input_files[ist->file_index]->eagain ||
  2681. input_files[ist->file_index]->eof_reached)
  2682. continue;
  2683. nb_requests = av_buffersrc_get_nb_failed_requests(ifilter->filter);
  2684. if (nb_requests > nb_requests_max) {
  2685. nb_requests_max = nb_requests;
  2686. *best_ist = ist;
  2687. }
  2688. }
  2689. if (!*best_ist)
  2690. for (i = 0; i < graph->nb_outputs; i++)
  2691. graph->outputs[i]->ost->unavailable = 1;
  2692. return 0;
  2693. }
  2694. /**
  2695. * Run a single step of transcoding.
  2696. *
  2697. * @return 0 for success, <0 for error
  2698. */
  2699. static int transcode_step(void)
  2700. {
  2701. OutputStream *ost;
  2702. InputStream *ist;
  2703. int ret;
  2704. ost = choose_output();
  2705. if (!ost) {
  2706. if (got_eagain()) {
  2707. reset_eagain();
  2708. av_usleep(10000);
  2709. return 0;
  2710. }
  2711. av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from, finishing.\n");
  2712. return AVERROR_EOF;
  2713. }
  2714. if (ost->filter) {
  2715. if ((ret = transcode_from_filter(ost->filter->graph, &ist)) < 0)
  2716. return ret;
  2717. if (!ist)
  2718. return 0;
  2719. } else {
  2720. av_assert0(ost->source_index >= 0);
  2721. ist = input_streams[ost->source_index];
  2722. }
  2723. ret = process_input(ist->file_index);
  2724. if (ret == AVERROR(EAGAIN)) {
  2725. if (input_files[ist->file_index]->eagain)
  2726. ost->unavailable = 1;
  2727. return 0;
  2728. }
  2729. if (ret < 0)
  2730. return ret == AVERROR_EOF ? 0 : ret;
  2731. return reap_filters();
  2732. }
  2733. /*
  2734. * The following code is the main loop of the file converter
  2735. */
  2736. static int transcode(void)
  2737. {
  2738. int ret, i;
  2739. AVFormatContext *os;
  2740. OutputStream *ost;
  2741. InputStream *ist;
  2742. int64_t timer_start;
  2743. ret = transcode_init();
  2744. if (ret < 0)
  2745. goto fail;
  2746. if (stdin_interaction) {
  2747. av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
  2748. }
  2749. timer_start = av_gettime();
  2750. #if HAVE_PTHREADS
  2751. if ((ret = init_input_threads()) < 0)
  2752. goto fail;
  2753. #endif
  2754. while (!received_sigterm) {
  2755. int64_t cur_time= av_gettime();
  2756. /* if 'q' pressed, exits */
  2757. if (stdin_interaction)
  2758. if (check_keyboard_interaction(cur_time) < 0)
  2759. break;
  2760. /* check if there's any stream where output is still needed */
  2761. if (!need_output()) {
  2762. av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
  2763. break;
  2764. }
  2765. ret = transcode_step();
  2766. if (ret < 0) {
  2767. if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
  2768. continue;
  2769. av_log(NULL, AV_LOG_ERROR, "Error while filtering.\n");
  2770. break;
  2771. }
  2772. /* dump report by using the output first video and audio streams */
  2773. print_report(0, timer_start, cur_time);
  2774. }
  2775. #if HAVE_PTHREADS
  2776. free_input_threads();
  2777. #endif
  2778. /* at the end of stream, we must flush the decoder buffers */
  2779. for (i = 0; i < nb_input_streams; i++) {
  2780. ist = input_streams[i];
  2781. if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
  2782. output_packet(ist, NULL);
  2783. }
  2784. }
  2785. flush_encoders();
  2786. term_exit();
  2787. /* write the trailer if needed and close file */
  2788. for (i = 0; i < nb_output_files; i++) {
  2789. os = output_files[i]->ctx;
  2790. av_write_trailer(os);
  2791. }
  2792. /* dump report by using the first video and audio streams */
  2793. print_report(1, timer_start, av_gettime());
  2794. /* close each encoder */
  2795. for (i = 0; i < nb_output_streams; i++) {
  2796. ost = output_streams[i];
  2797. if (ost->encoding_needed) {
  2798. av_freep(&ost->st->codec->stats_in);
  2799. avcodec_close(ost->st->codec);
  2800. }
  2801. }
  2802. /* close each decoder */
  2803. for (i = 0; i < nb_input_streams; i++) {
  2804. ist = input_streams[i];
  2805. if (ist->decoding_needed) {
  2806. avcodec_close(ist->st->codec);
  2807. }
  2808. }
  2809. /* finished ! */
  2810. ret = 0;
  2811. fail:
  2812. #if HAVE_PTHREADS
  2813. free_input_threads();
  2814. #endif
  2815. if (output_streams) {
  2816. for (i = 0; i < nb_output_streams; i++) {
  2817. ost = output_streams[i];
  2818. if (ost) {
  2819. if (ost->stream_copy)
  2820. av_freep(&ost->st->codec->extradata);
  2821. if (ost->logfile) {
  2822. fclose(ost->logfile);
  2823. ost->logfile = NULL;
  2824. }
  2825. av_freep(&ost->st->codec->subtitle_header);
  2826. av_free(ost->forced_kf_pts);
  2827. av_dict_free(&ost->opts);
  2828. av_dict_free(&ost->swr_opts);
  2829. av_dict_free(&ost->resample_opts);
  2830. }
  2831. }
  2832. }
  2833. return ret;
  2834. }
  2835. static int64_t getutime(void)
  2836. {
  2837. #if HAVE_GETRUSAGE
  2838. struct rusage rusage;
  2839. getrusage(RUSAGE_SELF, &rusage);
  2840. return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
  2841. #elif HAVE_GETPROCESSTIMES
  2842. HANDLE proc;
  2843. FILETIME c, e, k, u;
  2844. proc = GetCurrentProcess();
  2845. GetProcessTimes(proc, &c, &e, &k, &u);
  2846. return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
  2847. #else
  2848. return av_gettime();
  2849. #endif
  2850. }
  2851. static int64_t getmaxrss(void)
  2852. {
  2853. #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
  2854. struct rusage rusage;
  2855. getrusage(RUSAGE_SELF, &rusage);
  2856. return (int64_t)rusage.ru_maxrss * 1024;
  2857. #elif HAVE_GETPROCESSMEMORYINFO
  2858. HANDLE proc;
  2859. PROCESS_MEMORY_COUNTERS memcounters;
  2860. proc = GetCurrentProcess();
  2861. memcounters.cb = sizeof(memcounters);
  2862. GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
  2863. return memcounters.PeakPagefileUsage;
  2864. #else
  2865. return 0;
  2866. #endif
  2867. }
  2868. static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
  2869. {
  2870. }
  2871. int main(int argc, char **argv)
  2872. {
  2873. int ret;
  2874. int64_t ti;
  2875. atexit(exit_program);
  2876. setvbuf(stderr,NULL,_IONBF,0); /* win32 runtime needs this */
  2877. av_log_set_flags(AV_LOG_SKIP_REPEATED);
  2878. parse_loglevel(argc, argv, options);
  2879. if(argc>1 && !strcmp(argv[1], "-d")){
  2880. run_as_daemon=1;
  2881. av_log_set_callback(log_callback_null);
  2882. argc--;
  2883. argv++;
  2884. }
  2885. avcodec_register_all();
  2886. #if CONFIG_AVDEVICE
  2887. avdevice_register_all();
  2888. #endif
  2889. avfilter_register_all();
  2890. av_register_all();
  2891. avformat_network_init();
  2892. show_banner(argc, argv, options);
  2893. term_init();
  2894. /* parse options and open all input/output files */
  2895. ret = ffmpeg_parse_options(argc, argv);
  2896. if (ret < 0)
  2897. exit(1);
  2898. if (nb_output_files <= 0 && nb_input_files == 0) {
  2899. show_usage();
  2900. av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
  2901. exit(1);
  2902. }
  2903. /* file converter / grab */
  2904. if (nb_output_files <= 0) {
  2905. av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
  2906. exit(1);
  2907. }
  2908. // if (nb_input_files == 0) {
  2909. // av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
  2910. // exit(1);
  2911. // }
  2912. current_time = ti = getutime();
  2913. if (transcode() < 0)
  2914. exit(1);
  2915. ti = getutime() - ti;
  2916. if (do_benchmark) {
  2917. printf("bench: utime=%0.3fs\n", ti / 1000000.0);
  2918. }
  2919. exit(received_nb_signals ? 255 : 0);
  2920. return 0;
  2921. }