ffmpeg.c 136 KB

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