avconv.c 89 KB

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