avconv.c 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846
  1. /*
  2. * avconv main
  3. * Copyright (c) 2000-2011 The Libav developers
  4. *
  5. * This file is part of Libav.
  6. *
  7. * Libav is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * Libav is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with Libav; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "config.h"
  22. #include <ctype.h>
  23. #include <string.h>
  24. #include <math.h>
  25. #include <stdlib.h>
  26. #include <errno.h>
  27. #include <signal.h>
  28. #include <limits.h>
  29. #include <stdint.h>
  30. #include "libavformat/avformat.h"
  31. #include "libavdevice/avdevice.h"
  32. #include "libswscale/swscale.h"
  33. #include "libavresample/avresample.h"
  34. #include "libavutil/opt.h"
  35. #include "libavutil/channel_layout.h"
  36. #include "libavutil/parseutils.h"
  37. #include "libavutil/samplefmt.h"
  38. #include "libavutil/fifo.h"
  39. #include "libavutil/internal.h"
  40. #include "libavutil/intreadwrite.h"
  41. #include "libavutil/dict.h"
  42. #include "libavutil/mathematics.h"
  43. #include "libavutil/pixdesc.h"
  44. #include "libavutil/avstring.h"
  45. #include "libavutil/libm.h"
  46. #include "libavutil/imgutils.h"
  47. #include "libavutil/time.h"
  48. #include "libavformat/os_support.h"
  49. # include "libavfilter/avfilter.h"
  50. # include "libavfilter/buffersrc.h"
  51. # include "libavfilter/buffersink.h"
  52. #if HAVE_SYS_RESOURCE_H
  53. #include <sys/time.h>
  54. #include <sys/types.h>
  55. #include <sys/resource.h>
  56. #elif HAVE_GETPROCESSTIMES
  57. #include <windows.h>
  58. #endif
  59. #if HAVE_GETPROCESSMEMORYINFO
  60. #include <windows.h>
  61. #include <psapi.h>
  62. #endif
  63. #if HAVE_SYS_SELECT_H
  64. #include <sys/select.h>
  65. #endif
  66. #if HAVE_PTHREADS
  67. #include <pthread.h>
  68. #endif
  69. #include <time.h>
  70. #include "avconv.h"
  71. #include "cmdutils.h"
  72. #include "libavutil/avassert.h"
  73. const char program_name[] = "avconv";
  74. const int program_birth_year = 2000;
  75. static FILE *vstats_file;
  76. static int nb_frames_drop = 0;
  77. #if HAVE_PTHREADS
  78. /* signal to input threads that they should exit; set by the main thread */
  79. static int transcoding_finished;
  80. #endif
  81. InputStream **input_streams = NULL;
  82. int nb_input_streams = 0;
  83. InputFile **input_files = NULL;
  84. int nb_input_files = 0;
  85. OutputStream **output_streams = NULL;
  86. int nb_output_streams = 0;
  87. OutputFile **output_files = NULL;
  88. int nb_output_files = 0;
  89. FilterGraph **filtergraphs;
  90. int nb_filtergraphs;
  91. static void term_exit(void)
  92. {
  93. av_log(NULL, AV_LOG_QUIET, "");
  94. }
  95. static volatile int received_sigterm = 0;
  96. static volatile int received_nb_signals = 0;
  97. static void
  98. sigterm_handler(int sig)
  99. {
  100. received_sigterm = sig;
  101. received_nb_signals++;
  102. term_exit();
  103. }
  104. static void term_init(void)
  105. {
  106. signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
  107. signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
  108. #ifdef SIGXCPU
  109. signal(SIGXCPU, sigterm_handler);
  110. #endif
  111. }
  112. static int decode_interrupt_cb(void *ctx)
  113. {
  114. return received_nb_signals > 1;
  115. }
  116. const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
  117. static void avconv_cleanup(int ret)
  118. {
  119. int i, j;
  120. for (i = 0; i < nb_filtergraphs; i++) {
  121. FilterGraph *fg = filtergraphs[i];
  122. avfilter_graph_free(&fg->graph);
  123. for (j = 0; j < fg->nb_inputs; j++) {
  124. av_freep(&fg->inputs[j]->name);
  125. av_freep(&fg->inputs[j]);
  126. }
  127. av_freep(&fg->inputs);
  128. for (j = 0; j < fg->nb_outputs; j++) {
  129. av_freep(&fg->outputs[j]->name);
  130. av_freep(&fg->outputs[j]);
  131. }
  132. av_freep(&fg->outputs);
  133. av_freep(&fg->graph_desc);
  134. av_freep(&filtergraphs[i]);
  135. }
  136. av_freep(&filtergraphs);
  137. /* close files */
  138. for (i = 0; i < nb_output_files; i++) {
  139. OutputFile *of = output_files[i];
  140. AVFormatContext *s = of->ctx;
  141. if (s && s->oformat && !(s->oformat->flags & AVFMT_NOFILE) && s->pb)
  142. avio_close(s->pb);
  143. avformat_free_context(s);
  144. av_dict_free(&of->opts);
  145. av_freep(&output_files[i]);
  146. }
  147. for (i = 0; i < nb_output_streams; i++) {
  148. OutputStream *ost = output_streams[i];
  149. for (j = 0; j < ost->nb_bitstream_filters; j++)
  150. av_bsf_free(&ost->bsf_ctx[j]);
  151. av_freep(&ost->bsf_ctx);
  152. av_freep(&ost->bitstream_filters);
  153. av_frame_free(&ost->filtered_frame);
  154. av_parser_close(ost->parser);
  155. avcodec_free_context(&ost->parser_avctx);
  156. av_freep(&ost->forced_keyframes);
  157. av_freep(&ost->avfilter);
  158. av_freep(&ost->logfile_prefix);
  159. avcodec_free_context(&ost->enc_ctx);
  160. av_freep(&output_streams[i]);
  161. }
  162. for (i = 0; i < nb_input_files; i++) {
  163. avformat_close_input(&input_files[i]->ctx);
  164. av_freep(&input_files[i]);
  165. }
  166. for (i = 0; i < nb_input_streams; i++) {
  167. InputStream *ist = input_streams[i];
  168. av_frame_free(&ist->decoded_frame);
  169. av_frame_free(&ist->filter_frame);
  170. av_dict_free(&ist->decoder_opts);
  171. av_freep(&ist->filters);
  172. av_freep(&ist->hwaccel_device);
  173. avcodec_free_context(&ist->dec_ctx);
  174. av_freep(&input_streams[i]);
  175. }
  176. if (vstats_file)
  177. fclose(vstats_file);
  178. av_free(vstats_filename);
  179. av_freep(&input_streams);
  180. av_freep(&input_files);
  181. av_freep(&output_streams);
  182. av_freep(&output_files);
  183. uninit_opts();
  184. avformat_network_deinit();
  185. if (received_sigterm) {
  186. av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
  187. (int) received_sigterm);
  188. exit (255);
  189. }
  190. }
  191. void assert_avoptions(AVDictionary *m)
  192. {
  193. AVDictionaryEntry *t;
  194. if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
  195. av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
  196. exit_program(1);
  197. }
  198. }
  199. static void abort_codec_experimental(AVCodec *c, int encoder)
  200. {
  201. const char *codec_string = encoder ? "encoder" : "decoder";
  202. AVCodec *codec;
  203. av_log(NULL, AV_LOG_FATAL, "%s '%s' is experimental and might produce bad "
  204. "results.\nAdd '-strict experimental' if you want to use it.\n",
  205. codec_string, c->name);
  206. codec = encoder ? avcodec_find_encoder(c->id) : avcodec_find_decoder(c->id);
  207. if (!(codec->capabilities & AV_CODEC_CAP_EXPERIMENTAL))
  208. av_log(NULL, AV_LOG_FATAL, "Or use the non experimental %s '%s'.\n",
  209. codec_string, codec->name);
  210. exit_program(1);
  211. }
  212. static void write_packet(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)
  213. {
  214. AVStream *st = ost->st;
  215. int ret;
  216. /*
  217. * Audio encoders may split the packets -- #frames in != #packets out.
  218. * But there is no reordering, so we can limit the number of output packets
  219. * by simply dropping them here.
  220. * Counting encoded video frames needs to be done separately because of
  221. * reordering, see do_video_out()
  222. */
  223. if (!(st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && ost->encoding_needed)) {
  224. if (ost->frame_number >= ost->max_frames) {
  225. av_packet_unref(pkt);
  226. return;
  227. }
  228. ost->frame_number++;
  229. }
  230. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  231. uint8_t *sd = av_packet_get_side_data(pkt, AV_PKT_DATA_QUALITY_FACTOR,
  232. NULL);
  233. ost->quality = sd ? *(int *)sd : -1;
  234. if (ost->frame_rate.num) {
  235. pkt->duration = av_rescale_q(1, av_inv_q(ost->frame_rate),
  236. ost->st->time_base);
  237. }
  238. }
  239. if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS) &&
  240. ost->last_mux_dts != AV_NOPTS_VALUE &&
  241. pkt->dts < ost->last_mux_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT)) {
  242. av_log(NULL, AV_LOG_WARNING, "Non-monotonous DTS in output stream "
  243. "%d:%d; previous: %"PRId64", current: %"PRId64"; ",
  244. ost->file_index, ost->st->index, ost->last_mux_dts, pkt->dts);
  245. if (exit_on_error) {
  246. av_log(NULL, AV_LOG_FATAL, "aborting.\n");
  247. exit_program(1);
  248. }
  249. av_log(NULL, AV_LOG_WARNING, "changing to %"PRId64". This may result "
  250. "in incorrect timestamps in the output file.\n",
  251. ost->last_mux_dts + 1);
  252. pkt->dts = ost->last_mux_dts + 1;
  253. if (pkt->pts != AV_NOPTS_VALUE)
  254. pkt->pts = FFMAX(pkt->pts, pkt->dts);
  255. }
  256. ost->last_mux_dts = pkt->dts;
  257. ost->data_size += pkt->size;
  258. ost->packets_written++;
  259. pkt->stream_index = ost->index;
  260. ret = av_interleaved_write_frame(s, pkt);
  261. if (ret < 0) {
  262. print_error("av_interleaved_write_frame()", ret);
  263. exit_program(1);
  264. }
  265. }
  266. static void output_packet(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)
  267. {
  268. int ret = 0;
  269. /* apply the output bitstream filters, if any */
  270. if (ost->nb_bitstream_filters) {
  271. int idx;
  272. ret = av_bsf_send_packet(ost->bsf_ctx[0], pkt);
  273. if (ret < 0)
  274. goto finish;
  275. idx = 1;
  276. while (idx) {
  277. /* get a packet from the previous filter up the chain */
  278. ret = av_bsf_receive_packet(ost->bsf_ctx[idx - 1], pkt);
  279. if (ret == AVERROR(EAGAIN)) {
  280. ret = 0;
  281. idx--;
  282. continue;
  283. } else if (ret < 0)
  284. goto finish;
  285. /* send it to the next filter down the chain or to the muxer */
  286. if (idx < ost->nb_bitstream_filters) {
  287. ret = av_bsf_send_packet(ost->bsf_ctx[idx], pkt);
  288. if (ret < 0)
  289. goto finish;
  290. idx++;
  291. } else
  292. write_packet(s, pkt, ost);
  293. }
  294. } else
  295. write_packet(s, pkt, ost);
  296. finish:
  297. if (ret < 0 && ret != AVERROR_EOF) {
  298. av_log(NULL, AV_LOG_FATAL, "Error applying bitstream filters to an output "
  299. "packet for stream #%d:%d.\n", ost->file_index, ost->index);
  300. exit_program(1);
  301. }
  302. }
  303. static int check_recording_time(OutputStream *ost)
  304. {
  305. OutputFile *of = output_files[ost->file_index];
  306. if (of->recording_time != INT64_MAX &&
  307. av_compare_ts(ost->sync_opts - ost->first_pts, ost->enc_ctx->time_base, of->recording_time,
  308. AV_TIME_BASE_Q) >= 0) {
  309. ost->finished = 1;
  310. return 0;
  311. }
  312. return 1;
  313. }
  314. static void do_audio_out(AVFormatContext *s, OutputStream *ost,
  315. AVFrame *frame)
  316. {
  317. AVCodecContext *enc = ost->enc_ctx;
  318. AVPacket pkt;
  319. int ret;
  320. av_init_packet(&pkt);
  321. pkt.data = NULL;
  322. pkt.size = 0;
  323. if (frame->pts == AV_NOPTS_VALUE || audio_sync_method < 0)
  324. frame->pts = ost->sync_opts;
  325. ost->sync_opts = frame->pts + frame->nb_samples;
  326. ost->samples_encoded += frame->nb_samples;
  327. ost->frames_encoded++;
  328. ret = avcodec_send_frame(enc, frame);
  329. if (ret < 0)
  330. goto error;
  331. while (1) {
  332. ret = avcodec_receive_packet(enc, &pkt);
  333. if (ret == AVERROR(EAGAIN))
  334. break;
  335. if (ret < 0)
  336. goto error;
  337. av_packet_rescale_ts(&pkt, enc->time_base, ost->st->time_base);
  338. output_packet(s, &pkt, ost);
  339. }
  340. return;
  341. error:
  342. av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
  343. exit_program(1);
  344. }
  345. static void do_subtitle_out(AVFormatContext *s,
  346. OutputStream *ost,
  347. InputStream *ist,
  348. AVSubtitle *sub,
  349. int64_t pts)
  350. {
  351. static uint8_t *subtitle_out = NULL;
  352. int subtitle_out_max_size = 1024 * 1024;
  353. int subtitle_out_size, nb, i;
  354. AVCodecContext *enc;
  355. AVPacket pkt;
  356. if (pts == AV_NOPTS_VALUE) {
  357. av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
  358. if (exit_on_error)
  359. exit_program(1);
  360. return;
  361. }
  362. enc = ost->enc_ctx;
  363. if (!subtitle_out) {
  364. subtitle_out = av_malloc(subtitle_out_max_size);
  365. }
  366. /* Note: DVB subtitle need one packet to draw them and one other
  367. packet to clear them */
  368. /* XXX: signal it in the codec context ? */
  369. if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
  370. nb = 2;
  371. else
  372. nb = 1;
  373. for (i = 0; i < nb; i++) {
  374. ost->sync_opts = av_rescale_q(pts, ist->st->time_base, enc->time_base);
  375. if (!check_recording_time(ost))
  376. return;
  377. sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
  378. // start_display_time is required to be 0
  379. sub->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
  380. sub->end_display_time -= sub->start_display_time;
  381. sub->start_display_time = 0;
  382. ost->frames_encoded++;
  383. subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
  384. subtitle_out_max_size, sub);
  385. if (subtitle_out_size < 0) {
  386. av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
  387. exit_program(1);
  388. }
  389. av_init_packet(&pkt);
  390. pkt.data = subtitle_out;
  391. pkt.size = subtitle_out_size;
  392. pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
  393. if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
  394. /* XXX: the pts correction is handled here. Maybe handling
  395. it in the codec would be better */
  396. if (i == 0)
  397. pkt.pts += 90 * sub->start_display_time;
  398. else
  399. pkt.pts += 90 * sub->end_display_time;
  400. }
  401. output_packet(s, &pkt, ost);
  402. }
  403. }
  404. static void do_video_out(AVFormatContext *s,
  405. OutputStream *ost,
  406. AVFrame *in_picture,
  407. int *frame_size)
  408. {
  409. int ret, format_video_sync;
  410. AVPacket pkt;
  411. AVCodecContext *enc = ost->enc_ctx;
  412. *frame_size = 0;
  413. format_video_sync = video_sync_method;
  414. if (format_video_sync == VSYNC_AUTO)
  415. format_video_sync = (s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH :
  416. (s->oformat->flags & AVFMT_VARIABLE_FPS) ? VSYNC_VFR : VSYNC_CFR;
  417. if (format_video_sync != VSYNC_PASSTHROUGH &&
  418. ost->frame_number &&
  419. in_picture->pts != AV_NOPTS_VALUE &&
  420. in_picture->pts < ost->sync_opts) {
  421. nb_frames_drop++;
  422. av_log(NULL, AV_LOG_WARNING,
  423. "*** dropping frame %d from stream %d at ts %"PRId64"\n",
  424. ost->frame_number, ost->st->index, in_picture->pts);
  425. return;
  426. }
  427. if (in_picture->pts == AV_NOPTS_VALUE)
  428. in_picture->pts = ost->sync_opts;
  429. ost->sync_opts = in_picture->pts;
  430. if (!ost->frame_number)
  431. ost->first_pts = in_picture->pts;
  432. av_init_packet(&pkt);
  433. pkt.data = NULL;
  434. pkt.size = 0;
  435. if (ost->frame_number >= ost->max_frames)
  436. return;
  437. if (enc->flags & (AV_CODEC_FLAG_INTERLACED_DCT | AV_CODEC_FLAG_INTERLACED_ME) &&
  438. ost->top_field_first >= 0)
  439. in_picture->top_field_first = !!ost->top_field_first;
  440. in_picture->quality = enc->global_quality;
  441. in_picture->pict_type = 0;
  442. if (ost->forced_kf_index < ost->forced_kf_count &&
  443. in_picture->pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
  444. in_picture->pict_type = AV_PICTURE_TYPE_I;
  445. ost->forced_kf_index++;
  446. }
  447. ost->frames_encoded++;
  448. ret = avcodec_send_frame(enc, in_picture);
  449. if (ret < 0)
  450. goto error;
  451. /*
  452. * For video, there may be reordering, so we can't throw away frames on
  453. * encoder flush, we need to limit them here, before they go into encoder.
  454. */
  455. ost->frame_number++;
  456. while (1) {
  457. ret = avcodec_receive_packet(enc, &pkt);
  458. if (ret == AVERROR(EAGAIN))
  459. break;
  460. if (ret < 0)
  461. goto error;
  462. av_packet_rescale_ts(&pkt, enc->time_base, ost->st->time_base);
  463. output_packet(s, &pkt, ost);
  464. *frame_size = pkt.size;
  465. /* if two pass, output log */
  466. if (ost->logfile && enc->stats_out) {
  467. fprintf(ost->logfile, "%s", enc->stats_out);
  468. }
  469. ost->sync_opts++;
  470. }
  471. return;
  472. error:
  473. av_assert0(ret != AVERROR(EAGAIN) && ret != AVERROR_EOF);
  474. av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
  475. exit_program(1);
  476. }
  477. #if FF_API_CODED_FRAME && FF_API_ERROR_FRAME
  478. static double psnr(double d)
  479. {
  480. return -10.0 * log(d) / log(10.0);
  481. }
  482. #endif
  483. static void do_video_stats(OutputStream *ost, int frame_size)
  484. {
  485. AVCodecContext *enc;
  486. int frame_number;
  487. double ti1, bitrate, avg_bitrate;
  488. /* this is executed just the first time do_video_stats is called */
  489. if (!vstats_file) {
  490. vstats_file = fopen(vstats_filename, "w");
  491. if (!vstats_file) {
  492. perror("fopen");
  493. exit_program(1);
  494. }
  495. }
  496. enc = ost->enc_ctx;
  497. if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  498. frame_number = ost->frame_number;
  499. fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number,
  500. ost->quality / (float)FF_QP2LAMBDA);
  501. #if FF_API_CODED_FRAME && FF_API_ERROR_FRAME
  502. FF_DISABLE_DEPRECATION_WARNINGS
  503. if (enc->flags & AV_CODEC_FLAG_PSNR)
  504. fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
  505. FF_ENABLE_DEPRECATION_WARNINGS
  506. #endif
  507. fprintf(vstats_file,"f_size= %6d ", frame_size);
  508. /* compute pts value */
  509. ti1 = ost->sync_opts * av_q2d(enc->time_base);
  510. if (ti1 < 0.01)
  511. ti1 = 0.01;
  512. bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
  513. avg_bitrate = (double)(ost->data_size * 8) / ti1 / 1000.0;
  514. fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
  515. (double)ost->data_size / 1024, ti1, bitrate, avg_bitrate);
  516. #if FF_API_CODED_FRAME
  517. FF_DISABLE_DEPRECATION_WARNINGS
  518. fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
  519. FF_ENABLE_DEPRECATION_WARNINGS
  520. #endif
  521. }
  522. }
  523. /*
  524. * Read one frame for lavfi output for ost and encode it.
  525. */
  526. static int poll_filter(OutputStream *ost)
  527. {
  528. OutputFile *of = output_files[ost->file_index];
  529. AVFrame *filtered_frame = NULL;
  530. int frame_size, ret;
  531. if (!ost->filtered_frame && !(ost->filtered_frame = av_frame_alloc())) {
  532. return AVERROR(ENOMEM);
  533. }
  534. filtered_frame = ost->filtered_frame;
  535. if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
  536. !(ost->enc->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE))
  537. ret = av_buffersink_get_samples(ost->filter->filter, filtered_frame,
  538. ost->enc_ctx->frame_size);
  539. else
  540. ret = av_buffersink_get_frame(ost->filter->filter, filtered_frame);
  541. if (ret < 0)
  542. return ret;
  543. if (filtered_frame->pts != AV_NOPTS_VALUE) {
  544. int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
  545. filtered_frame->pts = av_rescale_q(filtered_frame->pts,
  546. ost->filter->filter->inputs[0]->time_base,
  547. ost->enc_ctx->time_base) -
  548. av_rescale_q(start_time,
  549. AV_TIME_BASE_Q,
  550. ost->enc_ctx->time_base);
  551. }
  552. switch (ost->filter->filter->inputs[0]->type) {
  553. case AVMEDIA_TYPE_VIDEO:
  554. if (!ost->frame_aspect_ratio)
  555. ost->enc_ctx->sample_aspect_ratio = filtered_frame->sample_aspect_ratio;
  556. do_video_out(of->ctx, ost, filtered_frame, &frame_size);
  557. if (vstats_filename && frame_size)
  558. do_video_stats(ost, frame_size);
  559. break;
  560. case AVMEDIA_TYPE_AUDIO:
  561. do_audio_out(of->ctx, ost, filtered_frame);
  562. break;
  563. default:
  564. // TODO support subtitle filters
  565. av_assert0(0);
  566. }
  567. av_frame_unref(filtered_frame);
  568. return 0;
  569. }
  570. static void finish_output_stream(OutputStream *ost)
  571. {
  572. OutputFile *of = output_files[ost->file_index];
  573. int i;
  574. ost->finished = 1;
  575. if (of->shortest) {
  576. for (i = 0; i < of->ctx->nb_streams; i++)
  577. output_streams[of->ost_index + i]->finished = 1;
  578. }
  579. }
  580. /*
  581. * Read as many frames from possible from lavfi and encode them.
  582. *
  583. * Always read from the active stream with the lowest timestamp. If no frames
  584. * are available for it then return EAGAIN and wait for more input. This way we
  585. * can use lavfi sources that generate unlimited amount of frames without memory
  586. * usage exploding.
  587. */
  588. static int poll_filters(void)
  589. {
  590. int i, ret = 0;
  591. while (ret >= 0 && !received_sigterm) {
  592. OutputStream *ost = NULL;
  593. int64_t min_pts = INT64_MAX;
  594. /* choose output stream with the lowest timestamp */
  595. for (i = 0; i < nb_output_streams; i++) {
  596. int64_t pts = output_streams[i]->sync_opts;
  597. if (!output_streams[i]->filter || output_streams[i]->finished)
  598. continue;
  599. pts = av_rescale_q(pts, output_streams[i]->enc_ctx->time_base,
  600. AV_TIME_BASE_Q);
  601. if (pts < min_pts) {
  602. min_pts = pts;
  603. ost = output_streams[i];
  604. }
  605. }
  606. if (!ost)
  607. break;
  608. ret = poll_filter(ost);
  609. if (ret == AVERROR_EOF) {
  610. finish_output_stream(ost);
  611. ret = 0;
  612. } else if (ret == AVERROR(EAGAIN))
  613. return 0;
  614. }
  615. return ret;
  616. }
  617. static void print_final_stats(int64_t total_size)
  618. {
  619. uint64_t video_size = 0, audio_size = 0, extra_size = 0, other_size = 0;
  620. uint64_t data_size = 0;
  621. float percent = -1.0;
  622. int i, j;
  623. for (i = 0; i < nb_output_streams; i++) {
  624. OutputStream *ost = output_streams[i];
  625. switch (ost->enc_ctx->codec_type) {
  626. case AVMEDIA_TYPE_VIDEO: video_size += ost->data_size; break;
  627. case AVMEDIA_TYPE_AUDIO: audio_size += ost->data_size; break;
  628. default: other_size += ost->data_size; break;
  629. }
  630. extra_size += ost->enc_ctx->extradata_size;
  631. data_size += ost->data_size;
  632. }
  633. if (data_size && total_size >= data_size)
  634. percent = 100.0 * (total_size - data_size) / data_size;
  635. av_log(NULL, AV_LOG_INFO, "\n");
  636. av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB other streams:%1.0fkB global headers:%1.0fkB muxing overhead: ",
  637. video_size / 1024.0,
  638. audio_size / 1024.0,
  639. other_size / 1024.0,
  640. extra_size / 1024.0);
  641. if (percent >= 0.0)
  642. av_log(NULL, AV_LOG_INFO, "%f%%", percent);
  643. else
  644. av_log(NULL, AV_LOG_INFO, "unknown");
  645. av_log(NULL, AV_LOG_INFO, "\n");
  646. /* print verbose per-stream stats */
  647. for (i = 0; i < nb_input_files; i++) {
  648. InputFile *f = input_files[i];
  649. uint64_t total_packets = 0, total_size = 0;
  650. av_log(NULL, AV_LOG_VERBOSE, "Input file #%d (%s):\n",
  651. i, f->ctx->filename);
  652. for (j = 0; j < f->nb_streams; j++) {
  653. InputStream *ist = input_streams[f->ist_index + j];
  654. enum AVMediaType type = ist->dec_ctx->codec_type;
  655. total_size += ist->data_size;
  656. total_packets += ist->nb_packets;
  657. av_log(NULL, AV_LOG_VERBOSE, " Input stream #%d:%d (%s): ",
  658. i, j, media_type_string(type));
  659. av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" packets read (%"PRIu64" bytes); ",
  660. ist->nb_packets, ist->data_size);
  661. if (ist->decoding_needed) {
  662. av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" frames decoded",
  663. ist->frames_decoded);
  664. if (type == AVMEDIA_TYPE_AUDIO)
  665. av_log(NULL, AV_LOG_VERBOSE, " (%"PRIu64" samples)", ist->samples_decoded);
  666. av_log(NULL, AV_LOG_VERBOSE, "; ");
  667. }
  668. av_log(NULL, AV_LOG_VERBOSE, "\n");
  669. }
  670. av_log(NULL, AV_LOG_VERBOSE, " Total: %"PRIu64" packets (%"PRIu64" bytes) demuxed\n",
  671. total_packets, total_size);
  672. }
  673. for (i = 0; i < nb_output_files; i++) {
  674. OutputFile *of = output_files[i];
  675. uint64_t total_packets = 0, total_size = 0;
  676. av_log(NULL, AV_LOG_VERBOSE, "Output file #%d (%s):\n",
  677. i, of->ctx->filename);
  678. for (j = 0; j < of->ctx->nb_streams; j++) {
  679. OutputStream *ost = output_streams[of->ost_index + j];
  680. enum AVMediaType type = ost->enc_ctx->codec_type;
  681. total_size += ost->data_size;
  682. total_packets += ost->packets_written;
  683. av_log(NULL, AV_LOG_VERBOSE, " Output stream #%d:%d (%s): ",
  684. i, j, media_type_string(type));
  685. if (ost->encoding_needed) {
  686. av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" frames encoded",
  687. ost->frames_encoded);
  688. if (type == AVMEDIA_TYPE_AUDIO)
  689. av_log(NULL, AV_LOG_VERBOSE, " (%"PRIu64" samples)", ost->samples_encoded);
  690. av_log(NULL, AV_LOG_VERBOSE, "; ");
  691. }
  692. av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" packets muxed (%"PRIu64" bytes); ",
  693. ost->packets_written, ost->data_size);
  694. av_log(NULL, AV_LOG_VERBOSE, "\n");
  695. }
  696. av_log(NULL, AV_LOG_VERBOSE, " Total: %"PRIu64" packets (%"PRIu64" bytes) muxed\n",
  697. total_packets, total_size);
  698. }
  699. }
  700. static void print_report(int is_last_report, int64_t timer_start)
  701. {
  702. char buf[1024];
  703. OutputStream *ost;
  704. AVFormatContext *oc;
  705. int64_t total_size;
  706. AVCodecContext *enc;
  707. int frame_number, vid, i;
  708. double bitrate, ti1, pts;
  709. static int64_t last_time = -1;
  710. static int qp_histogram[52];
  711. if (!print_stats && !is_last_report)
  712. return;
  713. if (!is_last_report) {
  714. int64_t cur_time;
  715. /* display the report every 0.5 seconds */
  716. cur_time = av_gettime_relative();
  717. if (last_time == -1) {
  718. last_time = cur_time;
  719. return;
  720. }
  721. if ((cur_time - last_time) < 500000)
  722. return;
  723. last_time = cur_time;
  724. }
  725. oc = output_files[0]->ctx;
  726. total_size = avio_size(oc->pb);
  727. if (total_size <= 0) // FIXME improve avio_size() so it works with non seekable output too
  728. total_size = avio_tell(oc->pb);
  729. if (total_size < 0) {
  730. char errbuf[128];
  731. av_strerror(total_size, errbuf, sizeof(errbuf));
  732. av_log(NULL, AV_LOG_VERBOSE, "Bitrate not available, "
  733. "avio_tell() failed: %s\n", errbuf);
  734. total_size = 0;
  735. }
  736. buf[0] = '\0';
  737. ti1 = 1e10;
  738. vid = 0;
  739. for (i = 0; i < nb_output_streams; i++) {
  740. float q = -1;
  741. ost = output_streams[i];
  742. enc = ost->enc_ctx;
  743. if (!ost->stream_copy)
  744. q = ost->quality / (float) FF_QP2LAMBDA;
  745. if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  746. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
  747. }
  748. if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  749. float t = (av_gettime_relative() - timer_start) / 1000000.0;
  750. frame_number = ost->frame_number;
  751. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3d q=%3.1f ",
  752. frame_number, (t > 1) ? (int)(frame_number / t + 0.5) : 0, q);
  753. if (is_last_report)
  754. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
  755. if (qp_hist) {
  756. int j;
  757. int qp = lrintf(q);
  758. if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
  759. qp_histogram[qp]++;
  760. for (j = 0; j < 32; j++)
  761. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log2(qp_histogram[j] + 1)));
  762. }
  763. #if FF_API_CODED_FRAME && FF_API_ERROR_FRAME
  764. FF_DISABLE_DEPRECATION_WARNINGS
  765. if (enc->flags & AV_CODEC_FLAG_PSNR) {
  766. int j;
  767. double error, error_sum = 0;
  768. double scale, scale_sum = 0;
  769. char type[3] = { 'Y','U','V' };
  770. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
  771. for (j = 0; j < 3; j++) {
  772. if (is_last_report) {
  773. error = enc->error[j];
  774. scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
  775. } else {
  776. error = enc->coded_frame->error[j];
  777. scale = enc->width * enc->height * 255.0 * 255.0;
  778. }
  779. if (j)
  780. scale /= 4;
  781. error_sum += error;
  782. scale_sum += scale;
  783. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error / scale));
  784. }
  785. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
  786. }
  787. FF_ENABLE_DEPRECATION_WARNINGS
  788. #endif
  789. vid = 1;
  790. }
  791. /* compute min output value */
  792. pts = (double)ost->last_mux_dts * av_q2d(ost->st->time_base);
  793. if ((pts < ti1) && (pts > 0))
  794. ti1 = pts;
  795. }
  796. if (ti1 < 0.01)
  797. ti1 = 0.01;
  798. bitrate = (double)(total_size * 8) / ti1 / 1000.0;
  799. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  800. "size=%8.0fkB time=%0.2f bitrate=%6.1fkbits/s",
  801. (double)total_size / 1024, ti1, bitrate);
  802. if (nb_frames_drop)
  803. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " drop=%d",
  804. nb_frames_drop);
  805. av_log(NULL, AV_LOG_INFO, "%s \r", buf);
  806. fflush(stderr);
  807. if (is_last_report)
  808. print_final_stats(total_size);
  809. }
  810. static void flush_encoders(void)
  811. {
  812. int i, ret;
  813. for (i = 0; i < nb_output_streams; i++) {
  814. OutputStream *ost = output_streams[i];
  815. AVCodecContext *enc = ost->enc_ctx;
  816. AVFormatContext *os = output_files[ost->file_index]->ctx;
  817. int stop_encoding = 0;
  818. if (!ost->encoding_needed)
  819. continue;
  820. if (enc->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
  821. continue;
  822. if (enc->codec_type != AVMEDIA_TYPE_VIDEO && enc->codec_type != AVMEDIA_TYPE_AUDIO)
  823. continue;
  824. avcodec_send_frame(enc, NULL);
  825. for (;;) {
  826. const char *desc = NULL;
  827. switch (enc->codec_type) {
  828. case AVMEDIA_TYPE_AUDIO:
  829. desc = "Audio";
  830. break;
  831. case AVMEDIA_TYPE_VIDEO:
  832. desc = "Video";
  833. break;
  834. default:
  835. av_assert0(0);
  836. }
  837. if (1) {
  838. AVPacket pkt;
  839. av_init_packet(&pkt);
  840. pkt.data = NULL;
  841. pkt.size = 0;
  842. ret = avcodec_receive_packet(enc, &pkt);
  843. if (ret < 0 && ret != AVERROR_EOF) {
  844. av_log(NULL, AV_LOG_FATAL, "%s encoding failed\n", desc);
  845. exit_program(1);
  846. }
  847. if (ost->logfile && enc->stats_out) {
  848. fprintf(ost->logfile, "%s", enc->stats_out);
  849. }
  850. if (ret == AVERROR_EOF) {
  851. stop_encoding = 1;
  852. break;
  853. }
  854. av_packet_rescale_ts(&pkt, enc->time_base, ost->st->time_base);
  855. output_packet(os, &pkt, ost);
  856. }
  857. if (stop_encoding)
  858. break;
  859. }
  860. }
  861. }
  862. /*
  863. * Check whether a packet from ist should be written into ost at this time
  864. */
  865. static int check_output_constraints(InputStream *ist, OutputStream *ost)
  866. {
  867. OutputFile *of = output_files[ost->file_index];
  868. int ist_index = input_files[ist->file_index]->ist_index + ist->st->index;
  869. if (ost->source_index != ist_index)
  870. return 0;
  871. if (of->start_time != AV_NOPTS_VALUE && ist->last_dts < of->start_time)
  872. return 0;
  873. return 1;
  874. }
  875. static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
  876. {
  877. OutputFile *of = output_files[ost->file_index];
  878. InputFile *f = input_files [ist->file_index];
  879. int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
  880. int64_t ost_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q, ost->st->time_base);
  881. AVPacket opkt;
  882. av_init_packet(&opkt);
  883. if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
  884. !ost->copy_initial_nonkeyframes)
  885. return;
  886. if (of->recording_time != INT64_MAX &&
  887. ist->last_dts >= of->recording_time + start_time) {
  888. ost->finished = 1;
  889. return;
  890. }
  891. if (f->recording_time != INT64_MAX) {
  892. start_time = f->ctx->start_time;
  893. if (f->start_time != AV_NOPTS_VALUE)
  894. start_time += f->start_time;
  895. if (ist->last_dts >= f->recording_time + start_time) {
  896. ost->finished = 1;
  897. return;
  898. }
  899. }
  900. /* force the input stream PTS */
  901. if (ost->enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO)
  902. ost->sync_opts++;
  903. if (pkt->pts != AV_NOPTS_VALUE)
  904. opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
  905. else
  906. opkt.pts = AV_NOPTS_VALUE;
  907. if (pkt->dts == AV_NOPTS_VALUE)
  908. opkt.dts = av_rescale_q(ist->last_dts, AV_TIME_BASE_Q, ost->st->time_base);
  909. else
  910. opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
  911. opkt.dts -= ost_tb_start_time;
  912. opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
  913. opkt.flags = pkt->flags;
  914. // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
  915. if ( ost->enc_ctx->codec_id != AV_CODEC_ID_H264
  916. && ost->enc_ctx->codec_id != AV_CODEC_ID_MPEG1VIDEO
  917. && ost->enc_ctx->codec_id != AV_CODEC_ID_MPEG2VIDEO
  918. && ost->enc_ctx->codec_id != AV_CODEC_ID_VC1
  919. ) {
  920. if (av_parser_change(ost->parser, ost->parser_avctx,
  921. &opkt.data, &opkt.size,
  922. pkt->data, pkt->size,
  923. pkt->flags & AV_PKT_FLAG_KEY)) {
  924. opkt.buf = av_buffer_create(opkt.data, opkt.size, av_buffer_default_free, NULL, 0);
  925. if (!opkt.buf)
  926. exit_program(1);
  927. }
  928. } else {
  929. opkt.data = pkt->data;
  930. opkt.size = pkt->size;
  931. }
  932. output_packet(of->ctx, &opkt, ost);
  933. }
  934. // This does not quite work like avcodec_decode_audio4/avcodec_decode_video2.
  935. // There is the following difference: if you got a frame, you must call
  936. // it again with pkt=NULL. pkt==NULL is treated differently from pkt.size==0
  937. // (pkt==NULL means get more output, pkt.size==0 is a flush/drain packet)
  938. static int decode(AVCodecContext *avctx, AVFrame *frame, int *got_frame, AVPacket *pkt)
  939. {
  940. int ret;
  941. *got_frame = 0;
  942. if (pkt) {
  943. ret = avcodec_send_packet(avctx, pkt);
  944. // In particular, we don't expect AVERROR(EAGAIN), because we read all
  945. // decoded frames with avcodec_receive_frame() until done.
  946. if (ret < 0)
  947. return ret == AVERROR_EOF ? 0 : ret;
  948. }
  949. ret = avcodec_receive_frame(avctx, frame);
  950. if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
  951. return ret;
  952. if (ret >= 0)
  953. *got_frame = 1;
  954. return 0;
  955. }
  956. int guess_input_channel_layout(InputStream *ist)
  957. {
  958. AVCodecContext *dec = ist->dec_ctx;
  959. if (!dec->channel_layout) {
  960. char layout_name[256];
  961. dec->channel_layout = av_get_default_channel_layout(dec->channels);
  962. if (!dec->channel_layout)
  963. return 0;
  964. av_get_channel_layout_string(layout_name, sizeof(layout_name),
  965. dec->channels, dec->channel_layout);
  966. av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Input Stream "
  967. "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
  968. }
  969. return 1;
  970. }
  971. static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
  972. {
  973. AVFrame *decoded_frame, *f;
  974. AVCodecContext *avctx = ist->dec_ctx;
  975. int i, ret, err = 0, resample_changed;
  976. if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
  977. return AVERROR(ENOMEM);
  978. if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
  979. return AVERROR(ENOMEM);
  980. decoded_frame = ist->decoded_frame;
  981. ret = decode(avctx, decoded_frame, got_output, pkt);
  982. if (!*got_output || ret < 0)
  983. return ret;
  984. ist->samples_decoded += decoded_frame->nb_samples;
  985. ist->frames_decoded++;
  986. /* if the decoder provides a pts, use it instead of the last packet pts.
  987. the decoder could be delaying output by a packet or more. */
  988. if (decoded_frame->pts != AV_NOPTS_VALUE)
  989. ist->next_dts = decoded_frame->pts;
  990. else if (pkt && pkt->pts != AV_NOPTS_VALUE) {
  991. decoded_frame->pts = pkt->pts;
  992. }
  993. resample_changed = ist->resample_sample_fmt != decoded_frame->format ||
  994. ist->resample_channels != avctx->channels ||
  995. ist->resample_channel_layout != decoded_frame->channel_layout ||
  996. ist->resample_sample_rate != decoded_frame->sample_rate;
  997. if (resample_changed) {
  998. char layout1[64], layout2[64];
  999. if (!guess_input_channel_layout(ist)) {
  1000. av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
  1001. "layout for Input Stream #%d.%d\n", ist->file_index,
  1002. ist->st->index);
  1003. exit_program(1);
  1004. }
  1005. decoded_frame->channel_layout = avctx->channel_layout;
  1006. av_get_channel_layout_string(layout1, sizeof(layout1), ist->resample_channels,
  1007. ist->resample_channel_layout);
  1008. av_get_channel_layout_string(layout2, sizeof(layout2), avctx->channels,
  1009. decoded_frame->channel_layout);
  1010. av_log(NULL, AV_LOG_INFO,
  1011. "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",
  1012. ist->file_index, ist->st->index,
  1013. ist->resample_sample_rate, av_get_sample_fmt_name(ist->resample_sample_fmt),
  1014. ist->resample_channels, layout1,
  1015. decoded_frame->sample_rate, av_get_sample_fmt_name(decoded_frame->format),
  1016. avctx->channels, layout2);
  1017. ist->resample_sample_fmt = decoded_frame->format;
  1018. ist->resample_sample_rate = decoded_frame->sample_rate;
  1019. ist->resample_channel_layout = decoded_frame->channel_layout;
  1020. ist->resample_channels = avctx->channels;
  1021. for (i = 0; i < nb_filtergraphs; i++)
  1022. if (ist_in_filtergraph(filtergraphs[i], ist) &&
  1023. configure_filtergraph(filtergraphs[i]) < 0) {
  1024. av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
  1025. exit_program(1);
  1026. }
  1027. }
  1028. if (decoded_frame->pts != AV_NOPTS_VALUE)
  1029. decoded_frame->pts = av_rescale_q(decoded_frame->pts,
  1030. ist->st->time_base,
  1031. (AVRational){1, avctx->sample_rate});
  1032. ist->nb_samples = decoded_frame->nb_samples;
  1033. for (i = 0; i < ist->nb_filters; i++) {
  1034. if (i < ist->nb_filters - 1) {
  1035. f = ist->filter_frame;
  1036. err = av_frame_ref(f, decoded_frame);
  1037. if (err < 0)
  1038. break;
  1039. } else
  1040. f = decoded_frame;
  1041. err = av_buffersrc_add_frame(ist->filters[i]->filter, f);
  1042. if (err < 0)
  1043. break;
  1044. }
  1045. av_frame_unref(ist->filter_frame);
  1046. av_frame_unref(decoded_frame);
  1047. return err < 0 ? err : ret;
  1048. }
  1049. static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output)
  1050. {
  1051. AVFrame *decoded_frame, *f;
  1052. int i, ret = 0, err = 0, resample_changed;
  1053. if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
  1054. return AVERROR(ENOMEM);
  1055. if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
  1056. return AVERROR(ENOMEM);
  1057. decoded_frame = ist->decoded_frame;
  1058. ret = decode(ist->dec_ctx, decoded_frame, got_output, pkt);
  1059. if (!*got_output || ret < 0)
  1060. return ret;
  1061. ist->frames_decoded++;
  1062. if (ist->hwaccel_retrieve_data && decoded_frame->format == ist->hwaccel_pix_fmt) {
  1063. err = ist->hwaccel_retrieve_data(ist->dec_ctx, decoded_frame);
  1064. if (err < 0)
  1065. goto fail;
  1066. }
  1067. ist->hwaccel_retrieved_pix_fmt = decoded_frame->format;
  1068. decoded_frame->pts = guess_correct_pts(&ist->pts_ctx, decoded_frame->pkt_pts,
  1069. decoded_frame->pkt_dts);
  1070. if (ist->st->sample_aspect_ratio.num)
  1071. decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
  1072. resample_changed = ist->resample_width != decoded_frame->width ||
  1073. ist->resample_height != decoded_frame->height ||
  1074. ist->resample_pix_fmt != decoded_frame->format;
  1075. if (resample_changed) {
  1076. av_log(NULL, AV_LOG_INFO,
  1077. "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
  1078. ist->file_index, ist->st->index,
  1079. ist->resample_width, ist->resample_height, av_get_pix_fmt_name(ist->resample_pix_fmt),
  1080. decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
  1081. ret = poll_filters();
  1082. if (ret < 0 && ret != AVERROR_EOF) {
  1083. char errbuf[128];
  1084. av_strerror(ret, errbuf, sizeof(errbuf));
  1085. av_log(NULL, AV_LOG_ERROR, "Error while filtering: %s\n", errbuf);
  1086. }
  1087. ist->resample_width = decoded_frame->width;
  1088. ist->resample_height = decoded_frame->height;
  1089. ist->resample_pix_fmt = decoded_frame->format;
  1090. for (i = 0; i < nb_filtergraphs; i++)
  1091. if (ist_in_filtergraph(filtergraphs[i], ist) &&
  1092. configure_filtergraph(filtergraphs[i]) < 0) {
  1093. av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
  1094. exit_program(1);
  1095. }
  1096. }
  1097. for (i = 0; i < ist->nb_filters; i++) {
  1098. if (i < ist->nb_filters - 1) {
  1099. f = ist->filter_frame;
  1100. err = av_frame_ref(f, decoded_frame);
  1101. if (err < 0)
  1102. break;
  1103. } else
  1104. f = decoded_frame;
  1105. err = av_buffersrc_add_frame(ist->filters[i]->filter, f);
  1106. if (err < 0)
  1107. break;
  1108. }
  1109. fail:
  1110. av_frame_unref(ist->filter_frame);
  1111. av_frame_unref(decoded_frame);
  1112. return err < 0 ? err : ret;
  1113. }
  1114. static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
  1115. {
  1116. AVSubtitle subtitle;
  1117. int i, ret = avcodec_decode_subtitle2(ist->dec_ctx,
  1118. &subtitle, got_output, pkt);
  1119. if (ret < 0)
  1120. return ret;
  1121. if (!*got_output)
  1122. return ret;
  1123. ist->frames_decoded++;
  1124. for (i = 0; i < nb_output_streams; i++) {
  1125. OutputStream *ost = output_streams[i];
  1126. if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
  1127. continue;
  1128. do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle, pkt->pts);
  1129. }
  1130. avsubtitle_free(&subtitle);
  1131. return ret;
  1132. }
  1133. static int send_filter_eof(InputStream *ist)
  1134. {
  1135. int i, ret;
  1136. for (i = 0; i < ist->nb_filters; i++) {
  1137. ret = av_buffersrc_add_frame(ist->filters[i]->filter, NULL);
  1138. if (ret < 0)
  1139. return ret;
  1140. }
  1141. return 0;
  1142. }
  1143. /* pkt = NULL means EOF (needed to flush decoder buffers) */
  1144. static void process_input_packet(InputStream *ist, const AVPacket *pkt, int no_eof)
  1145. {
  1146. int i;
  1147. int repeating = 0;
  1148. AVPacket avpkt;
  1149. if (ist->next_dts == AV_NOPTS_VALUE)
  1150. ist->next_dts = ist->last_dts;
  1151. if (!pkt) {
  1152. /* EOF handling */
  1153. av_init_packet(&avpkt);
  1154. avpkt.data = NULL;
  1155. avpkt.size = 0;
  1156. } else {
  1157. avpkt = *pkt;
  1158. }
  1159. if (pkt && pkt->dts != AV_NOPTS_VALUE)
  1160. ist->next_dts = ist->last_dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
  1161. // while we have more to decode or while the decoder did output something on EOF
  1162. while (ist->decoding_needed && (!pkt || avpkt.size > 0)) {
  1163. int ret = 0;
  1164. int got_output = 0;
  1165. if (!repeating)
  1166. ist->last_dts = ist->next_dts;
  1167. switch (ist->dec_ctx->codec_type) {
  1168. case AVMEDIA_TYPE_AUDIO:
  1169. ret = decode_audio (ist, repeating ? NULL : &avpkt, &got_output);
  1170. break;
  1171. case AVMEDIA_TYPE_VIDEO:
  1172. ret = decode_video (ist, repeating ? NULL : &avpkt, &got_output);
  1173. if (repeating && !got_output)
  1174. ;
  1175. else if (pkt && pkt->duration)
  1176. ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
  1177. else if (ist->st->avg_frame_rate.num)
  1178. ist->next_dts += av_rescale_q(1, av_inv_q(ist->st->avg_frame_rate),
  1179. AV_TIME_BASE_Q);
  1180. else if (ist->dec_ctx->framerate.num != 0) {
  1181. int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 :
  1182. ist->dec_ctx->ticks_per_frame;
  1183. ist->next_dts += av_rescale_q(ticks, ist->dec_ctx->framerate, AV_TIME_BASE_Q);
  1184. }
  1185. break;
  1186. case AVMEDIA_TYPE_SUBTITLE:
  1187. if (repeating)
  1188. break;
  1189. ret = transcode_subtitles(ist, &avpkt, &got_output);
  1190. break;
  1191. default:
  1192. return;
  1193. }
  1194. if (ret < 0) {
  1195. av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d\n",
  1196. ist->file_index, ist->st->index);
  1197. if (exit_on_error)
  1198. exit_program(1);
  1199. break;
  1200. }
  1201. if (!got_output)
  1202. break;
  1203. repeating = 1;
  1204. }
  1205. /* after flushing, send an EOF on all the filter inputs attached to the stream */
  1206. /* except when looping we need to flush but not to send an EOF */
  1207. if (!pkt && ist->decoding_needed && !no_eof) {
  1208. int ret = send_filter_eof(ist);
  1209. if (ret < 0) {
  1210. av_log(NULL, AV_LOG_FATAL, "Error marking filters as finished\n");
  1211. exit_program(1);
  1212. }
  1213. }
  1214. /* handle stream copy */
  1215. if (!ist->decoding_needed) {
  1216. ist->last_dts = ist->next_dts;
  1217. switch (ist->dec_ctx->codec_type) {
  1218. case AVMEDIA_TYPE_AUDIO:
  1219. ist->next_dts += ((int64_t)AV_TIME_BASE * ist->dec_ctx->frame_size) /
  1220. ist->dec_ctx->sample_rate;
  1221. break;
  1222. case AVMEDIA_TYPE_VIDEO:
  1223. if (ist->dec_ctx->framerate.num != 0) {
  1224. int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->dec_ctx->ticks_per_frame;
  1225. ist->next_dts += ((int64_t)AV_TIME_BASE *
  1226. ist->dec_ctx->framerate.den * ticks) /
  1227. ist->dec_ctx->framerate.num;
  1228. }
  1229. break;
  1230. }
  1231. }
  1232. for (i = 0; pkt && i < nb_output_streams; i++) {
  1233. OutputStream *ost = output_streams[i];
  1234. if (!check_output_constraints(ist, ost) || ost->encoding_needed)
  1235. continue;
  1236. do_streamcopy(ist, ost, pkt);
  1237. }
  1238. return;
  1239. }
  1240. static void print_sdp(void)
  1241. {
  1242. char sdp[16384];
  1243. int i;
  1244. AVFormatContext **avc = av_malloc(sizeof(*avc) * nb_output_files);
  1245. if (!avc)
  1246. exit_program(1);
  1247. for (i = 0; i < nb_output_files; i++)
  1248. avc[i] = output_files[i]->ctx;
  1249. av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
  1250. printf("SDP:\n%s\n", sdp);
  1251. fflush(stdout);
  1252. av_freep(&avc);
  1253. }
  1254. static const HWAccel *get_hwaccel(enum AVPixelFormat pix_fmt)
  1255. {
  1256. int i;
  1257. for (i = 0; hwaccels[i].name; i++)
  1258. if (hwaccels[i].pix_fmt == pix_fmt)
  1259. return &hwaccels[i];
  1260. return NULL;
  1261. }
  1262. static enum AVPixelFormat get_format(AVCodecContext *s, const enum AVPixelFormat *pix_fmts)
  1263. {
  1264. InputStream *ist = s->opaque;
  1265. const enum AVPixelFormat *p;
  1266. int ret;
  1267. for (p = pix_fmts; *p != -1; p++) {
  1268. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(*p);
  1269. const HWAccel *hwaccel;
  1270. if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
  1271. break;
  1272. hwaccel = get_hwaccel(*p);
  1273. if (!hwaccel ||
  1274. (ist->active_hwaccel_id && ist->active_hwaccel_id != hwaccel->id) ||
  1275. (ist->hwaccel_id != HWACCEL_AUTO && ist->hwaccel_id != hwaccel->id))
  1276. continue;
  1277. ret = hwaccel->init(s);
  1278. if (ret < 0) {
  1279. if (ist->hwaccel_id == hwaccel->id) {
  1280. av_log(NULL, AV_LOG_FATAL,
  1281. "%s hwaccel requested for input stream #%d:%d, "
  1282. "but cannot be initialized.\n", hwaccel->name,
  1283. ist->file_index, ist->st->index);
  1284. return AV_PIX_FMT_NONE;
  1285. }
  1286. continue;
  1287. }
  1288. ist->active_hwaccel_id = hwaccel->id;
  1289. ist->hwaccel_pix_fmt = *p;
  1290. break;
  1291. }
  1292. return *p;
  1293. }
  1294. static int get_buffer(AVCodecContext *s, AVFrame *frame, int flags)
  1295. {
  1296. InputStream *ist = s->opaque;
  1297. if (ist->hwaccel_get_buffer && frame->format == ist->hwaccel_pix_fmt)
  1298. return ist->hwaccel_get_buffer(s, frame, flags);
  1299. return avcodec_default_get_buffer2(s, frame, flags);
  1300. }
  1301. static int init_input_stream(int ist_index, char *error, int error_len)
  1302. {
  1303. int ret;
  1304. InputStream *ist = input_streams[ist_index];
  1305. if (ist->decoding_needed) {
  1306. AVCodec *codec = ist->dec;
  1307. if (!codec) {
  1308. snprintf(error, error_len, "Decoder (codec id %d) not found for input stream #%d:%d",
  1309. ist->dec_ctx->codec_id, ist->file_index, ist->st->index);
  1310. return AVERROR(EINVAL);
  1311. }
  1312. ist->dec_ctx->opaque = ist;
  1313. ist->dec_ctx->get_format = get_format;
  1314. ist->dec_ctx->get_buffer2 = get_buffer;
  1315. ist->dec_ctx->thread_safe_callbacks = 1;
  1316. av_opt_set_int(ist->dec_ctx, "refcounted_frames", 1, 0);
  1317. if (!av_dict_get(ist->decoder_opts, "threads", NULL, 0))
  1318. av_dict_set(&ist->decoder_opts, "threads", "auto", 0);
  1319. if ((ret = avcodec_open2(ist->dec_ctx, codec, &ist->decoder_opts)) < 0) {
  1320. char errbuf[128];
  1321. if (ret == AVERROR_EXPERIMENTAL)
  1322. abort_codec_experimental(codec, 0);
  1323. av_strerror(ret, errbuf, sizeof(errbuf));
  1324. snprintf(error, error_len,
  1325. "Error while opening decoder for input stream "
  1326. "#%d:%d : %s",
  1327. ist->file_index, ist->st->index, errbuf);
  1328. return ret;
  1329. }
  1330. assert_avoptions(ist->decoder_opts);
  1331. }
  1332. ist->last_dts = ist->st->avg_frame_rate.num ? - ist->dec_ctx->has_b_frames * AV_TIME_BASE / av_q2d(ist->st->avg_frame_rate) : 0;
  1333. ist->next_dts = AV_NOPTS_VALUE;
  1334. init_pts_correction(&ist->pts_ctx);
  1335. return 0;
  1336. }
  1337. static InputStream *get_input_stream(OutputStream *ost)
  1338. {
  1339. if (ost->source_index >= 0)
  1340. return input_streams[ost->source_index];
  1341. if (ost->filter) {
  1342. FilterGraph *fg = ost->filter->graph;
  1343. int i;
  1344. for (i = 0; i < fg->nb_inputs; i++)
  1345. if (fg->inputs[i]->ist->dec_ctx->codec_type == ost->enc_ctx->codec_type)
  1346. return fg->inputs[i]->ist;
  1347. }
  1348. return NULL;
  1349. }
  1350. static int init_output_bsfs(OutputStream *ost)
  1351. {
  1352. AVBSFContext *ctx;
  1353. int i, ret;
  1354. if (!ost->nb_bitstream_filters)
  1355. return 0;
  1356. ost->bsf_ctx = av_mallocz_array(ost->nb_bitstream_filters, sizeof(*ost->bsf_ctx));
  1357. if (!ost->bsf_ctx)
  1358. return AVERROR(ENOMEM);
  1359. for (i = 0; i < ost->nb_bitstream_filters; i++) {
  1360. ret = av_bsf_alloc(ost->bitstream_filters[i], &ctx);
  1361. if (ret < 0) {
  1362. av_log(NULL, AV_LOG_ERROR, "Error allocating a bitstream filter context\n");
  1363. return ret;
  1364. }
  1365. ost->bsf_ctx[i] = ctx;
  1366. ret = avcodec_parameters_copy(ctx->par_in,
  1367. i ? ost->bsf_ctx[i - 1]->par_out : ost->st->codecpar);
  1368. if (ret < 0)
  1369. return ret;
  1370. ctx->time_base_in = i ? ost->bsf_ctx[i - 1]->time_base_out : ost->st->time_base;
  1371. ret = av_bsf_init(ctx);
  1372. if (ret < 0) {
  1373. av_log(NULL, AV_LOG_ERROR, "Error initializing bitstream filter: %s\n",
  1374. ost->bitstream_filters[i]->name);
  1375. return ret;
  1376. }
  1377. }
  1378. ctx = ost->bsf_ctx[ost->nb_bitstream_filters - 1];
  1379. ret = avcodec_parameters_copy(ost->st->codecpar, ctx->par_out);
  1380. if (ret < 0)
  1381. return ret;
  1382. ost->st->time_base = ctx->time_base_out;
  1383. return 0;
  1384. }
  1385. static int init_output_stream(OutputStream *ost, char *error, int error_len)
  1386. {
  1387. int ret = 0;
  1388. if (ost->encoding_needed) {
  1389. AVCodec *codec = ost->enc;
  1390. AVCodecContext *dec = NULL;
  1391. InputStream *ist;
  1392. if ((ist = get_input_stream(ost)))
  1393. dec = ist->dec_ctx;
  1394. if (dec && dec->subtitle_header) {
  1395. ost->enc_ctx->subtitle_header = av_malloc(dec->subtitle_header_size);
  1396. if (!ost->enc_ctx->subtitle_header)
  1397. return AVERROR(ENOMEM);
  1398. memcpy(ost->enc_ctx->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
  1399. ost->enc_ctx->subtitle_header_size = dec->subtitle_header_size;
  1400. }
  1401. if (!av_dict_get(ost->encoder_opts, "threads", NULL, 0))
  1402. av_dict_set(&ost->encoder_opts, "threads", "auto", 0);
  1403. if (ost->filter && ost->filter->filter->inputs[0]->hw_frames_ctx) {
  1404. ost->enc_ctx->hw_frames_ctx = av_buffer_ref(ost->filter->filter->inputs[0]->hw_frames_ctx);
  1405. if (!ost->enc_ctx->hw_frames_ctx)
  1406. return AVERROR(ENOMEM);
  1407. }
  1408. if ((ret = avcodec_open2(ost->enc_ctx, codec, &ost->encoder_opts)) < 0) {
  1409. if (ret == AVERROR_EXPERIMENTAL)
  1410. abort_codec_experimental(codec, 1);
  1411. snprintf(error, error_len,
  1412. "Error while opening encoder for output stream #%d:%d - "
  1413. "maybe incorrect parameters such as bit_rate, rate, width or height",
  1414. ost->file_index, ost->index);
  1415. return ret;
  1416. }
  1417. assert_avoptions(ost->encoder_opts);
  1418. if (ost->enc_ctx->bit_rate && ost->enc_ctx->bit_rate < 1000)
  1419. av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
  1420. "It takes bits/s as argument, not kbits/s\n");
  1421. ret = avcodec_parameters_from_context(ost->st->codecpar, ost->enc_ctx);
  1422. if (ret < 0) {
  1423. av_log(NULL, AV_LOG_FATAL,
  1424. "Error initializing the output stream codec context.\n");
  1425. exit_program(1);
  1426. }
  1427. if (ost->enc_ctx->nb_coded_side_data) {
  1428. int i;
  1429. ost->st->side_data = av_realloc_array(NULL, ost->enc_ctx->nb_coded_side_data,
  1430. sizeof(*ost->st->side_data));
  1431. if (!ost->st->side_data)
  1432. return AVERROR(ENOMEM);
  1433. for (i = 0; i < ost->enc_ctx->nb_coded_side_data; i++) {
  1434. const AVPacketSideData *sd_src = &ost->enc_ctx->coded_side_data[i];
  1435. AVPacketSideData *sd_dst = &ost->st->side_data[i];
  1436. sd_dst->data = av_malloc(sd_src->size);
  1437. if (!sd_dst->data)
  1438. return AVERROR(ENOMEM);
  1439. memcpy(sd_dst->data, sd_src->data, sd_src->size);
  1440. sd_dst->size = sd_src->size;
  1441. sd_dst->type = sd_src->type;
  1442. ost->st->nb_side_data++;
  1443. }
  1444. }
  1445. ost->st->time_base = ost->enc_ctx->time_base;
  1446. } else {
  1447. ret = av_opt_set_dict(ost->enc_ctx, &ost->encoder_opts);
  1448. if (ret < 0)
  1449. return ret;
  1450. /*
  1451. * FIXME: will the codec context used by the parser during streamcopy
  1452. * This should go away with the new parser API.
  1453. */
  1454. ret = avcodec_parameters_to_context(ost->parser_avctx, ost->st->codecpar);
  1455. if (ret < 0)
  1456. return ret;
  1457. }
  1458. /* initialize bitstream filters for the output stream
  1459. * needs to be done here, because the codec id for streamcopy is not
  1460. * known until now */
  1461. ret = init_output_bsfs(ost);
  1462. if (ret < 0)
  1463. return ret;
  1464. return ret;
  1465. }
  1466. static void parse_forced_key_frames(char *kf, OutputStream *ost,
  1467. AVCodecContext *avctx)
  1468. {
  1469. char *p;
  1470. int n = 1, i;
  1471. int64_t t;
  1472. for (p = kf; *p; p++)
  1473. if (*p == ',')
  1474. n++;
  1475. ost->forced_kf_count = n;
  1476. ost->forced_kf_pts = av_malloc(sizeof(*ost->forced_kf_pts) * n);
  1477. if (!ost->forced_kf_pts) {
  1478. av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
  1479. exit_program(1);
  1480. }
  1481. p = kf;
  1482. for (i = 0; i < n; i++) {
  1483. char *next = strchr(p, ',');
  1484. if (next)
  1485. *next++ = 0;
  1486. t = parse_time_or_die("force_key_frames", p, 1);
  1487. ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
  1488. p = next;
  1489. }
  1490. }
  1491. static void set_encoder_id(OutputFile *of, OutputStream *ost)
  1492. {
  1493. AVDictionaryEntry *e;
  1494. uint8_t *encoder_string;
  1495. int encoder_string_len;
  1496. int format_flags = 0;
  1497. e = av_dict_get(of->opts, "fflags", NULL, 0);
  1498. if (e) {
  1499. const AVOption *o = av_opt_find(of->ctx, "fflags", NULL, 0, 0);
  1500. if (!o)
  1501. return;
  1502. av_opt_eval_flags(of->ctx, o, e->value, &format_flags);
  1503. }
  1504. encoder_string_len = sizeof(LIBAVCODEC_IDENT) + strlen(ost->enc->name) + 2;
  1505. encoder_string = av_mallocz(encoder_string_len);
  1506. if (!encoder_string)
  1507. exit_program(1);
  1508. if (!(format_flags & AVFMT_FLAG_BITEXACT))
  1509. av_strlcpy(encoder_string, LIBAVCODEC_IDENT " ", encoder_string_len);
  1510. av_strlcat(encoder_string, ost->enc->name, encoder_string_len);
  1511. av_dict_set(&ost->st->metadata, "encoder", encoder_string,
  1512. AV_DICT_DONT_STRDUP_VAL | AV_DICT_DONT_OVERWRITE);
  1513. }
  1514. static int transcode_init(void)
  1515. {
  1516. int ret = 0, i, j, k;
  1517. AVFormatContext *oc;
  1518. OutputStream *ost;
  1519. InputStream *ist;
  1520. char error[1024];
  1521. int want_sdp = 1;
  1522. /* init framerate emulation */
  1523. for (i = 0; i < nb_input_files; i++) {
  1524. InputFile *ifile = input_files[i];
  1525. if (ifile->rate_emu)
  1526. for (j = 0; j < ifile->nb_streams; j++)
  1527. input_streams[j + ifile->ist_index]->start = av_gettime_relative();
  1528. }
  1529. /* for each output stream, we compute the right encoding parameters */
  1530. for (i = 0; i < nb_output_streams; i++) {
  1531. ost = output_streams[i];
  1532. oc = output_files[ost->file_index]->ctx;
  1533. ist = get_input_stream(ost);
  1534. if (ost->attachment_filename)
  1535. continue;
  1536. if (ist) {
  1537. ost->st->disposition = ist->st->disposition;
  1538. }
  1539. if (ost->stream_copy) {
  1540. AVCodecParameters *par_dst = ost->st->codecpar;
  1541. AVCodecParameters *par_src = ist->st->codecpar;
  1542. AVRational sar;
  1543. uint64_t extra_size;
  1544. av_assert0(ist && !ost->filter);
  1545. extra_size = (uint64_t)par_src->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE;
  1546. if (extra_size > INT_MAX) {
  1547. return AVERROR(EINVAL);
  1548. }
  1549. /* if stream_copy is selected, no need to decode or encode */
  1550. par_dst->codec_id = par_src->codec_id;
  1551. par_dst->codec_type = par_src->codec_type;
  1552. if (!par_dst->codec_tag) {
  1553. if (!oc->oformat->codec_tag ||
  1554. av_codec_get_id (oc->oformat->codec_tag, par_src->codec_tag) == par_dst->codec_id ||
  1555. av_codec_get_tag(oc->oformat->codec_tag, par_src->codec_id) <= 0)
  1556. par_dst->codec_tag = par_src->codec_tag;
  1557. }
  1558. par_dst->bit_rate = par_src->bit_rate;
  1559. par_dst->field_order = par_src->field_order;
  1560. par_dst->chroma_location = par_src->chroma_location;
  1561. par_dst->extradata = av_mallocz(extra_size);
  1562. if (!par_dst->extradata) {
  1563. return AVERROR(ENOMEM);
  1564. }
  1565. memcpy(par_dst->extradata, par_src->extradata, par_src->extradata_size);
  1566. par_dst->extradata_size = par_src->extradata_size;
  1567. ost->st->time_base = ist->st->time_base;
  1568. if (ist->st->nb_side_data) {
  1569. ost->st->side_data = av_realloc_array(NULL, ist->st->nb_side_data,
  1570. sizeof(*ist->st->side_data));
  1571. if (!ost->st->side_data)
  1572. return AVERROR(ENOMEM);
  1573. for (j = 0; j < ist->st->nb_side_data; j++) {
  1574. const AVPacketSideData *sd_src = &ist->st->side_data[j];
  1575. AVPacketSideData *sd_dst = &ost->st->side_data[j];
  1576. sd_dst->data = av_malloc(sd_src->size);
  1577. if (!sd_dst->data)
  1578. return AVERROR(ENOMEM);
  1579. memcpy(sd_dst->data, sd_src->data, sd_src->size);
  1580. sd_dst->size = sd_src->size;
  1581. sd_dst->type = sd_src->type;
  1582. ost->st->nb_side_data++;
  1583. }
  1584. }
  1585. ost->parser = av_parser_init(par_dst->codec_id);
  1586. ost->parser_avctx = avcodec_alloc_context3(NULL);
  1587. if (!ost->parser_avctx)
  1588. return AVERROR(ENOMEM);
  1589. switch (par_dst->codec_type) {
  1590. case AVMEDIA_TYPE_AUDIO:
  1591. if (audio_volume != 256) {
  1592. av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
  1593. exit_program(1);
  1594. }
  1595. par_dst->channel_layout = par_src->channel_layout;
  1596. par_dst->sample_rate = par_src->sample_rate;
  1597. par_dst->channels = par_src->channels;
  1598. par_dst->block_align = par_src->block_align;
  1599. break;
  1600. case AVMEDIA_TYPE_VIDEO:
  1601. par_dst->format = par_src->format;
  1602. par_dst->width = par_src->width;
  1603. par_dst->height = par_src->height;
  1604. if (ost->frame_aspect_ratio)
  1605. sar = av_d2q(ost->frame_aspect_ratio * par_dst->height / par_dst->width, 255);
  1606. else if (ist->st->sample_aspect_ratio.num)
  1607. sar = ist->st->sample_aspect_ratio;
  1608. else
  1609. sar = par_src->sample_aspect_ratio;
  1610. ost->st->sample_aspect_ratio = par_dst->sample_aspect_ratio = sar;
  1611. break;
  1612. case AVMEDIA_TYPE_SUBTITLE:
  1613. par_dst->width = par_src->width;
  1614. par_dst->height = par_src->height;
  1615. break;
  1616. case AVMEDIA_TYPE_DATA:
  1617. case AVMEDIA_TYPE_ATTACHMENT:
  1618. break;
  1619. default:
  1620. abort();
  1621. }
  1622. } else {
  1623. AVCodecContext *enc_ctx = ost->enc_ctx;
  1624. AVCodecContext *dec_ctx = NULL;
  1625. if (!ost->enc) {
  1626. /* should only happen when a default codec is not present. */
  1627. snprintf(error, sizeof(error), "Automatic encoder selection "
  1628. "failed for output stream #%d:%d. Default encoder for "
  1629. "format %s is probably disabled. Please choose an "
  1630. "encoder manually.\n", ost->file_index, ost->index,
  1631. oc->oformat->name);
  1632. ret = AVERROR(EINVAL);
  1633. goto dump_format;
  1634. }
  1635. set_encoder_id(output_files[ost->file_index], ost);
  1636. if (ist) {
  1637. dec_ctx = ist->dec_ctx;
  1638. enc_ctx->bits_per_raw_sample = dec_ctx->bits_per_raw_sample;
  1639. enc_ctx->chroma_sample_location = dec_ctx->chroma_sample_location;
  1640. }
  1641. /*
  1642. * We want CFR output if and only if one of those is true:
  1643. * 1) user specified output framerate with -r
  1644. * 2) user specified -vsync cfr
  1645. * 3) output format is CFR and the user didn't force vsync to
  1646. * something else than CFR
  1647. *
  1648. * in such a case, set ost->frame_rate
  1649. */
  1650. if (enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO &&
  1651. !ost->frame_rate.num && ist &&
  1652. (video_sync_method == VSYNC_CFR ||
  1653. (video_sync_method == VSYNC_AUTO &&
  1654. !(oc->oformat->flags & (AVFMT_NOTIMESTAMPS | AVFMT_VARIABLE_FPS))))) {
  1655. if (ist->framerate.num)
  1656. ost->frame_rate = ist->framerate;
  1657. else if (ist->st->avg_frame_rate.num)
  1658. ost->frame_rate = ist->st->avg_frame_rate;
  1659. else {
  1660. av_log(NULL, AV_LOG_WARNING, "Constant framerate requested "
  1661. "for the output stream #%d:%d, but no information "
  1662. "about the input framerate is available. Falling "
  1663. "back to a default value of 25fps. Use the -r option "
  1664. "if you want a different framerate.\n",
  1665. ost->file_index, ost->index);
  1666. ost->frame_rate = (AVRational){ 25, 1 };
  1667. }
  1668. if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
  1669. int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
  1670. ost->frame_rate = ost->enc->supported_framerates[idx];
  1671. }
  1672. }
  1673. #if CONFIG_LIBMFX
  1674. if (qsv_transcode_init(ost))
  1675. exit_program(1);
  1676. #endif
  1677. if (!ost->filter &&
  1678. (enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
  1679. enc_ctx->codec_type == AVMEDIA_TYPE_AUDIO)) {
  1680. FilterGraph *fg;
  1681. fg = init_simple_filtergraph(ist, ost);
  1682. if (configure_filtergraph(fg)) {
  1683. av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
  1684. exit_program(1);
  1685. }
  1686. }
  1687. switch (enc_ctx->codec_type) {
  1688. case AVMEDIA_TYPE_AUDIO:
  1689. enc_ctx->sample_fmt = ost->filter->filter->inputs[0]->format;
  1690. enc_ctx->sample_rate = ost->filter->filter->inputs[0]->sample_rate;
  1691. enc_ctx->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
  1692. enc_ctx->channels = av_get_channel_layout_nb_channels(enc_ctx->channel_layout);
  1693. enc_ctx->time_base = (AVRational){ 1, enc_ctx->sample_rate };
  1694. break;
  1695. case AVMEDIA_TYPE_VIDEO:
  1696. enc_ctx->time_base = ost->filter->filter->inputs[0]->time_base;
  1697. enc_ctx->width = ost->filter->filter->inputs[0]->w;
  1698. enc_ctx->height = ost->filter->filter->inputs[0]->h;
  1699. enc_ctx->sample_aspect_ratio = ost->st->sample_aspect_ratio =
  1700. ost->frame_aspect_ratio ? // overridden by the -aspect cli option
  1701. av_d2q(ost->frame_aspect_ratio * enc_ctx->height/enc_ctx->width, 255) :
  1702. ost->filter->filter->inputs[0]->sample_aspect_ratio;
  1703. enc_ctx->pix_fmt = ost->filter->filter->inputs[0]->format;
  1704. ost->st->avg_frame_rate = ost->frame_rate;
  1705. if (dec_ctx &&
  1706. (enc_ctx->width != dec_ctx->width ||
  1707. enc_ctx->height != dec_ctx->height ||
  1708. enc_ctx->pix_fmt != dec_ctx->pix_fmt)) {
  1709. enc_ctx->bits_per_raw_sample = 0;
  1710. }
  1711. if (ost->forced_keyframes)
  1712. parse_forced_key_frames(ost->forced_keyframes, ost,
  1713. ost->enc_ctx);
  1714. break;
  1715. case AVMEDIA_TYPE_SUBTITLE:
  1716. enc_ctx->time_base = (AVRational){1, 1000};
  1717. break;
  1718. default:
  1719. abort();
  1720. break;
  1721. }
  1722. }
  1723. }
  1724. /* init input streams */
  1725. for (i = 0; i < nb_input_streams; i++)
  1726. if ((ret = init_input_stream(i, error, sizeof(error))) < 0)
  1727. goto dump_format;
  1728. /* open each encoder */
  1729. for (i = 0; i < nb_output_streams; i++) {
  1730. ret = init_output_stream(output_streams[i], error, sizeof(error));
  1731. if (ret < 0)
  1732. goto dump_format;
  1733. }
  1734. /* discard unused programs */
  1735. for (i = 0; i < nb_input_files; i++) {
  1736. InputFile *ifile = input_files[i];
  1737. for (j = 0; j < ifile->ctx->nb_programs; j++) {
  1738. AVProgram *p = ifile->ctx->programs[j];
  1739. int discard = AVDISCARD_ALL;
  1740. for (k = 0; k < p->nb_stream_indexes; k++)
  1741. if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
  1742. discard = AVDISCARD_DEFAULT;
  1743. break;
  1744. }
  1745. p->discard = discard;
  1746. }
  1747. }
  1748. /* open files and write file headers */
  1749. for (i = 0; i < nb_output_files; i++) {
  1750. oc = output_files[i]->ctx;
  1751. oc->interrupt_callback = int_cb;
  1752. if ((ret = avformat_write_header(oc, &output_files[i]->opts)) < 0) {
  1753. char errbuf[128];
  1754. av_strerror(ret, errbuf, sizeof(errbuf));
  1755. snprintf(error, sizeof(error),
  1756. "Could not write header for output file #%d "
  1757. "(incorrect codec parameters ?): %s",
  1758. i, errbuf);
  1759. ret = AVERROR(EINVAL);
  1760. goto dump_format;
  1761. }
  1762. assert_avoptions(output_files[i]->opts);
  1763. if (strcmp(oc->oformat->name, "rtp")) {
  1764. want_sdp = 0;
  1765. }
  1766. }
  1767. dump_format:
  1768. /* dump the file output parameters - cannot be done before in case
  1769. of stream copy */
  1770. for (i = 0; i < nb_output_files; i++) {
  1771. av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
  1772. }
  1773. /* dump the stream mapping */
  1774. av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
  1775. for (i = 0; i < nb_input_streams; i++) {
  1776. ist = input_streams[i];
  1777. for (j = 0; j < ist->nb_filters; j++) {
  1778. if (ist->filters[j]->graph->graph_desc) {
  1779. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
  1780. ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
  1781. ist->filters[j]->name);
  1782. if (nb_filtergraphs > 1)
  1783. av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
  1784. av_log(NULL, AV_LOG_INFO, "\n");
  1785. }
  1786. }
  1787. }
  1788. for (i = 0; i < nb_output_streams; i++) {
  1789. ost = output_streams[i];
  1790. if (ost->attachment_filename) {
  1791. /* an attached file */
  1792. av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
  1793. ost->attachment_filename, ost->file_index, ost->index);
  1794. continue;
  1795. }
  1796. if (ost->filter && ost->filter->graph->graph_desc) {
  1797. /* output from a complex graph */
  1798. av_log(NULL, AV_LOG_INFO, " %s", ost->filter->name);
  1799. if (nb_filtergraphs > 1)
  1800. av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
  1801. av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
  1802. ost->index, ost->enc ? ost->enc->name : "?");
  1803. continue;
  1804. }
  1805. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
  1806. input_streams[ost->source_index]->file_index,
  1807. input_streams[ost->source_index]->st->index,
  1808. ost->file_index,
  1809. ost->index);
  1810. if (ost->sync_ist != input_streams[ost->source_index])
  1811. av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
  1812. ost->sync_ist->file_index,
  1813. ost->sync_ist->st->index);
  1814. if (ost->stream_copy)
  1815. av_log(NULL, AV_LOG_INFO, " (copy)");
  1816. else {
  1817. const AVCodec *in_codec = input_streams[ost->source_index]->dec;
  1818. const AVCodec *out_codec = ost->enc;
  1819. const char *decoder_name = "?";
  1820. const char *in_codec_name = "?";
  1821. const char *encoder_name = "?";
  1822. const char *out_codec_name = "?";
  1823. const AVCodecDescriptor *desc;
  1824. if (in_codec) {
  1825. decoder_name = in_codec->name;
  1826. desc = avcodec_descriptor_get(in_codec->id);
  1827. if (desc)
  1828. in_codec_name = desc->name;
  1829. if (!strcmp(decoder_name, in_codec_name))
  1830. decoder_name = "native";
  1831. }
  1832. if (out_codec) {
  1833. encoder_name = out_codec->name;
  1834. desc = avcodec_descriptor_get(out_codec->id);
  1835. if (desc)
  1836. out_codec_name = desc->name;
  1837. if (!strcmp(encoder_name, out_codec_name))
  1838. encoder_name = "native";
  1839. }
  1840. av_log(NULL, AV_LOG_INFO, " (%s (%s) -> %s (%s))",
  1841. in_codec_name, decoder_name,
  1842. out_codec_name, encoder_name);
  1843. }
  1844. av_log(NULL, AV_LOG_INFO, "\n");
  1845. }
  1846. if (ret) {
  1847. av_log(NULL, AV_LOG_ERROR, "%s\n", error);
  1848. return ret;
  1849. }
  1850. if (want_sdp) {
  1851. print_sdp();
  1852. }
  1853. return 0;
  1854. }
  1855. /* Return 1 if there remain streams where more output is wanted, 0 otherwise. */
  1856. static int need_output(void)
  1857. {
  1858. int i;
  1859. for (i = 0; i < nb_output_streams; i++) {
  1860. OutputStream *ost = output_streams[i];
  1861. OutputFile *of = output_files[ost->file_index];
  1862. AVFormatContext *os = output_files[ost->file_index]->ctx;
  1863. if (ost->finished ||
  1864. (os->pb && avio_tell(os->pb) >= of->limit_filesize))
  1865. continue;
  1866. if (ost->frame_number >= ost->max_frames) {
  1867. int j;
  1868. for (j = 0; j < of->ctx->nb_streams; j++)
  1869. output_streams[of->ost_index + j]->finished = 1;
  1870. continue;
  1871. }
  1872. return 1;
  1873. }
  1874. return 0;
  1875. }
  1876. static InputFile *select_input_file(void)
  1877. {
  1878. InputFile *ifile = NULL;
  1879. int64_t ipts_min = INT64_MAX;
  1880. int i;
  1881. for (i = 0; i < nb_input_streams; i++) {
  1882. InputStream *ist = input_streams[i];
  1883. int64_t ipts = ist->last_dts;
  1884. if (ist->discard || input_files[ist->file_index]->eagain)
  1885. continue;
  1886. if (!input_files[ist->file_index]->eof_reached) {
  1887. if (ipts < ipts_min) {
  1888. ipts_min = ipts;
  1889. ifile = input_files[ist->file_index];
  1890. }
  1891. }
  1892. }
  1893. return ifile;
  1894. }
  1895. #if HAVE_PTHREADS
  1896. static void *input_thread(void *arg)
  1897. {
  1898. InputFile *f = arg;
  1899. int ret = 0;
  1900. while (!transcoding_finished && ret >= 0) {
  1901. AVPacket pkt;
  1902. ret = av_read_frame(f->ctx, &pkt);
  1903. if (ret == AVERROR(EAGAIN)) {
  1904. av_usleep(10000);
  1905. ret = 0;
  1906. continue;
  1907. } else if (ret < 0)
  1908. break;
  1909. pthread_mutex_lock(&f->fifo_lock);
  1910. while (!av_fifo_space(f->fifo))
  1911. pthread_cond_wait(&f->fifo_cond, &f->fifo_lock);
  1912. av_fifo_generic_write(f->fifo, &pkt, sizeof(pkt), NULL);
  1913. pthread_mutex_unlock(&f->fifo_lock);
  1914. }
  1915. f->finished = 1;
  1916. return NULL;
  1917. }
  1918. static void free_input_threads(void)
  1919. {
  1920. int i;
  1921. if (nb_input_files == 1)
  1922. return;
  1923. transcoding_finished = 1;
  1924. for (i = 0; i < nb_input_files; i++) {
  1925. InputFile *f = input_files[i];
  1926. AVPacket pkt;
  1927. if (!f->fifo || f->joined)
  1928. continue;
  1929. pthread_mutex_lock(&f->fifo_lock);
  1930. while (av_fifo_size(f->fifo)) {
  1931. av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
  1932. av_packet_unref(&pkt);
  1933. }
  1934. pthread_cond_signal(&f->fifo_cond);
  1935. pthread_mutex_unlock(&f->fifo_lock);
  1936. pthread_join(f->thread, NULL);
  1937. f->joined = 1;
  1938. while (av_fifo_size(f->fifo)) {
  1939. av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
  1940. av_packet_unref(&pkt);
  1941. }
  1942. av_fifo_free(f->fifo);
  1943. }
  1944. }
  1945. static int init_input_threads(void)
  1946. {
  1947. int i, ret;
  1948. if (nb_input_files == 1)
  1949. return 0;
  1950. for (i = 0; i < nb_input_files; i++) {
  1951. InputFile *f = input_files[i];
  1952. if (!(f->fifo = av_fifo_alloc(8*sizeof(AVPacket))))
  1953. return AVERROR(ENOMEM);
  1954. pthread_mutex_init(&f->fifo_lock, NULL);
  1955. pthread_cond_init (&f->fifo_cond, NULL);
  1956. if ((ret = pthread_create(&f->thread, NULL, input_thread, f)))
  1957. return AVERROR(ret);
  1958. }
  1959. return 0;
  1960. }
  1961. static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
  1962. {
  1963. int ret = 0;
  1964. pthread_mutex_lock(&f->fifo_lock);
  1965. if (av_fifo_size(f->fifo)) {
  1966. av_fifo_generic_read(f->fifo, pkt, sizeof(*pkt), NULL);
  1967. pthread_cond_signal(&f->fifo_cond);
  1968. } else {
  1969. if (f->finished)
  1970. ret = AVERROR_EOF;
  1971. else
  1972. ret = AVERROR(EAGAIN);
  1973. }
  1974. pthread_mutex_unlock(&f->fifo_lock);
  1975. return ret;
  1976. }
  1977. #endif
  1978. static int get_input_packet(InputFile *f, AVPacket *pkt)
  1979. {
  1980. if (f->rate_emu) {
  1981. int i;
  1982. for (i = 0; i < f->nb_streams; i++) {
  1983. InputStream *ist = input_streams[f->ist_index + i];
  1984. int64_t pts = av_rescale(ist->last_dts, 1000000, AV_TIME_BASE);
  1985. int64_t now = av_gettime_relative() - ist->start;
  1986. if (pts > now)
  1987. return AVERROR(EAGAIN);
  1988. }
  1989. }
  1990. #if HAVE_PTHREADS
  1991. if (nb_input_files > 1)
  1992. return get_input_packet_mt(f, pkt);
  1993. #endif
  1994. return av_read_frame(f->ctx, pkt);
  1995. }
  1996. static int got_eagain(void)
  1997. {
  1998. int i;
  1999. for (i = 0; i < nb_input_files; i++)
  2000. if (input_files[i]->eagain)
  2001. return 1;
  2002. return 0;
  2003. }
  2004. static void reset_eagain(void)
  2005. {
  2006. int i;
  2007. for (i = 0; i < nb_input_files; i++)
  2008. input_files[i]->eagain = 0;
  2009. }
  2010. // set duration to max(tmp, duration) in a proper time base and return duration's time_base
  2011. static AVRational duration_max(int64_t tmp, int64_t *duration, AVRational tmp_time_base,
  2012. AVRational time_base)
  2013. {
  2014. int ret;
  2015. if (!*duration) {
  2016. *duration = tmp;
  2017. return tmp_time_base;
  2018. }
  2019. ret = av_compare_ts(*duration, time_base, tmp, tmp_time_base);
  2020. if (ret < 0) {
  2021. *duration = tmp;
  2022. return tmp_time_base;
  2023. }
  2024. return time_base;
  2025. }
  2026. static int seek_to_start(InputFile *ifile, AVFormatContext *is)
  2027. {
  2028. InputStream *ist;
  2029. AVCodecContext *avctx;
  2030. int i, ret, has_audio = 0;
  2031. int64_t duration = 0;
  2032. ret = av_seek_frame(is, -1, is->start_time, 0);
  2033. if (ret < 0)
  2034. return ret;
  2035. for (i = 0; i < ifile->nb_streams; i++) {
  2036. ist = input_streams[ifile->ist_index + i];
  2037. avctx = ist->dec_ctx;
  2038. // flush decoders
  2039. if (ist->decoding_needed) {
  2040. process_input_packet(ist, NULL, 1);
  2041. avcodec_flush_buffers(avctx);
  2042. }
  2043. /* duration is the length of the last frame in a stream
  2044. * when audio stream is present we don't care about
  2045. * last video frame length because it's not defined exactly */
  2046. if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && ist->nb_samples)
  2047. has_audio = 1;
  2048. }
  2049. for (i = 0; i < ifile->nb_streams; i++) {
  2050. ist = input_streams[ifile->ist_index + i];
  2051. avctx = ist->dec_ctx;
  2052. if (has_audio) {
  2053. if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && ist->nb_samples) {
  2054. AVRational sample_rate = {1, avctx->sample_rate};
  2055. duration = av_rescale_q(ist->nb_samples, sample_rate, ist->st->time_base);
  2056. } else
  2057. continue;
  2058. } else {
  2059. if (ist->framerate.num) {
  2060. duration = av_rescale_q(1, ist->framerate, ist->st->time_base);
  2061. } else if (ist->st->avg_frame_rate.num) {
  2062. duration = av_rescale_q(1, ist->st->avg_frame_rate, ist->st->time_base);
  2063. } else duration = 1;
  2064. }
  2065. if (!ifile->duration)
  2066. ifile->time_base = ist->st->time_base;
  2067. /* the total duration of the stream, max_pts - min_pts is
  2068. * the duration of the stream without the last frame */
  2069. duration += ist->max_pts - ist->min_pts;
  2070. ifile->time_base = duration_max(duration, &ifile->duration, ist->st->time_base,
  2071. ifile->time_base);
  2072. }
  2073. if (ifile->loop > 0)
  2074. ifile->loop--;
  2075. return ret;
  2076. }
  2077. /*
  2078. * Read one packet from an input file and send it for
  2079. * - decoding -> lavfi (audio/video)
  2080. * - decoding -> encoding -> muxing (subtitles)
  2081. * - muxing (streamcopy)
  2082. *
  2083. * Return
  2084. * - 0 -- one packet was read and processed
  2085. * - AVERROR(EAGAIN) -- no packets were available for selected file,
  2086. * this function should be called again
  2087. * - AVERROR_EOF -- this function should not be called again
  2088. */
  2089. static int process_input(void)
  2090. {
  2091. InputFile *ifile;
  2092. AVFormatContext *is;
  2093. InputStream *ist;
  2094. AVPacket pkt;
  2095. int ret, i, j;
  2096. int64_t duration;
  2097. /* select the stream that we must read now */
  2098. ifile = select_input_file();
  2099. /* if none, if is finished */
  2100. if (!ifile) {
  2101. if (got_eagain()) {
  2102. reset_eagain();
  2103. av_usleep(10000);
  2104. return AVERROR(EAGAIN);
  2105. }
  2106. av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from.\n");
  2107. return AVERROR_EOF;
  2108. }
  2109. is = ifile->ctx;
  2110. ret = get_input_packet(ifile, &pkt);
  2111. if (ret == AVERROR(EAGAIN)) {
  2112. ifile->eagain = 1;
  2113. return ret;
  2114. }
  2115. if (ret < 0 && ifile->loop) {
  2116. if ((ret = seek_to_start(ifile, is)) < 0)
  2117. return ret;
  2118. ret = get_input_packet(ifile, &pkt);
  2119. }
  2120. if (ret < 0) {
  2121. if (ret != AVERROR_EOF) {
  2122. print_error(is->filename, ret);
  2123. if (exit_on_error)
  2124. exit_program(1);
  2125. }
  2126. ifile->eof_reached = 1;
  2127. for (i = 0; i < ifile->nb_streams; i++) {
  2128. ist = input_streams[ifile->ist_index + i];
  2129. if (ist->decoding_needed)
  2130. process_input_packet(ist, NULL, 0);
  2131. /* mark all outputs that don't go through lavfi as finished */
  2132. for (j = 0; j < nb_output_streams; j++) {
  2133. OutputStream *ost = output_streams[j];
  2134. if (ost->source_index == ifile->ist_index + i &&
  2135. (ost->stream_copy || ost->enc->type == AVMEDIA_TYPE_SUBTITLE))
  2136. finish_output_stream(ost);
  2137. }
  2138. }
  2139. return AVERROR(EAGAIN);
  2140. }
  2141. reset_eagain();
  2142. if (do_pkt_dump) {
  2143. av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
  2144. is->streams[pkt.stream_index]);
  2145. }
  2146. /* the following test is needed in case new streams appear
  2147. dynamically in stream : we ignore them */
  2148. if (pkt.stream_index >= ifile->nb_streams)
  2149. goto discard_packet;
  2150. ist = input_streams[ifile->ist_index + pkt.stream_index];
  2151. ist->data_size += pkt.size;
  2152. ist->nb_packets++;
  2153. if (ist->discard)
  2154. goto discard_packet;
  2155. /* add the stream-global side data to the first packet */
  2156. if (ist->nb_packets == 1)
  2157. for (i = 0; i < ist->st->nb_side_data; i++) {
  2158. AVPacketSideData *src_sd = &ist->st->side_data[i];
  2159. uint8_t *dst_data;
  2160. if (av_packet_get_side_data(&pkt, src_sd->type, NULL))
  2161. continue;
  2162. if (ist->autorotate && src_sd->type == AV_PKT_DATA_DISPLAYMATRIX)
  2163. continue;
  2164. dst_data = av_packet_new_side_data(&pkt, src_sd->type, src_sd->size);
  2165. if (!dst_data)
  2166. exit_program(1);
  2167. memcpy(dst_data, src_sd->data, src_sd->size);
  2168. }
  2169. if (pkt.dts != AV_NOPTS_VALUE)
  2170. pkt.dts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
  2171. if (pkt.pts != AV_NOPTS_VALUE)
  2172. pkt.pts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
  2173. if (pkt.pts != AV_NOPTS_VALUE)
  2174. pkt.pts *= ist->ts_scale;
  2175. if (pkt.dts != AV_NOPTS_VALUE)
  2176. pkt.dts *= ist->ts_scale;
  2177. if ((ist->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
  2178. ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&
  2179. pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE &&
  2180. (is->iformat->flags & AVFMT_TS_DISCONT)) {
  2181. int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
  2182. int64_t delta = pkt_dts - ist->next_dts;
  2183. if ((FFABS(delta) > 1LL * dts_delta_threshold * AV_TIME_BASE || pkt_dts + 1 < ist->last_dts) && !copy_ts) {
  2184. ifile->ts_offset -= delta;
  2185. av_log(NULL, AV_LOG_DEBUG,
  2186. "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
  2187. delta, ifile->ts_offset);
  2188. pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  2189. if (pkt.pts != AV_NOPTS_VALUE)
  2190. pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  2191. }
  2192. }
  2193. duration = av_rescale_q(ifile->duration, ifile->time_base, ist->st->time_base);
  2194. if (pkt.pts != AV_NOPTS_VALUE) {
  2195. pkt.pts += duration;
  2196. ist->max_pts = FFMAX(pkt.pts, ist->max_pts);
  2197. ist->min_pts = FFMIN(pkt.pts, ist->min_pts);
  2198. }
  2199. if (pkt.dts != AV_NOPTS_VALUE)
  2200. pkt.dts += duration;
  2201. process_input_packet(ist, &pkt, 0);
  2202. discard_packet:
  2203. av_packet_unref(&pkt);
  2204. return 0;
  2205. }
  2206. /*
  2207. * The following code is the main loop of the file converter
  2208. */
  2209. static int transcode(void)
  2210. {
  2211. int ret, i, need_input = 1;
  2212. AVFormatContext *os;
  2213. OutputStream *ost;
  2214. InputStream *ist;
  2215. int64_t timer_start;
  2216. ret = transcode_init();
  2217. if (ret < 0)
  2218. goto fail;
  2219. av_log(NULL, AV_LOG_INFO, "Press ctrl-c to stop encoding\n");
  2220. term_init();
  2221. timer_start = av_gettime_relative();
  2222. #if HAVE_PTHREADS
  2223. if ((ret = init_input_threads()) < 0)
  2224. goto fail;
  2225. #endif
  2226. while (!received_sigterm) {
  2227. /* check if there's any stream where output is still needed */
  2228. if (!need_output()) {
  2229. av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
  2230. break;
  2231. }
  2232. /* read and process one input packet if needed */
  2233. if (need_input) {
  2234. ret = process_input();
  2235. if (ret == AVERROR_EOF)
  2236. need_input = 0;
  2237. }
  2238. ret = poll_filters();
  2239. if (ret < 0 && ret != AVERROR_EOF) {
  2240. char errbuf[128];
  2241. av_strerror(ret, errbuf, sizeof(errbuf));
  2242. av_log(NULL, AV_LOG_ERROR, "Error while filtering: %s\n", errbuf);
  2243. break;
  2244. }
  2245. /* dump report by using the output first video and audio streams */
  2246. print_report(0, timer_start);
  2247. }
  2248. #if HAVE_PTHREADS
  2249. free_input_threads();
  2250. #endif
  2251. /* at the end of stream, we must flush the decoder buffers */
  2252. for (i = 0; i < nb_input_streams; i++) {
  2253. ist = input_streams[i];
  2254. if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
  2255. process_input_packet(ist, NULL, 0);
  2256. }
  2257. }
  2258. poll_filters();
  2259. flush_encoders();
  2260. term_exit();
  2261. /* write the trailer if needed and close file */
  2262. for (i = 0; i < nb_output_files; i++) {
  2263. os = output_files[i]->ctx;
  2264. av_write_trailer(os);
  2265. }
  2266. /* dump report by using the first video and audio streams */
  2267. print_report(1, timer_start);
  2268. /* close each encoder */
  2269. for (i = 0; i < nb_output_streams; i++) {
  2270. ost = output_streams[i];
  2271. if (ost->encoding_needed) {
  2272. av_freep(&ost->enc_ctx->stats_in);
  2273. }
  2274. }
  2275. /* close each decoder */
  2276. for (i = 0; i < nb_input_streams; i++) {
  2277. ist = input_streams[i];
  2278. if (ist->decoding_needed) {
  2279. avcodec_close(ist->dec_ctx);
  2280. if (ist->hwaccel_uninit)
  2281. ist->hwaccel_uninit(ist->dec_ctx);
  2282. }
  2283. }
  2284. av_buffer_unref(&hw_device_ctx);
  2285. /* finished ! */
  2286. ret = 0;
  2287. fail:
  2288. #if HAVE_PTHREADS
  2289. free_input_threads();
  2290. #endif
  2291. if (output_streams) {
  2292. for (i = 0; i < nb_output_streams; i++) {
  2293. ost = output_streams[i];
  2294. if (ost) {
  2295. if (ost->logfile) {
  2296. fclose(ost->logfile);
  2297. ost->logfile = NULL;
  2298. }
  2299. av_free(ost->forced_kf_pts);
  2300. av_dict_free(&ost->encoder_opts);
  2301. av_dict_free(&ost->resample_opts);
  2302. }
  2303. }
  2304. }
  2305. return ret;
  2306. }
  2307. static int64_t getutime(void)
  2308. {
  2309. #if HAVE_GETRUSAGE
  2310. struct rusage rusage;
  2311. getrusage(RUSAGE_SELF, &rusage);
  2312. return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
  2313. #elif HAVE_GETPROCESSTIMES
  2314. HANDLE proc;
  2315. FILETIME c, e, k, u;
  2316. proc = GetCurrentProcess();
  2317. GetProcessTimes(proc, &c, &e, &k, &u);
  2318. return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
  2319. #else
  2320. return av_gettime_relative();
  2321. #endif
  2322. }
  2323. static int64_t getmaxrss(void)
  2324. {
  2325. #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
  2326. struct rusage rusage;
  2327. getrusage(RUSAGE_SELF, &rusage);
  2328. return (int64_t)rusage.ru_maxrss * 1024;
  2329. #elif HAVE_GETPROCESSMEMORYINFO
  2330. HANDLE proc;
  2331. PROCESS_MEMORY_COUNTERS memcounters;
  2332. proc = GetCurrentProcess();
  2333. memcounters.cb = sizeof(memcounters);
  2334. GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
  2335. return memcounters.PeakPagefileUsage;
  2336. #else
  2337. return 0;
  2338. #endif
  2339. }
  2340. int main(int argc, char **argv)
  2341. {
  2342. int ret;
  2343. int64_t ti;
  2344. register_exit(avconv_cleanup);
  2345. av_log_set_flags(AV_LOG_SKIP_REPEATED);
  2346. parse_loglevel(argc, argv, options);
  2347. avcodec_register_all();
  2348. #if CONFIG_AVDEVICE
  2349. avdevice_register_all();
  2350. #endif
  2351. avfilter_register_all();
  2352. av_register_all();
  2353. avformat_network_init();
  2354. show_banner();
  2355. /* parse options and open all input/output files */
  2356. ret = avconv_parse_options(argc, argv);
  2357. if (ret < 0)
  2358. exit_program(1);
  2359. if (nb_output_files <= 0 && nb_input_files == 0) {
  2360. show_usage();
  2361. av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
  2362. exit_program(1);
  2363. }
  2364. /* file converter / grab */
  2365. if (nb_output_files <= 0) {
  2366. fprintf(stderr, "At least one output file must be specified\n");
  2367. exit_program(1);
  2368. }
  2369. ti = getutime();
  2370. if (transcode() < 0)
  2371. exit_program(1);
  2372. ti = getutime() - ti;
  2373. if (do_benchmark) {
  2374. int maxrss = getmaxrss() / 1024;
  2375. printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);
  2376. }
  2377. exit_program(0);
  2378. return 0;
  2379. }