ffmpeg.c 108 KB

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