ffmpeg.c 108 KB

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