ffmpeg.c 129 KB

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