ffplay.c 129 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699
  1. /*
  2. * Copyright (c) 2003 Fabrice Bellard
  3. *
  4. * This file is part of FFmpeg.
  5. *
  6. * FFmpeg is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or (at your option) any later version.
  10. *
  11. * FFmpeg is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with FFmpeg; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. /**
  21. * @file
  22. * simple media player based on the FFmpeg libraries
  23. */
  24. #include "config.h"
  25. #include <inttypes.h>
  26. #include <math.h>
  27. #include <limits.h>
  28. #include <signal.h>
  29. #include <stdint.h>
  30. #include "libavutil/avstring.h"
  31. #include "libavutil/eval.h"
  32. #include "libavutil/mathematics.h"
  33. #include "libavutil/pixdesc.h"
  34. #include "libavutil/imgutils.h"
  35. #include "libavutil/dict.h"
  36. #include "libavutil/parseutils.h"
  37. #include "libavutil/samplefmt.h"
  38. #include "libavutil/avassert.h"
  39. #include "libavutil/time.h"
  40. #include "libavformat/avformat.h"
  41. #include "libavdevice/avdevice.h"
  42. #include "libswscale/swscale.h"
  43. #include "libavutil/opt.h"
  44. #include "libavcodec/avfft.h"
  45. #include "libswresample/swresample.h"
  46. #if CONFIG_AVFILTER
  47. # include "libavfilter/avfilter.h"
  48. # include "libavfilter/buffersink.h"
  49. # include "libavfilter/buffersrc.h"
  50. #endif
  51. #include <SDL.h>
  52. #include <SDL_thread.h>
  53. #include "cmdutils.h"
  54. #include <assert.h>
  55. const char program_name[] = "ffplay";
  56. const int program_birth_year = 2003;
  57. #define MAX_QUEUE_SIZE (15 * 1024 * 1024)
  58. #define MIN_FRAMES 25
  59. #define EXTERNAL_CLOCK_MIN_FRAMES 2
  60. #define EXTERNAL_CLOCK_MAX_FRAMES 10
  61. /* Minimum SDL audio buffer size, in samples. */
  62. #define SDL_AUDIO_MIN_BUFFER_SIZE 512
  63. /* Calculate actual buffer size keeping in mind not cause too frequent audio callbacks */
  64. #define SDL_AUDIO_MAX_CALLBACKS_PER_SEC 30
  65. /* Step size for volume control in dB */
  66. #define SDL_VOLUME_STEP (0.75)
  67. /* no AV sync correction is done if below the minimum AV sync threshold */
  68. #define AV_SYNC_THRESHOLD_MIN 0.04
  69. /* AV sync correction is done if above the maximum AV sync threshold */
  70. #define AV_SYNC_THRESHOLD_MAX 0.1
  71. /* If a frame duration is longer than this, it will not be duplicated to compensate AV sync */
  72. #define AV_SYNC_FRAMEDUP_THRESHOLD 0.1
  73. /* no AV correction is done if too big error */
  74. #define AV_NOSYNC_THRESHOLD 10.0
  75. /* maximum audio speed change to get correct sync */
  76. #define SAMPLE_CORRECTION_PERCENT_MAX 10
  77. /* external clock speed adjustment constants for realtime sources based on buffer fullness */
  78. #define EXTERNAL_CLOCK_SPEED_MIN 0.900
  79. #define EXTERNAL_CLOCK_SPEED_MAX 1.010
  80. #define EXTERNAL_CLOCK_SPEED_STEP 0.001
  81. /* we use about AUDIO_DIFF_AVG_NB A-V differences to make the average */
  82. #define AUDIO_DIFF_AVG_NB 20
  83. /* polls for possible required screen refresh at least this often, should be less than 1/fps */
  84. #define REFRESH_RATE 0.01
  85. /* NOTE: the size must be big enough to compensate the hardware audio buffersize size */
  86. /* TODO: We assume that a decoded and resampled frame fits into this buffer */
  87. #define SAMPLE_ARRAY_SIZE (8 * 65536)
  88. #define CURSOR_HIDE_DELAY 1000000
  89. #define USE_ONEPASS_SUBTITLE_RENDER 1
  90. static unsigned sws_flags = SWS_BICUBIC;
  91. typedef struct MyAVPacketList {
  92. AVPacket pkt;
  93. struct MyAVPacketList *next;
  94. int serial;
  95. } MyAVPacketList;
  96. typedef struct PacketQueue {
  97. MyAVPacketList *first_pkt, *last_pkt;
  98. int nb_packets;
  99. int size;
  100. int64_t duration;
  101. int abort_request;
  102. int serial;
  103. SDL_mutex *mutex;
  104. SDL_cond *cond;
  105. } PacketQueue;
  106. #define VIDEO_PICTURE_QUEUE_SIZE 3
  107. #define SUBPICTURE_QUEUE_SIZE 16
  108. #define SAMPLE_QUEUE_SIZE 9
  109. #define FRAME_QUEUE_SIZE FFMAX(SAMPLE_QUEUE_SIZE, FFMAX(VIDEO_PICTURE_QUEUE_SIZE, SUBPICTURE_QUEUE_SIZE))
  110. typedef struct AudioParams {
  111. int freq;
  112. int channels;
  113. int64_t channel_layout;
  114. enum AVSampleFormat fmt;
  115. int frame_size;
  116. int bytes_per_sec;
  117. } AudioParams;
  118. typedef struct Clock {
  119. double pts; /* clock base */
  120. double pts_drift; /* clock base minus time at which we updated the clock */
  121. double last_updated;
  122. double speed;
  123. int serial; /* clock is based on a packet with this serial */
  124. int paused;
  125. int *queue_serial; /* pointer to the current packet queue serial, used for obsolete clock detection */
  126. } Clock;
  127. /* Common struct for handling all types of decoded data and allocated render buffers. */
  128. typedef struct Frame {
  129. AVFrame *frame;
  130. AVSubtitle sub;
  131. int serial;
  132. double pts; /* presentation timestamp for the frame */
  133. double duration; /* estimated duration of the frame */
  134. int64_t pos; /* byte position of the frame in the input file */
  135. int width;
  136. int height;
  137. int format;
  138. AVRational sar;
  139. int uploaded;
  140. int flip_v;
  141. } Frame;
  142. typedef struct FrameQueue {
  143. Frame queue[FRAME_QUEUE_SIZE];
  144. int rindex;
  145. int windex;
  146. int size;
  147. int max_size;
  148. int keep_last;
  149. int rindex_shown;
  150. SDL_mutex *mutex;
  151. SDL_cond *cond;
  152. PacketQueue *pktq;
  153. } FrameQueue;
  154. enum {
  155. AV_SYNC_AUDIO_MASTER, /* default choice */
  156. AV_SYNC_VIDEO_MASTER,
  157. AV_SYNC_EXTERNAL_CLOCK, /* synchronize to an external clock */
  158. };
  159. typedef struct Decoder {
  160. AVPacket pkt;
  161. AVPacket pkt_temp;
  162. PacketQueue *queue;
  163. AVCodecContext *avctx;
  164. int pkt_serial;
  165. int finished;
  166. int packet_pending;
  167. SDL_cond *empty_queue_cond;
  168. int64_t start_pts;
  169. AVRational start_pts_tb;
  170. int64_t next_pts;
  171. AVRational next_pts_tb;
  172. SDL_Thread *decoder_tid;
  173. } Decoder;
  174. typedef struct VideoState {
  175. SDL_Thread *read_tid;
  176. AVInputFormat *iformat;
  177. int abort_request;
  178. int force_refresh;
  179. int paused;
  180. int last_paused;
  181. int queue_attachments_req;
  182. int seek_req;
  183. int seek_flags;
  184. int64_t seek_pos;
  185. int64_t seek_rel;
  186. int read_pause_return;
  187. AVFormatContext *ic;
  188. int realtime;
  189. Clock audclk;
  190. Clock vidclk;
  191. Clock extclk;
  192. FrameQueue pictq;
  193. FrameQueue subpq;
  194. FrameQueue sampq;
  195. Decoder auddec;
  196. Decoder viddec;
  197. Decoder subdec;
  198. int audio_stream;
  199. int av_sync_type;
  200. double audio_clock;
  201. int audio_clock_serial;
  202. double audio_diff_cum; /* used for AV difference average computation */
  203. double audio_diff_avg_coef;
  204. double audio_diff_threshold;
  205. int audio_diff_avg_count;
  206. AVStream *audio_st;
  207. PacketQueue audioq;
  208. int audio_hw_buf_size;
  209. uint8_t *audio_buf;
  210. uint8_t *audio_buf1;
  211. unsigned int audio_buf_size; /* in bytes */
  212. unsigned int audio_buf1_size;
  213. int audio_buf_index; /* in bytes */
  214. int audio_write_buf_size;
  215. int audio_volume;
  216. int muted;
  217. struct AudioParams audio_src;
  218. #if CONFIG_AVFILTER
  219. struct AudioParams audio_filter_src;
  220. #endif
  221. struct AudioParams audio_tgt;
  222. struct SwrContext *swr_ctx;
  223. int frame_drops_early;
  224. int frame_drops_late;
  225. enum ShowMode {
  226. SHOW_MODE_NONE = -1, SHOW_MODE_VIDEO = 0, SHOW_MODE_WAVES, SHOW_MODE_RDFT, SHOW_MODE_NB
  227. } show_mode;
  228. int16_t sample_array[SAMPLE_ARRAY_SIZE];
  229. int sample_array_index;
  230. int last_i_start;
  231. RDFTContext *rdft;
  232. int rdft_bits;
  233. FFTSample *rdft_data;
  234. int xpos;
  235. double last_vis_time;
  236. SDL_Texture *vis_texture;
  237. SDL_Texture *sub_texture;
  238. SDL_Texture *vid_texture;
  239. int subtitle_stream;
  240. AVStream *subtitle_st;
  241. PacketQueue subtitleq;
  242. double frame_timer;
  243. double frame_last_returned_time;
  244. double frame_last_filter_delay;
  245. int video_stream;
  246. AVStream *video_st;
  247. PacketQueue videoq;
  248. double max_frame_duration; // maximum duration of a frame - above this, we consider the jump a timestamp discontinuity
  249. struct SwsContext *img_convert_ctx;
  250. struct SwsContext *sub_convert_ctx;
  251. int eof;
  252. char *filename;
  253. int width, height, xleft, ytop;
  254. int step;
  255. #if CONFIG_AVFILTER
  256. int vfilter_idx;
  257. AVFilterContext *in_video_filter; // the first filter in the video chain
  258. AVFilterContext *out_video_filter; // the last filter in the video chain
  259. AVFilterContext *in_audio_filter; // the first filter in the audio chain
  260. AVFilterContext *out_audio_filter; // the last filter in the audio chain
  261. AVFilterGraph *agraph; // audio filter graph
  262. #endif
  263. int last_video_stream, last_audio_stream, last_subtitle_stream;
  264. SDL_cond *continue_read_thread;
  265. } VideoState;
  266. /* options specified by the user */
  267. static AVInputFormat *file_iformat;
  268. static const char *input_filename;
  269. static const char *window_title;
  270. static int default_width = 640;
  271. static int default_height = 480;
  272. static int screen_width = 0;
  273. static int screen_height = 0;
  274. static int audio_disable;
  275. static int video_disable;
  276. static int subtitle_disable;
  277. static const char* wanted_stream_spec[AVMEDIA_TYPE_NB] = {0};
  278. static int seek_by_bytes = -1;
  279. static int display_disable;
  280. static int borderless;
  281. static int startup_volume = 100;
  282. static int show_status = 1;
  283. static int av_sync_type = AV_SYNC_AUDIO_MASTER;
  284. static int64_t start_time = AV_NOPTS_VALUE;
  285. static int64_t duration = AV_NOPTS_VALUE;
  286. static int fast = 0;
  287. static int genpts = 0;
  288. static int lowres = 0;
  289. static int decoder_reorder_pts = -1;
  290. static int autoexit;
  291. static int exit_on_keydown;
  292. static int exit_on_mousedown;
  293. static int loop = 1;
  294. static int framedrop = -1;
  295. static int infinite_buffer = -1;
  296. static enum ShowMode show_mode = SHOW_MODE_NONE;
  297. static const char *audio_codec_name;
  298. static const char *subtitle_codec_name;
  299. static const char *video_codec_name;
  300. double rdftspeed = 0.02;
  301. static int64_t cursor_last_shown;
  302. static int cursor_hidden = 0;
  303. #if CONFIG_AVFILTER
  304. static const char **vfilters_list = NULL;
  305. static int nb_vfilters = 0;
  306. static char *afilters = NULL;
  307. #endif
  308. static int autorotate = 1;
  309. /* current context */
  310. static int is_full_screen;
  311. static int64_t audio_callback_time;
  312. static AVPacket flush_pkt;
  313. #define FF_QUIT_EVENT (SDL_USEREVENT + 2)
  314. static SDL_Window *window;
  315. static SDL_Renderer *renderer;
  316. #if CONFIG_AVFILTER
  317. static int opt_add_vfilter(void *optctx, const char *opt, const char *arg)
  318. {
  319. GROW_ARRAY(vfilters_list, nb_vfilters);
  320. vfilters_list[nb_vfilters - 1] = arg;
  321. return 0;
  322. }
  323. #endif
  324. static inline
  325. int cmp_audio_fmts(enum AVSampleFormat fmt1, int64_t channel_count1,
  326. enum AVSampleFormat fmt2, int64_t channel_count2)
  327. {
  328. /* If channel count == 1, planar and non-planar formats are the same */
  329. if (channel_count1 == 1 && channel_count2 == 1)
  330. return av_get_packed_sample_fmt(fmt1) != av_get_packed_sample_fmt(fmt2);
  331. else
  332. return channel_count1 != channel_count2 || fmt1 != fmt2;
  333. }
  334. static inline
  335. int64_t get_valid_channel_layout(int64_t channel_layout, int channels)
  336. {
  337. if (channel_layout && av_get_channel_layout_nb_channels(channel_layout) == channels)
  338. return channel_layout;
  339. else
  340. return 0;
  341. }
  342. static int packet_queue_put_private(PacketQueue *q, AVPacket *pkt)
  343. {
  344. MyAVPacketList *pkt1;
  345. if (q->abort_request)
  346. return -1;
  347. pkt1 = av_malloc(sizeof(MyAVPacketList));
  348. if (!pkt1)
  349. return -1;
  350. pkt1->pkt = *pkt;
  351. pkt1->next = NULL;
  352. if (pkt == &flush_pkt)
  353. q->serial++;
  354. pkt1->serial = q->serial;
  355. if (!q->last_pkt)
  356. q->first_pkt = pkt1;
  357. else
  358. q->last_pkt->next = pkt1;
  359. q->last_pkt = pkt1;
  360. q->nb_packets++;
  361. q->size += pkt1->pkt.size + sizeof(*pkt1);
  362. q->duration += pkt1->pkt.duration;
  363. /* XXX: should duplicate packet data in DV case */
  364. SDL_CondSignal(q->cond);
  365. return 0;
  366. }
  367. static int packet_queue_put(PacketQueue *q, AVPacket *pkt)
  368. {
  369. int ret;
  370. SDL_LockMutex(q->mutex);
  371. ret = packet_queue_put_private(q, pkt);
  372. SDL_UnlockMutex(q->mutex);
  373. if (pkt != &flush_pkt && ret < 0)
  374. av_packet_unref(pkt);
  375. return ret;
  376. }
  377. static int packet_queue_put_nullpacket(PacketQueue *q, int stream_index)
  378. {
  379. AVPacket pkt1, *pkt = &pkt1;
  380. av_init_packet(pkt);
  381. pkt->data = NULL;
  382. pkt->size = 0;
  383. pkt->stream_index = stream_index;
  384. return packet_queue_put(q, pkt);
  385. }
  386. /* packet queue handling */
  387. static int packet_queue_init(PacketQueue *q)
  388. {
  389. memset(q, 0, sizeof(PacketQueue));
  390. q->mutex = SDL_CreateMutex();
  391. if (!q->mutex) {
  392. av_log(NULL, AV_LOG_FATAL, "SDL_CreateMutex(): %s\n", SDL_GetError());
  393. return AVERROR(ENOMEM);
  394. }
  395. q->cond = SDL_CreateCond();
  396. if (!q->cond) {
  397. av_log(NULL, AV_LOG_FATAL, "SDL_CreateCond(): %s\n", SDL_GetError());
  398. return AVERROR(ENOMEM);
  399. }
  400. q->abort_request = 1;
  401. return 0;
  402. }
  403. static void packet_queue_flush(PacketQueue *q)
  404. {
  405. MyAVPacketList *pkt, *pkt1;
  406. SDL_LockMutex(q->mutex);
  407. for (pkt = q->first_pkt; pkt; pkt = pkt1) {
  408. pkt1 = pkt->next;
  409. av_packet_unref(&pkt->pkt);
  410. av_freep(&pkt);
  411. }
  412. q->last_pkt = NULL;
  413. q->first_pkt = NULL;
  414. q->nb_packets = 0;
  415. q->size = 0;
  416. q->duration = 0;
  417. SDL_UnlockMutex(q->mutex);
  418. }
  419. static void packet_queue_destroy(PacketQueue *q)
  420. {
  421. packet_queue_flush(q);
  422. SDL_DestroyMutex(q->mutex);
  423. SDL_DestroyCond(q->cond);
  424. }
  425. static void packet_queue_abort(PacketQueue *q)
  426. {
  427. SDL_LockMutex(q->mutex);
  428. q->abort_request = 1;
  429. SDL_CondSignal(q->cond);
  430. SDL_UnlockMutex(q->mutex);
  431. }
  432. static void packet_queue_start(PacketQueue *q)
  433. {
  434. SDL_LockMutex(q->mutex);
  435. q->abort_request = 0;
  436. packet_queue_put_private(q, &flush_pkt);
  437. SDL_UnlockMutex(q->mutex);
  438. }
  439. /* return < 0 if aborted, 0 if no packet and > 0 if packet. */
  440. static int packet_queue_get(PacketQueue *q, AVPacket *pkt, int block, int *serial)
  441. {
  442. MyAVPacketList *pkt1;
  443. int ret;
  444. SDL_LockMutex(q->mutex);
  445. for (;;) {
  446. if (q->abort_request) {
  447. ret = -1;
  448. break;
  449. }
  450. pkt1 = q->first_pkt;
  451. if (pkt1) {
  452. q->first_pkt = pkt1->next;
  453. if (!q->first_pkt)
  454. q->last_pkt = NULL;
  455. q->nb_packets--;
  456. q->size -= pkt1->pkt.size + sizeof(*pkt1);
  457. q->duration -= pkt1->pkt.duration;
  458. *pkt = pkt1->pkt;
  459. if (serial)
  460. *serial = pkt1->serial;
  461. av_free(pkt1);
  462. ret = 1;
  463. break;
  464. } else if (!block) {
  465. ret = 0;
  466. break;
  467. } else {
  468. SDL_CondWait(q->cond, q->mutex);
  469. }
  470. }
  471. SDL_UnlockMutex(q->mutex);
  472. return ret;
  473. }
  474. static void decoder_init(Decoder *d, AVCodecContext *avctx, PacketQueue *queue, SDL_cond *empty_queue_cond) {
  475. memset(d, 0, sizeof(Decoder));
  476. d->avctx = avctx;
  477. d->queue = queue;
  478. d->empty_queue_cond = empty_queue_cond;
  479. d->start_pts = AV_NOPTS_VALUE;
  480. }
  481. static int decoder_decode_frame(Decoder *d, AVFrame *frame, AVSubtitle *sub) {
  482. int got_frame = 0;
  483. do {
  484. int ret = -1;
  485. if (d->queue->abort_request)
  486. return -1;
  487. if (!d->packet_pending || d->queue->serial != d->pkt_serial) {
  488. AVPacket pkt;
  489. do {
  490. if (d->queue->nb_packets == 0)
  491. SDL_CondSignal(d->empty_queue_cond);
  492. if (packet_queue_get(d->queue, &pkt, 1, &d->pkt_serial) < 0)
  493. return -1;
  494. if (pkt.data == flush_pkt.data) {
  495. avcodec_flush_buffers(d->avctx);
  496. d->finished = 0;
  497. d->next_pts = d->start_pts;
  498. d->next_pts_tb = d->start_pts_tb;
  499. }
  500. } while (pkt.data == flush_pkt.data || d->queue->serial != d->pkt_serial);
  501. av_packet_unref(&d->pkt);
  502. d->pkt_temp = d->pkt = pkt;
  503. d->packet_pending = 1;
  504. }
  505. switch (d->avctx->codec_type) {
  506. case AVMEDIA_TYPE_VIDEO:
  507. ret = avcodec_decode_video2(d->avctx, frame, &got_frame, &d->pkt_temp);
  508. if (got_frame) {
  509. if (decoder_reorder_pts == -1) {
  510. frame->pts = av_frame_get_best_effort_timestamp(frame);
  511. } else if (!decoder_reorder_pts) {
  512. frame->pts = frame->pkt_dts;
  513. }
  514. }
  515. break;
  516. case AVMEDIA_TYPE_AUDIO:
  517. ret = avcodec_decode_audio4(d->avctx, frame, &got_frame, &d->pkt_temp);
  518. if (got_frame) {
  519. AVRational tb = (AVRational){1, frame->sample_rate};
  520. if (frame->pts != AV_NOPTS_VALUE)
  521. frame->pts = av_rescale_q(frame->pts, av_codec_get_pkt_timebase(d->avctx), tb);
  522. else if (d->next_pts != AV_NOPTS_VALUE)
  523. frame->pts = av_rescale_q(d->next_pts, d->next_pts_tb, tb);
  524. if (frame->pts != AV_NOPTS_VALUE) {
  525. d->next_pts = frame->pts + frame->nb_samples;
  526. d->next_pts_tb = tb;
  527. }
  528. }
  529. break;
  530. case AVMEDIA_TYPE_SUBTITLE:
  531. ret = avcodec_decode_subtitle2(d->avctx, sub, &got_frame, &d->pkt_temp);
  532. break;
  533. }
  534. if (ret < 0) {
  535. d->packet_pending = 0;
  536. } else {
  537. d->pkt_temp.dts =
  538. d->pkt_temp.pts = AV_NOPTS_VALUE;
  539. if (d->pkt_temp.data) {
  540. if (d->avctx->codec_type != AVMEDIA_TYPE_AUDIO)
  541. ret = d->pkt_temp.size;
  542. d->pkt_temp.data += ret;
  543. d->pkt_temp.size -= ret;
  544. if (d->pkt_temp.size <= 0)
  545. d->packet_pending = 0;
  546. } else {
  547. if (!got_frame) {
  548. d->packet_pending = 0;
  549. d->finished = d->pkt_serial;
  550. }
  551. }
  552. }
  553. } while (!got_frame && !d->finished);
  554. return got_frame;
  555. }
  556. static void decoder_destroy(Decoder *d) {
  557. av_packet_unref(&d->pkt);
  558. avcodec_free_context(&d->avctx);
  559. }
  560. static void frame_queue_unref_item(Frame *vp)
  561. {
  562. av_frame_unref(vp->frame);
  563. avsubtitle_free(&vp->sub);
  564. }
  565. static int frame_queue_init(FrameQueue *f, PacketQueue *pktq, int max_size, int keep_last)
  566. {
  567. int i;
  568. memset(f, 0, sizeof(FrameQueue));
  569. if (!(f->mutex = SDL_CreateMutex())) {
  570. av_log(NULL, AV_LOG_FATAL, "SDL_CreateMutex(): %s\n", SDL_GetError());
  571. return AVERROR(ENOMEM);
  572. }
  573. if (!(f->cond = SDL_CreateCond())) {
  574. av_log(NULL, AV_LOG_FATAL, "SDL_CreateCond(): %s\n", SDL_GetError());
  575. return AVERROR(ENOMEM);
  576. }
  577. f->pktq = pktq;
  578. f->max_size = FFMIN(max_size, FRAME_QUEUE_SIZE);
  579. f->keep_last = !!keep_last;
  580. for (i = 0; i < f->max_size; i++)
  581. if (!(f->queue[i].frame = av_frame_alloc()))
  582. return AVERROR(ENOMEM);
  583. return 0;
  584. }
  585. static void frame_queue_destory(FrameQueue *f)
  586. {
  587. int i;
  588. for (i = 0; i < f->max_size; i++) {
  589. Frame *vp = &f->queue[i];
  590. frame_queue_unref_item(vp);
  591. av_frame_free(&vp->frame);
  592. }
  593. SDL_DestroyMutex(f->mutex);
  594. SDL_DestroyCond(f->cond);
  595. }
  596. static void frame_queue_signal(FrameQueue *f)
  597. {
  598. SDL_LockMutex(f->mutex);
  599. SDL_CondSignal(f->cond);
  600. SDL_UnlockMutex(f->mutex);
  601. }
  602. static Frame *frame_queue_peek(FrameQueue *f)
  603. {
  604. return &f->queue[(f->rindex + f->rindex_shown) % f->max_size];
  605. }
  606. static Frame *frame_queue_peek_next(FrameQueue *f)
  607. {
  608. return &f->queue[(f->rindex + f->rindex_shown + 1) % f->max_size];
  609. }
  610. static Frame *frame_queue_peek_last(FrameQueue *f)
  611. {
  612. return &f->queue[f->rindex];
  613. }
  614. static Frame *frame_queue_peek_writable(FrameQueue *f)
  615. {
  616. /* wait until we have space to put a new frame */
  617. SDL_LockMutex(f->mutex);
  618. while (f->size >= f->max_size &&
  619. !f->pktq->abort_request) {
  620. SDL_CondWait(f->cond, f->mutex);
  621. }
  622. SDL_UnlockMutex(f->mutex);
  623. if (f->pktq->abort_request)
  624. return NULL;
  625. return &f->queue[f->windex];
  626. }
  627. static Frame *frame_queue_peek_readable(FrameQueue *f)
  628. {
  629. /* wait until we have a readable a new frame */
  630. SDL_LockMutex(f->mutex);
  631. while (f->size - f->rindex_shown <= 0 &&
  632. !f->pktq->abort_request) {
  633. SDL_CondWait(f->cond, f->mutex);
  634. }
  635. SDL_UnlockMutex(f->mutex);
  636. if (f->pktq->abort_request)
  637. return NULL;
  638. return &f->queue[(f->rindex + f->rindex_shown) % f->max_size];
  639. }
  640. static void frame_queue_push(FrameQueue *f)
  641. {
  642. if (++f->windex == f->max_size)
  643. f->windex = 0;
  644. SDL_LockMutex(f->mutex);
  645. f->size++;
  646. SDL_CondSignal(f->cond);
  647. SDL_UnlockMutex(f->mutex);
  648. }
  649. static void frame_queue_next(FrameQueue *f)
  650. {
  651. if (f->keep_last && !f->rindex_shown) {
  652. f->rindex_shown = 1;
  653. return;
  654. }
  655. frame_queue_unref_item(&f->queue[f->rindex]);
  656. if (++f->rindex == f->max_size)
  657. f->rindex = 0;
  658. SDL_LockMutex(f->mutex);
  659. f->size--;
  660. SDL_CondSignal(f->cond);
  661. SDL_UnlockMutex(f->mutex);
  662. }
  663. /* return the number of undisplayed frames in the queue */
  664. static int frame_queue_nb_remaining(FrameQueue *f)
  665. {
  666. return f->size - f->rindex_shown;
  667. }
  668. /* return last shown position */
  669. static int64_t frame_queue_last_pos(FrameQueue *f)
  670. {
  671. Frame *fp = &f->queue[f->rindex];
  672. if (f->rindex_shown && fp->serial == f->pktq->serial)
  673. return fp->pos;
  674. else
  675. return -1;
  676. }
  677. static void decoder_abort(Decoder *d, FrameQueue *fq)
  678. {
  679. packet_queue_abort(d->queue);
  680. frame_queue_signal(fq);
  681. SDL_WaitThread(d->decoder_tid, NULL);
  682. d->decoder_tid = NULL;
  683. packet_queue_flush(d->queue);
  684. }
  685. static inline void fill_rectangle(int x, int y, int w, int h)
  686. {
  687. SDL_Rect rect;
  688. rect.x = x;
  689. rect.y = y;
  690. rect.w = w;
  691. rect.h = h;
  692. if (w && h)
  693. SDL_RenderFillRect(renderer, &rect);
  694. }
  695. static int realloc_texture(SDL_Texture **texture, Uint32 new_format, int new_width, int new_height, SDL_BlendMode blendmode, int init_texture)
  696. {
  697. Uint32 format;
  698. int access, w, h;
  699. if (SDL_QueryTexture(*texture, &format, &access, &w, &h) < 0 || new_width != w || new_height != h || new_format != format) {
  700. void *pixels;
  701. int pitch;
  702. SDL_DestroyTexture(*texture);
  703. if (!(*texture = SDL_CreateTexture(renderer, new_format, SDL_TEXTUREACCESS_STREAMING, new_width, new_height)))
  704. return -1;
  705. if (SDL_SetTextureBlendMode(*texture, blendmode) < 0)
  706. return -1;
  707. if (init_texture) {
  708. if (SDL_LockTexture(*texture, NULL, &pixels, &pitch) < 0)
  709. return -1;
  710. memset(pixels, 0, pitch * new_height);
  711. SDL_UnlockTexture(*texture);
  712. }
  713. }
  714. return 0;
  715. }
  716. static void calculate_display_rect(SDL_Rect *rect,
  717. int scr_xleft, int scr_ytop, int scr_width, int scr_height,
  718. int pic_width, int pic_height, AVRational pic_sar)
  719. {
  720. float aspect_ratio;
  721. int width, height, x, y;
  722. if (pic_sar.num == 0)
  723. aspect_ratio = 0;
  724. else
  725. aspect_ratio = av_q2d(pic_sar);
  726. if (aspect_ratio <= 0.0)
  727. aspect_ratio = 1.0;
  728. aspect_ratio *= (float)pic_width / (float)pic_height;
  729. /* XXX: we suppose the screen has a 1.0 pixel ratio */
  730. height = scr_height;
  731. width = lrint(height * aspect_ratio) & ~1;
  732. if (width > scr_width) {
  733. width = scr_width;
  734. height = lrint(width / aspect_ratio) & ~1;
  735. }
  736. x = (scr_width - width) / 2;
  737. y = (scr_height - height) / 2;
  738. rect->x = scr_xleft + x;
  739. rect->y = scr_ytop + y;
  740. rect->w = FFMAX(width, 1);
  741. rect->h = FFMAX(height, 1);
  742. }
  743. static int upload_texture(SDL_Texture *tex, AVFrame *frame, struct SwsContext **img_convert_ctx) {
  744. int ret = 0;
  745. switch (frame->format) {
  746. case AV_PIX_FMT_YUV420P:
  747. if (frame->linesize[0] < 0 || frame->linesize[1] < 0 || frame->linesize[2] < 0) {
  748. av_log(NULL, AV_LOG_ERROR, "Negative linesize is not supported for YUV.\n");
  749. return -1;
  750. }
  751. ret = SDL_UpdateYUVTexture(tex, NULL, frame->data[0], frame->linesize[0],
  752. frame->data[1], frame->linesize[1],
  753. frame->data[2], frame->linesize[2]);
  754. break;
  755. case AV_PIX_FMT_BGRA:
  756. if (frame->linesize[0] < 0) {
  757. ret = SDL_UpdateTexture(tex, NULL, frame->data[0] + frame->linesize[0] * (frame->height - 1), -frame->linesize[0]);
  758. } else {
  759. ret = SDL_UpdateTexture(tex, NULL, frame->data[0], frame->linesize[0]);
  760. }
  761. break;
  762. default:
  763. /* This should only happen if we are not using avfilter... */
  764. *img_convert_ctx = sws_getCachedContext(*img_convert_ctx,
  765. frame->width, frame->height, frame->format, frame->width, frame->height,
  766. AV_PIX_FMT_BGRA, sws_flags, NULL, NULL, NULL);
  767. if (*img_convert_ctx != NULL) {
  768. uint8_t *pixels[4];
  769. int pitch[4];
  770. if (!SDL_LockTexture(tex, NULL, (void **)pixels, pitch)) {
  771. sws_scale(*img_convert_ctx, (const uint8_t * const *)frame->data, frame->linesize,
  772. 0, frame->height, pixels, pitch);
  773. SDL_UnlockTexture(tex);
  774. }
  775. } else {
  776. av_log(NULL, AV_LOG_FATAL, "Cannot initialize the conversion context\n");
  777. ret = -1;
  778. }
  779. break;
  780. }
  781. return ret;
  782. }
  783. static void video_image_display(VideoState *is)
  784. {
  785. Frame *vp;
  786. Frame *sp = NULL;
  787. SDL_Rect rect;
  788. vp = frame_queue_peek_last(&is->pictq);
  789. if (is->subtitle_st) {
  790. if (frame_queue_nb_remaining(&is->subpq) > 0) {
  791. sp = frame_queue_peek(&is->subpq);
  792. if (vp->pts >= sp->pts + ((float) sp->sub.start_display_time / 1000)) {
  793. if (!sp->uploaded) {
  794. uint8_t* pixels[4];
  795. int pitch[4];
  796. int i;
  797. if (!sp->width || !sp->height) {
  798. sp->width = vp->width;
  799. sp->height = vp->height;
  800. }
  801. if (realloc_texture(&is->sub_texture, SDL_PIXELFORMAT_ARGB8888, sp->width, sp->height, SDL_BLENDMODE_BLEND, 1) < 0)
  802. return;
  803. for (i = 0; i < sp->sub.num_rects; i++) {
  804. AVSubtitleRect *sub_rect = sp->sub.rects[i];
  805. sub_rect->x = av_clip(sub_rect->x, 0, sp->width );
  806. sub_rect->y = av_clip(sub_rect->y, 0, sp->height);
  807. sub_rect->w = av_clip(sub_rect->w, 0, sp->width - sub_rect->x);
  808. sub_rect->h = av_clip(sub_rect->h, 0, sp->height - sub_rect->y);
  809. is->sub_convert_ctx = sws_getCachedContext(is->sub_convert_ctx,
  810. sub_rect->w, sub_rect->h, AV_PIX_FMT_PAL8,
  811. sub_rect->w, sub_rect->h, AV_PIX_FMT_BGRA,
  812. 0, NULL, NULL, NULL);
  813. if (!is->sub_convert_ctx) {
  814. av_log(NULL, AV_LOG_FATAL, "Cannot initialize the conversion context\n");
  815. return;
  816. }
  817. if (!SDL_LockTexture(is->sub_texture, (SDL_Rect *)sub_rect, (void **)pixels, pitch)) {
  818. sws_scale(is->sub_convert_ctx, (const uint8_t * const *)sub_rect->data, sub_rect->linesize,
  819. 0, sub_rect->h, pixels, pitch);
  820. SDL_UnlockTexture(is->sub_texture);
  821. }
  822. }
  823. sp->uploaded = 1;
  824. }
  825. } else
  826. sp = NULL;
  827. }
  828. }
  829. calculate_display_rect(&rect, is->xleft, is->ytop, is->width, is->height, vp->width, vp->height, vp->sar);
  830. if (!vp->uploaded) {
  831. int sdl_pix_fmt = vp->frame->format == AV_PIX_FMT_YUV420P ? SDL_PIXELFORMAT_YV12 : SDL_PIXELFORMAT_ARGB8888;
  832. if (realloc_texture(&is->vid_texture, sdl_pix_fmt, vp->frame->width, vp->frame->height, SDL_BLENDMODE_NONE, 0) < 0)
  833. return;
  834. if (upload_texture(is->vid_texture, vp->frame, &is->img_convert_ctx) < 0)
  835. return;
  836. vp->uploaded = 1;
  837. vp->flip_v = vp->frame->linesize[0] < 0;
  838. }
  839. SDL_RenderCopyEx(renderer, is->vid_texture, NULL, &rect, 0, NULL, vp->flip_v ? SDL_FLIP_VERTICAL : 0);
  840. if (sp) {
  841. #if USE_ONEPASS_SUBTITLE_RENDER
  842. SDL_RenderCopy(renderer, is->sub_texture, NULL, &rect);
  843. #else
  844. int i;
  845. double xratio = (double)rect.w / (double)sp->width;
  846. double yratio = (double)rect.h / (double)sp->height;
  847. for (i = 0; i < sp->sub.num_rects; i++) {
  848. SDL_Rect *sub_rect = (SDL_Rect*)sp->sub.rects[i];
  849. SDL_Rect target = {.x = rect.x + sub_rect->x * xratio,
  850. .y = rect.y + sub_rect->y * yratio,
  851. .w = sub_rect->w * xratio,
  852. .h = sub_rect->h * yratio};
  853. SDL_RenderCopy(renderer, is->sub_texture, sub_rect, &target);
  854. }
  855. #endif
  856. }
  857. }
  858. static inline int compute_mod(int a, int b)
  859. {
  860. return a < 0 ? a%b + b : a%b;
  861. }
  862. static void video_audio_display(VideoState *s)
  863. {
  864. int i, i_start, x, y1, y, ys, delay, n, nb_display_channels;
  865. int ch, channels, h, h2;
  866. int64_t time_diff;
  867. int rdft_bits, nb_freq;
  868. for (rdft_bits = 1; (1 << rdft_bits) < 2 * s->height; rdft_bits++)
  869. ;
  870. nb_freq = 1 << (rdft_bits - 1);
  871. /* compute display index : center on currently output samples */
  872. channels = s->audio_tgt.channels;
  873. nb_display_channels = channels;
  874. if (!s->paused) {
  875. int data_used= s->show_mode == SHOW_MODE_WAVES ? s->width : (2*nb_freq);
  876. n = 2 * channels;
  877. delay = s->audio_write_buf_size;
  878. delay /= n;
  879. /* to be more precise, we take into account the time spent since
  880. the last buffer computation */
  881. if (audio_callback_time) {
  882. time_diff = av_gettime_relative() - audio_callback_time;
  883. delay -= (time_diff * s->audio_tgt.freq) / 1000000;
  884. }
  885. delay += 2 * data_used;
  886. if (delay < data_used)
  887. delay = data_used;
  888. i_start= x = compute_mod(s->sample_array_index - delay * channels, SAMPLE_ARRAY_SIZE);
  889. if (s->show_mode == SHOW_MODE_WAVES) {
  890. h = INT_MIN;
  891. for (i = 0; i < 1000; i += channels) {
  892. int idx = (SAMPLE_ARRAY_SIZE + x - i) % SAMPLE_ARRAY_SIZE;
  893. int a = s->sample_array[idx];
  894. int b = s->sample_array[(idx + 4 * channels) % SAMPLE_ARRAY_SIZE];
  895. int c = s->sample_array[(idx + 5 * channels) % SAMPLE_ARRAY_SIZE];
  896. int d = s->sample_array[(idx + 9 * channels) % SAMPLE_ARRAY_SIZE];
  897. int score = a - d;
  898. if (h < score && (b ^ c) < 0) {
  899. h = score;
  900. i_start = idx;
  901. }
  902. }
  903. }
  904. s->last_i_start = i_start;
  905. } else {
  906. i_start = s->last_i_start;
  907. }
  908. if (s->show_mode == SHOW_MODE_WAVES) {
  909. SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
  910. /* total height for one channel */
  911. h = s->height / nb_display_channels;
  912. /* graph height / 2 */
  913. h2 = (h * 9) / 20;
  914. for (ch = 0; ch < nb_display_channels; ch++) {
  915. i = i_start + ch;
  916. y1 = s->ytop + ch * h + (h / 2); /* position of center line */
  917. for (x = 0; x < s->width; x++) {
  918. y = (s->sample_array[i] * h2) >> 15;
  919. if (y < 0) {
  920. y = -y;
  921. ys = y1 - y;
  922. } else {
  923. ys = y1;
  924. }
  925. fill_rectangle(s->xleft + x, ys, 1, y);
  926. i += channels;
  927. if (i >= SAMPLE_ARRAY_SIZE)
  928. i -= SAMPLE_ARRAY_SIZE;
  929. }
  930. }
  931. SDL_SetRenderDrawColor(renderer, 0, 0, 255, 255);
  932. for (ch = 1; ch < nb_display_channels; ch++) {
  933. y = s->ytop + ch * h;
  934. fill_rectangle(s->xleft, y, s->width, 1);
  935. }
  936. } else {
  937. if (realloc_texture(&s->vis_texture, SDL_PIXELFORMAT_ARGB8888, s->width, s->height, SDL_BLENDMODE_NONE, 1) < 0)
  938. return;
  939. nb_display_channels= FFMIN(nb_display_channels, 2);
  940. if (rdft_bits != s->rdft_bits) {
  941. av_rdft_end(s->rdft);
  942. av_free(s->rdft_data);
  943. s->rdft = av_rdft_init(rdft_bits, DFT_R2C);
  944. s->rdft_bits = rdft_bits;
  945. s->rdft_data = av_malloc_array(nb_freq, 4 *sizeof(*s->rdft_data));
  946. }
  947. if (!s->rdft || !s->rdft_data){
  948. av_log(NULL, AV_LOG_ERROR, "Failed to allocate buffers for RDFT, switching to waves display\n");
  949. s->show_mode = SHOW_MODE_WAVES;
  950. } else {
  951. FFTSample *data[2];
  952. SDL_Rect rect = {.x = s->xpos, .y = 0, .w = 1, .h = s->height};
  953. uint32_t *pixels;
  954. int pitch;
  955. for (ch = 0; ch < nb_display_channels; ch++) {
  956. data[ch] = s->rdft_data + 2 * nb_freq * ch;
  957. i = i_start + ch;
  958. for (x = 0; x < 2 * nb_freq; x++) {
  959. double w = (x-nb_freq) * (1.0 / nb_freq);
  960. data[ch][x] = s->sample_array[i] * (1.0 - w * w);
  961. i += channels;
  962. if (i >= SAMPLE_ARRAY_SIZE)
  963. i -= SAMPLE_ARRAY_SIZE;
  964. }
  965. av_rdft_calc(s->rdft, data[ch]);
  966. }
  967. /* Least efficient way to do this, we should of course
  968. * directly access it but it is more than fast enough. */
  969. if (!SDL_LockTexture(s->vis_texture, &rect, (void **)&pixels, &pitch)) {
  970. pitch >>= 2;
  971. pixels += pitch * s->height;
  972. for (y = 0; y < s->height; y++) {
  973. double w = 1 / sqrt(nb_freq);
  974. int a = sqrt(w * sqrt(data[0][2 * y + 0] * data[0][2 * y + 0] + data[0][2 * y + 1] * data[0][2 * y + 1]));
  975. int b = (nb_display_channels == 2 ) ? sqrt(w * hypot(data[1][2 * y + 0], data[1][2 * y + 1]))
  976. : a;
  977. a = FFMIN(a, 255);
  978. b = FFMIN(b, 255);
  979. pixels -= pitch;
  980. *pixels = (a << 16) + (b << 8) + ((a+b) >> 1);
  981. }
  982. SDL_UnlockTexture(s->vis_texture);
  983. }
  984. SDL_RenderCopy(renderer, s->vis_texture, NULL, NULL);
  985. }
  986. if (!s->paused)
  987. s->xpos++;
  988. if (s->xpos >= s->width)
  989. s->xpos= s->xleft;
  990. }
  991. }
  992. static void stream_component_close(VideoState *is, int stream_index)
  993. {
  994. AVFormatContext *ic = is->ic;
  995. AVCodecParameters *codecpar;
  996. if (stream_index < 0 || stream_index >= ic->nb_streams)
  997. return;
  998. codecpar = ic->streams[stream_index]->codecpar;
  999. switch (codecpar->codec_type) {
  1000. case AVMEDIA_TYPE_AUDIO:
  1001. decoder_abort(&is->auddec, &is->sampq);
  1002. SDL_CloseAudio();
  1003. decoder_destroy(&is->auddec);
  1004. swr_free(&is->swr_ctx);
  1005. av_freep(&is->audio_buf1);
  1006. is->audio_buf1_size = 0;
  1007. is->audio_buf = NULL;
  1008. if (is->rdft) {
  1009. av_rdft_end(is->rdft);
  1010. av_freep(&is->rdft_data);
  1011. is->rdft = NULL;
  1012. is->rdft_bits = 0;
  1013. }
  1014. break;
  1015. case AVMEDIA_TYPE_VIDEO:
  1016. decoder_abort(&is->viddec, &is->pictq);
  1017. decoder_destroy(&is->viddec);
  1018. break;
  1019. case AVMEDIA_TYPE_SUBTITLE:
  1020. decoder_abort(&is->subdec, &is->subpq);
  1021. decoder_destroy(&is->subdec);
  1022. break;
  1023. default:
  1024. break;
  1025. }
  1026. ic->streams[stream_index]->discard = AVDISCARD_ALL;
  1027. switch (codecpar->codec_type) {
  1028. case AVMEDIA_TYPE_AUDIO:
  1029. is->audio_st = NULL;
  1030. is->audio_stream = -1;
  1031. break;
  1032. case AVMEDIA_TYPE_VIDEO:
  1033. is->video_st = NULL;
  1034. is->video_stream = -1;
  1035. break;
  1036. case AVMEDIA_TYPE_SUBTITLE:
  1037. is->subtitle_st = NULL;
  1038. is->subtitle_stream = -1;
  1039. break;
  1040. default:
  1041. break;
  1042. }
  1043. }
  1044. static void stream_close(VideoState *is)
  1045. {
  1046. /* XXX: use a special url_shutdown call to abort parse cleanly */
  1047. is->abort_request = 1;
  1048. SDL_WaitThread(is->read_tid, NULL);
  1049. /* close each stream */
  1050. if (is->audio_stream >= 0)
  1051. stream_component_close(is, is->audio_stream);
  1052. if (is->video_stream >= 0)
  1053. stream_component_close(is, is->video_stream);
  1054. if (is->subtitle_stream >= 0)
  1055. stream_component_close(is, is->subtitle_stream);
  1056. avformat_close_input(&is->ic);
  1057. packet_queue_destroy(&is->videoq);
  1058. packet_queue_destroy(&is->audioq);
  1059. packet_queue_destroy(&is->subtitleq);
  1060. /* free all pictures */
  1061. frame_queue_destory(&is->pictq);
  1062. frame_queue_destory(&is->sampq);
  1063. frame_queue_destory(&is->subpq);
  1064. SDL_DestroyCond(is->continue_read_thread);
  1065. sws_freeContext(is->img_convert_ctx);
  1066. sws_freeContext(is->sub_convert_ctx);
  1067. av_free(is->filename);
  1068. if (is->vis_texture)
  1069. SDL_DestroyTexture(is->vis_texture);
  1070. if (is->vid_texture)
  1071. SDL_DestroyTexture(is->vid_texture);
  1072. if (is->sub_texture)
  1073. SDL_DestroyTexture(is->sub_texture);
  1074. av_free(is);
  1075. }
  1076. static void do_exit(VideoState *is)
  1077. {
  1078. if (is) {
  1079. stream_close(is);
  1080. }
  1081. if (renderer)
  1082. SDL_DestroyRenderer(renderer);
  1083. if (window)
  1084. SDL_DestroyWindow(window);
  1085. av_lockmgr_register(NULL);
  1086. uninit_opts();
  1087. #if CONFIG_AVFILTER
  1088. av_freep(&vfilters_list);
  1089. #endif
  1090. avformat_network_deinit();
  1091. if (show_status)
  1092. printf("\n");
  1093. SDL_Quit();
  1094. av_log(NULL, AV_LOG_QUIET, "%s", "");
  1095. exit(0);
  1096. }
  1097. static void sigterm_handler(int sig)
  1098. {
  1099. exit(123);
  1100. }
  1101. static void set_default_window_size(int width, int height, AVRational sar)
  1102. {
  1103. SDL_Rect rect;
  1104. calculate_display_rect(&rect, 0, 0, INT_MAX, height, width, height, sar);
  1105. default_width = rect.w;
  1106. default_height = rect.h;
  1107. }
  1108. static int video_open(VideoState *is)
  1109. {
  1110. int w,h;
  1111. if (screen_width) {
  1112. w = screen_width;
  1113. h = screen_height;
  1114. } else {
  1115. w = default_width;
  1116. h = default_height;
  1117. }
  1118. if (!window) {
  1119. int flags = SDL_WINDOW_SHOWN;
  1120. if (!window_title)
  1121. window_title = input_filename;
  1122. if (is_full_screen)
  1123. flags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
  1124. if (borderless)
  1125. flags |= SDL_WINDOW_BORDERLESS;
  1126. else
  1127. flags |= SDL_WINDOW_RESIZABLE;
  1128. window = SDL_CreateWindow(window_title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, w, h, flags);
  1129. SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear");
  1130. if (window) {
  1131. SDL_RendererInfo info;
  1132. renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
  1133. if (!renderer) {
  1134. av_log(NULL, AV_LOG_WARNING, "Failed to initialize a hardware accelerated renderer: %s\n", SDL_GetError());
  1135. renderer = SDL_CreateRenderer(window, -1, 0);
  1136. }
  1137. if (renderer) {
  1138. if (!SDL_GetRendererInfo(renderer, &info))
  1139. av_log(NULL, AV_LOG_VERBOSE, "Initialized %s renderer.\n", info.name);
  1140. }
  1141. }
  1142. } else {
  1143. SDL_SetWindowSize(window, w, h);
  1144. }
  1145. if (!window || !renderer) {
  1146. av_log(NULL, AV_LOG_FATAL, "SDL: could not set video mode - exiting\n");
  1147. do_exit(is);
  1148. }
  1149. is->width = w;
  1150. is->height = h;
  1151. return 0;
  1152. }
  1153. /* display the current picture, if any */
  1154. static void video_display(VideoState *is)
  1155. {
  1156. if (!window)
  1157. video_open(is);
  1158. SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
  1159. SDL_RenderClear(renderer);
  1160. if (is->audio_st && is->show_mode != SHOW_MODE_VIDEO)
  1161. video_audio_display(is);
  1162. else if (is->video_st)
  1163. video_image_display(is);
  1164. SDL_RenderPresent(renderer);
  1165. }
  1166. static double get_clock(Clock *c)
  1167. {
  1168. if (*c->queue_serial != c->serial)
  1169. return NAN;
  1170. if (c->paused) {
  1171. return c->pts;
  1172. } else {
  1173. double time = av_gettime_relative() / 1000000.0;
  1174. return c->pts_drift + time - (time - c->last_updated) * (1.0 - c->speed);
  1175. }
  1176. }
  1177. static void set_clock_at(Clock *c, double pts, int serial, double time)
  1178. {
  1179. c->pts = pts;
  1180. c->last_updated = time;
  1181. c->pts_drift = c->pts - time;
  1182. c->serial = serial;
  1183. }
  1184. static void set_clock(Clock *c, double pts, int serial)
  1185. {
  1186. double time = av_gettime_relative() / 1000000.0;
  1187. set_clock_at(c, pts, serial, time);
  1188. }
  1189. static void set_clock_speed(Clock *c, double speed)
  1190. {
  1191. set_clock(c, get_clock(c), c->serial);
  1192. c->speed = speed;
  1193. }
  1194. static void init_clock(Clock *c, int *queue_serial)
  1195. {
  1196. c->speed = 1.0;
  1197. c->paused = 0;
  1198. c->queue_serial = queue_serial;
  1199. set_clock(c, NAN, -1);
  1200. }
  1201. static void sync_clock_to_slave(Clock *c, Clock *slave)
  1202. {
  1203. double clock = get_clock(c);
  1204. double slave_clock = get_clock(slave);
  1205. if (!isnan(slave_clock) && (isnan(clock) || fabs(clock - slave_clock) > AV_NOSYNC_THRESHOLD))
  1206. set_clock(c, slave_clock, slave->serial);
  1207. }
  1208. static int get_master_sync_type(VideoState *is) {
  1209. if (is->av_sync_type == AV_SYNC_VIDEO_MASTER) {
  1210. if (is->video_st)
  1211. return AV_SYNC_VIDEO_MASTER;
  1212. else
  1213. return AV_SYNC_AUDIO_MASTER;
  1214. } else if (is->av_sync_type == AV_SYNC_AUDIO_MASTER) {
  1215. if (is->audio_st)
  1216. return AV_SYNC_AUDIO_MASTER;
  1217. else
  1218. return AV_SYNC_EXTERNAL_CLOCK;
  1219. } else {
  1220. return AV_SYNC_EXTERNAL_CLOCK;
  1221. }
  1222. }
  1223. /* get the current master clock value */
  1224. static double get_master_clock(VideoState *is)
  1225. {
  1226. double val;
  1227. switch (get_master_sync_type(is)) {
  1228. case AV_SYNC_VIDEO_MASTER:
  1229. val = get_clock(&is->vidclk);
  1230. break;
  1231. case AV_SYNC_AUDIO_MASTER:
  1232. val = get_clock(&is->audclk);
  1233. break;
  1234. default:
  1235. val = get_clock(&is->extclk);
  1236. break;
  1237. }
  1238. return val;
  1239. }
  1240. static void check_external_clock_speed(VideoState *is) {
  1241. if (is->video_stream >= 0 && is->videoq.nb_packets <= EXTERNAL_CLOCK_MIN_FRAMES ||
  1242. is->audio_stream >= 0 && is->audioq.nb_packets <= EXTERNAL_CLOCK_MIN_FRAMES) {
  1243. set_clock_speed(&is->extclk, FFMAX(EXTERNAL_CLOCK_SPEED_MIN, is->extclk.speed - EXTERNAL_CLOCK_SPEED_STEP));
  1244. } else if ((is->video_stream < 0 || is->videoq.nb_packets > EXTERNAL_CLOCK_MAX_FRAMES) &&
  1245. (is->audio_stream < 0 || is->audioq.nb_packets > EXTERNAL_CLOCK_MAX_FRAMES)) {
  1246. set_clock_speed(&is->extclk, FFMIN(EXTERNAL_CLOCK_SPEED_MAX, is->extclk.speed + EXTERNAL_CLOCK_SPEED_STEP));
  1247. } else {
  1248. double speed = is->extclk.speed;
  1249. if (speed != 1.0)
  1250. set_clock_speed(&is->extclk, speed + EXTERNAL_CLOCK_SPEED_STEP * (1.0 - speed) / fabs(1.0 - speed));
  1251. }
  1252. }
  1253. /* seek in the stream */
  1254. static void stream_seek(VideoState *is, int64_t pos, int64_t rel, int seek_by_bytes)
  1255. {
  1256. if (!is->seek_req) {
  1257. is->seek_pos = pos;
  1258. is->seek_rel = rel;
  1259. is->seek_flags &= ~AVSEEK_FLAG_BYTE;
  1260. if (seek_by_bytes)
  1261. is->seek_flags |= AVSEEK_FLAG_BYTE;
  1262. is->seek_req = 1;
  1263. SDL_CondSignal(is->continue_read_thread);
  1264. }
  1265. }
  1266. /* pause or resume the video */
  1267. static void stream_toggle_pause(VideoState *is)
  1268. {
  1269. if (is->paused) {
  1270. is->frame_timer += av_gettime_relative() / 1000000.0 - is->vidclk.last_updated;
  1271. if (is->read_pause_return != AVERROR(ENOSYS)) {
  1272. is->vidclk.paused = 0;
  1273. }
  1274. set_clock(&is->vidclk, get_clock(&is->vidclk), is->vidclk.serial);
  1275. }
  1276. set_clock(&is->extclk, get_clock(&is->extclk), is->extclk.serial);
  1277. is->paused = is->audclk.paused = is->vidclk.paused = is->extclk.paused = !is->paused;
  1278. }
  1279. static void toggle_pause(VideoState *is)
  1280. {
  1281. stream_toggle_pause(is);
  1282. is->step = 0;
  1283. }
  1284. static void toggle_mute(VideoState *is)
  1285. {
  1286. is->muted = !is->muted;
  1287. }
  1288. static void update_volume(VideoState *is, int sign, double step)
  1289. {
  1290. double volume_level = is->audio_volume ? (20 * log(is->audio_volume / (double)SDL_MIX_MAXVOLUME) / log(10)) : -1000.0;
  1291. int new_volume = lrint(SDL_MIX_MAXVOLUME * pow(10.0, (volume_level + sign * step) / 20.0));
  1292. is->audio_volume = av_clip(is->audio_volume == new_volume ? (is->audio_volume + sign) : new_volume, 0, SDL_MIX_MAXVOLUME);
  1293. }
  1294. static void step_to_next_frame(VideoState *is)
  1295. {
  1296. /* if the stream is paused unpause it, then step */
  1297. if (is->paused)
  1298. stream_toggle_pause(is);
  1299. is->step = 1;
  1300. }
  1301. static double compute_target_delay(double delay, VideoState *is)
  1302. {
  1303. double sync_threshold, diff = 0;
  1304. /* update delay to follow master synchronisation source */
  1305. if (get_master_sync_type(is) != AV_SYNC_VIDEO_MASTER) {
  1306. /* if video is slave, we try to correct big delays by
  1307. duplicating or deleting a frame */
  1308. diff = get_clock(&is->vidclk) - get_master_clock(is);
  1309. /* skip or repeat frame. We take into account the
  1310. delay to compute the threshold. I still don't know
  1311. if it is the best guess */
  1312. sync_threshold = FFMAX(AV_SYNC_THRESHOLD_MIN, FFMIN(AV_SYNC_THRESHOLD_MAX, delay));
  1313. if (!isnan(diff) && fabs(diff) < is->max_frame_duration) {
  1314. if (diff <= -sync_threshold)
  1315. delay = FFMAX(0, delay + diff);
  1316. else if (diff >= sync_threshold && delay > AV_SYNC_FRAMEDUP_THRESHOLD)
  1317. delay = delay + diff;
  1318. else if (diff >= sync_threshold)
  1319. delay = 2 * delay;
  1320. }
  1321. }
  1322. av_log(NULL, AV_LOG_TRACE, "video: delay=%0.3f A-V=%f\n",
  1323. delay, -diff);
  1324. return delay;
  1325. }
  1326. static double vp_duration(VideoState *is, Frame *vp, Frame *nextvp) {
  1327. if (vp->serial == nextvp->serial) {
  1328. double duration = nextvp->pts - vp->pts;
  1329. if (isnan(duration) || duration <= 0 || duration > is->max_frame_duration)
  1330. return vp->duration;
  1331. else
  1332. return duration;
  1333. } else {
  1334. return 0.0;
  1335. }
  1336. }
  1337. static void update_video_pts(VideoState *is, double pts, int64_t pos, int serial) {
  1338. /* update current video pts */
  1339. set_clock(&is->vidclk, pts, serial);
  1340. sync_clock_to_slave(&is->extclk, &is->vidclk);
  1341. }
  1342. /* called to display each frame */
  1343. static void video_refresh(void *opaque, double *remaining_time)
  1344. {
  1345. VideoState *is = opaque;
  1346. double time;
  1347. Frame *sp, *sp2;
  1348. if (!is->paused && get_master_sync_type(is) == AV_SYNC_EXTERNAL_CLOCK && is->realtime)
  1349. check_external_clock_speed(is);
  1350. if (!display_disable && is->show_mode != SHOW_MODE_VIDEO && is->audio_st) {
  1351. time = av_gettime_relative() / 1000000.0;
  1352. if (is->force_refresh || is->last_vis_time + rdftspeed < time) {
  1353. video_display(is);
  1354. is->last_vis_time = time;
  1355. }
  1356. *remaining_time = FFMIN(*remaining_time, is->last_vis_time + rdftspeed - time);
  1357. }
  1358. if (is->video_st) {
  1359. retry:
  1360. if (frame_queue_nb_remaining(&is->pictq) == 0) {
  1361. // nothing to do, no picture to display in the queue
  1362. } else {
  1363. double last_duration, duration, delay;
  1364. Frame *vp, *lastvp;
  1365. /* dequeue the picture */
  1366. lastvp = frame_queue_peek_last(&is->pictq);
  1367. vp = frame_queue_peek(&is->pictq);
  1368. if (vp->serial != is->videoq.serial) {
  1369. frame_queue_next(&is->pictq);
  1370. goto retry;
  1371. }
  1372. if (lastvp->serial != vp->serial)
  1373. is->frame_timer = av_gettime_relative() / 1000000.0;
  1374. if (is->paused)
  1375. goto display;
  1376. /* compute nominal last_duration */
  1377. last_duration = vp_duration(is, lastvp, vp);
  1378. delay = compute_target_delay(last_duration, is);
  1379. time= av_gettime_relative()/1000000.0;
  1380. if (time < is->frame_timer + delay) {
  1381. *remaining_time = FFMIN(is->frame_timer + delay - time, *remaining_time);
  1382. goto display;
  1383. }
  1384. is->frame_timer += delay;
  1385. if (delay > 0 && time - is->frame_timer > AV_SYNC_THRESHOLD_MAX)
  1386. is->frame_timer = time;
  1387. SDL_LockMutex(is->pictq.mutex);
  1388. if (!isnan(vp->pts))
  1389. update_video_pts(is, vp->pts, vp->pos, vp->serial);
  1390. SDL_UnlockMutex(is->pictq.mutex);
  1391. if (frame_queue_nb_remaining(&is->pictq) > 1) {
  1392. Frame *nextvp = frame_queue_peek_next(&is->pictq);
  1393. duration = vp_duration(is, vp, nextvp);
  1394. if(!is->step && (framedrop>0 || (framedrop && get_master_sync_type(is) != AV_SYNC_VIDEO_MASTER)) && time > is->frame_timer + duration){
  1395. is->frame_drops_late++;
  1396. frame_queue_next(&is->pictq);
  1397. goto retry;
  1398. }
  1399. }
  1400. if (is->subtitle_st) {
  1401. while (frame_queue_nb_remaining(&is->subpq) > 0) {
  1402. sp = frame_queue_peek(&is->subpq);
  1403. if (frame_queue_nb_remaining(&is->subpq) > 1)
  1404. sp2 = frame_queue_peek_next(&is->subpq);
  1405. else
  1406. sp2 = NULL;
  1407. if (sp->serial != is->subtitleq.serial
  1408. || (is->vidclk.pts > (sp->pts + ((float) sp->sub.end_display_time / 1000)))
  1409. || (sp2 && is->vidclk.pts > (sp2->pts + ((float) sp2->sub.start_display_time / 1000))))
  1410. {
  1411. if (sp->uploaded) {
  1412. int i;
  1413. for (i = 0; i < sp->sub.num_rects; i++) {
  1414. AVSubtitleRect *sub_rect = sp->sub.rects[i];
  1415. uint8_t *pixels;
  1416. int pitch, j;
  1417. if (!SDL_LockTexture(is->sub_texture, (SDL_Rect *)sub_rect, (void **)&pixels, &pitch)) {
  1418. for (j = 0; j < sub_rect->h; j++, pixels += pitch)
  1419. memset(pixels, 0, sub_rect->w << 2);
  1420. SDL_UnlockTexture(is->sub_texture);
  1421. }
  1422. }
  1423. }
  1424. frame_queue_next(&is->subpq);
  1425. } else {
  1426. break;
  1427. }
  1428. }
  1429. }
  1430. frame_queue_next(&is->pictq);
  1431. is->force_refresh = 1;
  1432. if (is->step && !is->paused)
  1433. stream_toggle_pause(is);
  1434. }
  1435. display:
  1436. /* display picture */
  1437. if (!display_disable && is->force_refresh && is->show_mode == SHOW_MODE_VIDEO && is->pictq.rindex_shown)
  1438. video_display(is);
  1439. }
  1440. is->force_refresh = 0;
  1441. if (show_status) {
  1442. static int64_t last_time;
  1443. int64_t cur_time;
  1444. int aqsize, vqsize, sqsize;
  1445. double av_diff;
  1446. cur_time = av_gettime_relative();
  1447. if (!last_time || (cur_time - last_time) >= 30000) {
  1448. aqsize = 0;
  1449. vqsize = 0;
  1450. sqsize = 0;
  1451. if (is->audio_st)
  1452. aqsize = is->audioq.size;
  1453. if (is->video_st)
  1454. vqsize = is->videoq.size;
  1455. if (is->subtitle_st)
  1456. sqsize = is->subtitleq.size;
  1457. av_diff = 0;
  1458. if (is->audio_st && is->video_st)
  1459. av_diff = get_clock(&is->audclk) - get_clock(&is->vidclk);
  1460. else if (is->video_st)
  1461. av_diff = get_master_clock(is) - get_clock(&is->vidclk);
  1462. else if (is->audio_st)
  1463. av_diff = get_master_clock(is) - get_clock(&is->audclk);
  1464. av_log(NULL, AV_LOG_INFO,
  1465. "%7.2f %s:%7.3f fd=%4d aq=%5dKB vq=%5dKB sq=%5dB f=%"PRId64"/%"PRId64" \r",
  1466. get_master_clock(is),
  1467. (is->audio_st && is->video_st) ? "A-V" : (is->video_st ? "M-V" : (is->audio_st ? "M-A" : " ")),
  1468. av_diff,
  1469. is->frame_drops_early + is->frame_drops_late,
  1470. aqsize / 1024,
  1471. vqsize / 1024,
  1472. sqsize,
  1473. is->video_st ? is->viddec.avctx->pts_correction_num_faulty_dts : 0,
  1474. is->video_st ? is->viddec.avctx->pts_correction_num_faulty_pts : 0);
  1475. fflush(stdout);
  1476. last_time = cur_time;
  1477. }
  1478. }
  1479. }
  1480. static int queue_picture(VideoState *is, AVFrame *src_frame, double pts, double duration, int64_t pos, int serial)
  1481. {
  1482. Frame *vp;
  1483. #if defined(DEBUG_SYNC)
  1484. printf("frame_type=%c pts=%0.3f\n",
  1485. av_get_picture_type_char(src_frame->pict_type), pts);
  1486. #endif
  1487. if (!(vp = frame_queue_peek_writable(&is->pictq)))
  1488. return -1;
  1489. vp->sar = src_frame->sample_aspect_ratio;
  1490. vp->uploaded = 0;
  1491. vp->width = src_frame->width;
  1492. vp->height = src_frame->height;
  1493. vp->format = src_frame->format;
  1494. vp->pts = pts;
  1495. vp->duration = duration;
  1496. vp->pos = pos;
  1497. vp->serial = serial;
  1498. set_default_window_size(vp->width, vp->height, vp->sar);
  1499. av_frame_move_ref(vp->frame, src_frame);
  1500. frame_queue_push(&is->pictq);
  1501. return 0;
  1502. }
  1503. static int get_video_frame(VideoState *is, AVFrame *frame)
  1504. {
  1505. int got_picture;
  1506. if ((got_picture = decoder_decode_frame(&is->viddec, frame, NULL)) < 0)
  1507. return -1;
  1508. if (got_picture) {
  1509. double dpts = NAN;
  1510. if (frame->pts != AV_NOPTS_VALUE)
  1511. dpts = av_q2d(is->video_st->time_base) * frame->pts;
  1512. frame->sample_aspect_ratio = av_guess_sample_aspect_ratio(is->ic, is->video_st, frame);
  1513. if (framedrop>0 || (framedrop && get_master_sync_type(is) != AV_SYNC_VIDEO_MASTER)) {
  1514. if (frame->pts != AV_NOPTS_VALUE) {
  1515. double diff = dpts - get_master_clock(is);
  1516. if (!isnan(diff) && fabs(diff) < AV_NOSYNC_THRESHOLD &&
  1517. diff - is->frame_last_filter_delay < 0 &&
  1518. is->viddec.pkt_serial == is->vidclk.serial &&
  1519. is->videoq.nb_packets) {
  1520. is->frame_drops_early++;
  1521. av_frame_unref(frame);
  1522. got_picture = 0;
  1523. }
  1524. }
  1525. }
  1526. }
  1527. return got_picture;
  1528. }
  1529. #if CONFIG_AVFILTER
  1530. static int configure_filtergraph(AVFilterGraph *graph, const char *filtergraph,
  1531. AVFilterContext *source_ctx, AVFilterContext *sink_ctx)
  1532. {
  1533. int ret, i;
  1534. int nb_filters = graph->nb_filters;
  1535. AVFilterInOut *outputs = NULL, *inputs = NULL;
  1536. if (filtergraph) {
  1537. outputs = avfilter_inout_alloc();
  1538. inputs = avfilter_inout_alloc();
  1539. if (!outputs || !inputs) {
  1540. ret = AVERROR(ENOMEM);
  1541. goto fail;
  1542. }
  1543. outputs->name = av_strdup("in");
  1544. outputs->filter_ctx = source_ctx;
  1545. outputs->pad_idx = 0;
  1546. outputs->next = NULL;
  1547. inputs->name = av_strdup("out");
  1548. inputs->filter_ctx = sink_ctx;
  1549. inputs->pad_idx = 0;
  1550. inputs->next = NULL;
  1551. if ((ret = avfilter_graph_parse_ptr(graph, filtergraph, &inputs, &outputs, NULL)) < 0)
  1552. goto fail;
  1553. } else {
  1554. if ((ret = avfilter_link(source_ctx, 0, sink_ctx, 0)) < 0)
  1555. goto fail;
  1556. }
  1557. /* Reorder the filters to ensure that inputs of the custom filters are merged first */
  1558. for (i = 0; i < graph->nb_filters - nb_filters; i++)
  1559. FFSWAP(AVFilterContext*, graph->filters[i], graph->filters[i + nb_filters]);
  1560. ret = avfilter_graph_config(graph, NULL);
  1561. fail:
  1562. avfilter_inout_free(&outputs);
  1563. avfilter_inout_free(&inputs);
  1564. return ret;
  1565. }
  1566. static int configure_video_filters(AVFilterGraph *graph, VideoState *is, const char *vfilters, AVFrame *frame)
  1567. {
  1568. static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_YUV420P, AV_PIX_FMT_BGRA, AV_PIX_FMT_NONE };
  1569. char sws_flags_str[512] = "";
  1570. char buffersrc_args[256];
  1571. int ret;
  1572. AVFilterContext *filt_src = NULL, *filt_out = NULL, *last_filter = NULL;
  1573. AVCodecParameters *codecpar = is->video_st->codecpar;
  1574. AVRational fr = av_guess_frame_rate(is->ic, is->video_st, NULL);
  1575. AVDictionaryEntry *e = NULL;
  1576. while ((e = av_dict_get(sws_dict, "", e, AV_DICT_IGNORE_SUFFIX))) {
  1577. if (!strcmp(e->key, "sws_flags")) {
  1578. av_strlcatf(sws_flags_str, sizeof(sws_flags_str), "%s=%s:", "flags", e->value);
  1579. } else
  1580. av_strlcatf(sws_flags_str, sizeof(sws_flags_str), "%s=%s:", e->key, e->value);
  1581. }
  1582. if (strlen(sws_flags_str))
  1583. sws_flags_str[strlen(sws_flags_str)-1] = '\0';
  1584. graph->scale_sws_opts = av_strdup(sws_flags_str);
  1585. snprintf(buffersrc_args, sizeof(buffersrc_args),
  1586. "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
  1587. frame->width, frame->height, frame->format,
  1588. is->video_st->time_base.num, is->video_st->time_base.den,
  1589. codecpar->sample_aspect_ratio.num, FFMAX(codecpar->sample_aspect_ratio.den, 1));
  1590. if (fr.num && fr.den)
  1591. av_strlcatf(buffersrc_args, sizeof(buffersrc_args), ":frame_rate=%d/%d", fr.num, fr.den);
  1592. if ((ret = avfilter_graph_create_filter(&filt_src,
  1593. avfilter_get_by_name("buffer"),
  1594. "ffplay_buffer", buffersrc_args, NULL,
  1595. graph)) < 0)
  1596. goto fail;
  1597. ret = avfilter_graph_create_filter(&filt_out,
  1598. avfilter_get_by_name("buffersink"),
  1599. "ffplay_buffersink", NULL, NULL, graph);
  1600. if (ret < 0)
  1601. goto fail;
  1602. if ((ret = av_opt_set_int_list(filt_out, "pix_fmts", pix_fmts, AV_PIX_FMT_NONE, AV_OPT_SEARCH_CHILDREN)) < 0)
  1603. goto fail;
  1604. last_filter = filt_out;
  1605. /* Note: this macro adds a filter before the lastly added filter, so the
  1606. * processing order of the filters is in reverse */
  1607. #define INSERT_FILT(name, arg) do { \
  1608. AVFilterContext *filt_ctx; \
  1609. \
  1610. ret = avfilter_graph_create_filter(&filt_ctx, \
  1611. avfilter_get_by_name(name), \
  1612. "ffplay_" name, arg, NULL, graph); \
  1613. if (ret < 0) \
  1614. goto fail; \
  1615. \
  1616. ret = avfilter_link(filt_ctx, 0, last_filter, 0); \
  1617. if (ret < 0) \
  1618. goto fail; \
  1619. \
  1620. last_filter = filt_ctx; \
  1621. } while (0)
  1622. if (autorotate) {
  1623. double theta = get_rotation(is->video_st);
  1624. if (fabs(theta - 90) < 1.0) {
  1625. INSERT_FILT("transpose", "clock");
  1626. } else if (fabs(theta - 180) < 1.0) {
  1627. INSERT_FILT("hflip", NULL);
  1628. INSERT_FILT("vflip", NULL);
  1629. } else if (fabs(theta - 270) < 1.0) {
  1630. INSERT_FILT("transpose", "cclock");
  1631. } else if (fabs(theta) > 1.0) {
  1632. char rotate_buf[64];
  1633. snprintf(rotate_buf, sizeof(rotate_buf), "%f*PI/180", theta);
  1634. INSERT_FILT("rotate", rotate_buf);
  1635. }
  1636. }
  1637. if ((ret = configure_filtergraph(graph, vfilters, filt_src, last_filter)) < 0)
  1638. goto fail;
  1639. is->in_video_filter = filt_src;
  1640. is->out_video_filter = filt_out;
  1641. fail:
  1642. return ret;
  1643. }
  1644. static int configure_audio_filters(VideoState *is, const char *afilters, int force_output_format)
  1645. {
  1646. static const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE };
  1647. int sample_rates[2] = { 0, -1 };
  1648. int64_t channel_layouts[2] = { 0, -1 };
  1649. int channels[2] = { 0, -1 };
  1650. AVFilterContext *filt_asrc = NULL, *filt_asink = NULL;
  1651. char aresample_swr_opts[512] = "";
  1652. AVDictionaryEntry *e = NULL;
  1653. char asrc_args[256];
  1654. int ret;
  1655. avfilter_graph_free(&is->agraph);
  1656. if (!(is->agraph = avfilter_graph_alloc()))
  1657. return AVERROR(ENOMEM);
  1658. while ((e = av_dict_get(swr_opts, "", e, AV_DICT_IGNORE_SUFFIX)))
  1659. av_strlcatf(aresample_swr_opts, sizeof(aresample_swr_opts), "%s=%s:", e->key, e->value);
  1660. if (strlen(aresample_swr_opts))
  1661. aresample_swr_opts[strlen(aresample_swr_opts)-1] = '\0';
  1662. av_opt_set(is->agraph, "aresample_swr_opts", aresample_swr_opts, 0);
  1663. ret = snprintf(asrc_args, sizeof(asrc_args),
  1664. "sample_rate=%d:sample_fmt=%s:channels=%d:time_base=%d/%d",
  1665. is->audio_filter_src.freq, av_get_sample_fmt_name(is->audio_filter_src.fmt),
  1666. is->audio_filter_src.channels,
  1667. 1, is->audio_filter_src.freq);
  1668. if (is->audio_filter_src.channel_layout)
  1669. snprintf(asrc_args + ret, sizeof(asrc_args) - ret,
  1670. ":channel_layout=0x%"PRIx64, is->audio_filter_src.channel_layout);
  1671. ret = avfilter_graph_create_filter(&filt_asrc,
  1672. avfilter_get_by_name("abuffer"), "ffplay_abuffer",
  1673. asrc_args, NULL, is->agraph);
  1674. if (ret < 0)
  1675. goto end;
  1676. ret = avfilter_graph_create_filter(&filt_asink,
  1677. avfilter_get_by_name("abuffersink"), "ffplay_abuffersink",
  1678. NULL, NULL, is->agraph);
  1679. if (ret < 0)
  1680. goto end;
  1681. if ((ret = av_opt_set_int_list(filt_asink, "sample_fmts", sample_fmts, AV_SAMPLE_FMT_NONE, AV_OPT_SEARCH_CHILDREN)) < 0)
  1682. goto end;
  1683. if ((ret = av_opt_set_int(filt_asink, "all_channel_counts", 1, AV_OPT_SEARCH_CHILDREN)) < 0)
  1684. goto end;
  1685. if (force_output_format) {
  1686. channel_layouts[0] = is->audio_tgt.channel_layout;
  1687. channels [0] = is->audio_tgt.channels;
  1688. sample_rates [0] = is->audio_tgt.freq;
  1689. if ((ret = av_opt_set_int(filt_asink, "all_channel_counts", 0, AV_OPT_SEARCH_CHILDREN)) < 0)
  1690. goto end;
  1691. if ((ret = av_opt_set_int_list(filt_asink, "channel_layouts", channel_layouts, -1, AV_OPT_SEARCH_CHILDREN)) < 0)
  1692. goto end;
  1693. if ((ret = av_opt_set_int_list(filt_asink, "channel_counts" , channels , -1, AV_OPT_SEARCH_CHILDREN)) < 0)
  1694. goto end;
  1695. if ((ret = av_opt_set_int_list(filt_asink, "sample_rates" , sample_rates , -1, AV_OPT_SEARCH_CHILDREN)) < 0)
  1696. goto end;
  1697. }
  1698. if ((ret = configure_filtergraph(is->agraph, afilters, filt_asrc, filt_asink)) < 0)
  1699. goto end;
  1700. is->in_audio_filter = filt_asrc;
  1701. is->out_audio_filter = filt_asink;
  1702. end:
  1703. if (ret < 0)
  1704. avfilter_graph_free(&is->agraph);
  1705. return ret;
  1706. }
  1707. #endif /* CONFIG_AVFILTER */
  1708. static int audio_thread(void *arg)
  1709. {
  1710. VideoState *is = arg;
  1711. AVFrame *frame = av_frame_alloc();
  1712. Frame *af;
  1713. #if CONFIG_AVFILTER
  1714. int last_serial = -1;
  1715. int64_t dec_channel_layout;
  1716. int reconfigure;
  1717. #endif
  1718. int got_frame = 0;
  1719. AVRational tb;
  1720. int ret = 0;
  1721. if (!frame)
  1722. return AVERROR(ENOMEM);
  1723. do {
  1724. if ((got_frame = decoder_decode_frame(&is->auddec, frame, NULL)) < 0)
  1725. goto the_end;
  1726. if (got_frame) {
  1727. tb = (AVRational){1, frame->sample_rate};
  1728. #if CONFIG_AVFILTER
  1729. dec_channel_layout = get_valid_channel_layout(frame->channel_layout, av_frame_get_channels(frame));
  1730. reconfigure =
  1731. cmp_audio_fmts(is->audio_filter_src.fmt, is->audio_filter_src.channels,
  1732. frame->format, av_frame_get_channels(frame)) ||
  1733. is->audio_filter_src.channel_layout != dec_channel_layout ||
  1734. is->audio_filter_src.freq != frame->sample_rate ||
  1735. is->auddec.pkt_serial != last_serial;
  1736. if (reconfigure) {
  1737. char buf1[1024], buf2[1024];
  1738. av_get_channel_layout_string(buf1, sizeof(buf1), -1, is->audio_filter_src.channel_layout);
  1739. av_get_channel_layout_string(buf2, sizeof(buf2), -1, dec_channel_layout);
  1740. av_log(NULL, AV_LOG_DEBUG,
  1741. "Audio frame changed from rate:%d ch:%d fmt:%s layout:%s serial:%d to rate:%d ch:%d fmt:%s layout:%s serial:%d\n",
  1742. is->audio_filter_src.freq, is->audio_filter_src.channels, av_get_sample_fmt_name(is->audio_filter_src.fmt), buf1, last_serial,
  1743. frame->sample_rate, av_frame_get_channels(frame), av_get_sample_fmt_name(frame->format), buf2, is->auddec.pkt_serial);
  1744. is->audio_filter_src.fmt = frame->format;
  1745. is->audio_filter_src.channels = av_frame_get_channels(frame);
  1746. is->audio_filter_src.channel_layout = dec_channel_layout;
  1747. is->audio_filter_src.freq = frame->sample_rate;
  1748. last_serial = is->auddec.pkt_serial;
  1749. if ((ret = configure_audio_filters(is, afilters, 1)) < 0)
  1750. goto the_end;
  1751. }
  1752. if ((ret = av_buffersrc_add_frame(is->in_audio_filter, frame)) < 0)
  1753. goto the_end;
  1754. while ((ret = av_buffersink_get_frame_flags(is->out_audio_filter, frame, 0)) >= 0) {
  1755. tb = av_buffersink_get_time_base(is->out_audio_filter);
  1756. #endif
  1757. if (!(af = frame_queue_peek_writable(&is->sampq)))
  1758. goto the_end;
  1759. af->pts = (frame->pts == AV_NOPTS_VALUE) ? NAN : frame->pts * av_q2d(tb);
  1760. af->pos = av_frame_get_pkt_pos(frame);
  1761. af->serial = is->auddec.pkt_serial;
  1762. af->duration = av_q2d((AVRational){frame->nb_samples, frame->sample_rate});
  1763. av_frame_move_ref(af->frame, frame);
  1764. frame_queue_push(&is->sampq);
  1765. #if CONFIG_AVFILTER
  1766. if (is->audioq.serial != is->auddec.pkt_serial)
  1767. break;
  1768. }
  1769. if (ret == AVERROR_EOF)
  1770. is->auddec.finished = is->auddec.pkt_serial;
  1771. #endif
  1772. }
  1773. } while (ret >= 0 || ret == AVERROR(EAGAIN) || ret == AVERROR_EOF);
  1774. the_end:
  1775. #if CONFIG_AVFILTER
  1776. avfilter_graph_free(&is->agraph);
  1777. #endif
  1778. av_frame_free(&frame);
  1779. return ret;
  1780. }
  1781. static int decoder_start(Decoder *d, int (*fn)(void *), void *arg)
  1782. {
  1783. packet_queue_start(d->queue);
  1784. d->decoder_tid = SDL_CreateThread(fn, "decoder", arg);
  1785. if (!d->decoder_tid) {
  1786. av_log(NULL, AV_LOG_ERROR, "SDL_CreateThread(): %s\n", SDL_GetError());
  1787. return AVERROR(ENOMEM);
  1788. }
  1789. return 0;
  1790. }
  1791. static int video_thread(void *arg)
  1792. {
  1793. VideoState *is = arg;
  1794. AVFrame *frame = av_frame_alloc();
  1795. double pts;
  1796. double duration;
  1797. int ret;
  1798. AVRational tb = is->video_st->time_base;
  1799. AVRational frame_rate = av_guess_frame_rate(is->ic, is->video_st, NULL);
  1800. #if CONFIG_AVFILTER
  1801. AVFilterGraph *graph = avfilter_graph_alloc();
  1802. AVFilterContext *filt_out = NULL, *filt_in = NULL;
  1803. int last_w = 0;
  1804. int last_h = 0;
  1805. enum AVPixelFormat last_format = -2;
  1806. int last_serial = -1;
  1807. int last_vfilter_idx = 0;
  1808. if (!graph) {
  1809. av_frame_free(&frame);
  1810. return AVERROR(ENOMEM);
  1811. }
  1812. #endif
  1813. if (!frame) {
  1814. #if CONFIG_AVFILTER
  1815. avfilter_graph_free(&graph);
  1816. #endif
  1817. return AVERROR(ENOMEM);
  1818. }
  1819. for (;;) {
  1820. ret = get_video_frame(is, frame);
  1821. if (ret < 0)
  1822. goto the_end;
  1823. if (!ret)
  1824. continue;
  1825. #if CONFIG_AVFILTER
  1826. if ( last_w != frame->width
  1827. || last_h != frame->height
  1828. || last_format != frame->format
  1829. || last_serial != is->viddec.pkt_serial
  1830. || last_vfilter_idx != is->vfilter_idx) {
  1831. av_log(NULL, AV_LOG_DEBUG,
  1832. "Video frame changed from size:%dx%d format:%s serial:%d to size:%dx%d format:%s serial:%d\n",
  1833. last_w, last_h,
  1834. (const char *)av_x_if_null(av_get_pix_fmt_name(last_format), "none"), last_serial,
  1835. frame->width, frame->height,
  1836. (const char *)av_x_if_null(av_get_pix_fmt_name(frame->format), "none"), is->viddec.pkt_serial);
  1837. avfilter_graph_free(&graph);
  1838. graph = avfilter_graph_alloc();
  1839. if ((ret = configure_video_filters(graph, is, vfilters_list ? vfilters_list[is->vfilter_idx] : NULL, frame)) < 0) {
  1840. SDL_Event event;
  1841. event.type = FF_QUIT_EVENT;
  1842. event.user.data1 = is;
  1843. SDL_PushEvent(&event);
  1844. goto the_end;
  1845. }
  1846. filt_in = is->in_video_filter;
  1847. filt_out = is->out_video_filter;
  1848. last_w = frame->width;
  1849. last_h = frame->height;
  1850. last_format = frame->format;
  1851. last_serial = is->viddec.pkt_serial;
  1852. last_vfilter_idx = is->vfilter_idx;
  1853. frame_rate = av_buffersink_get_frame_rate(filt_out);
  1854. }
  1855. ret = av_buffersrc_add_frame(filt_in, frame);
  1856. if (ret < 0)
  1857. goto the_end;
  1858. while (ret >= 0) {
  1859. is->frame_last_returned_time = av_gettime_relative() / 1000000.0;
  1860. ret = av_buffersink_get_frame_flags(filt_out, frame, 0);
  1861. if (ret < 0) {
  1862. if (ret == AVERROR_EOF)
  1863. is->viddec.finished = is->viddec.pkt_serial;
  1864. ret = 0;
  1865. break;
  1866. }
  1867. is->frame_last_filter_delay = av_gettime_relative() / 1000000.0 - is->frame_last_returned_time;
  1868. if (fabs(is->frame_last_filter_delay) > AV_NOSYNC_THRESHOLD / 10.0)
  1869. is->frame_last_filter_delay = 0;
  1870. tb = av_buffersink_get_time_base(filt_out);
  1871. #endif
  1872. duration = (frame_rate.num && frame_rate.den ? av_q2d((AVRational){frame_rate.den, frame_rate.num}) : 0);
  1873. pts = (frame->pts == AV_NOPTS_VALUE) ? NAN : frame->pts * av_q2d(tb);
  1874. ret = queue_picture(is, frame, pts, duration, av_frame_get_pkt_pos(frame), is->viddec.pkt_serial);
  1875. av_frame_unref(frame);
  1876. #if CONFIG_AVFILTER
  1877. }
  1878. #endif
  1879. if (ret < 0)
  1880. goto the_end;
  1881. }
  1882. the_end:
  1883. #if CONFIG_AVFILTER
  1884. avfilter_graph_free(&graph);
  1885. #endif
  1886. av_frame_free(&frame);
  1887. return 0;
  1888. }
  1889. static int subtitle_thread(void *arg)
  1890. {
  1891. VideoState *is = arg;
  1892. Frame *sp;
  1893. int got_subtitle;
  1894. double pts;
  1895. for (;;) {
  1896. if (!(sp = frame_queue_peek_writable(&is->subpq)))
  1897. return 0;
  1898. if ((got_subtitle = decoder_decode_frame(&is->subdec, NULL, &sp->sub)) < 0)
  1899. break;
  1900. pts = 0;
  1901. if (got_subtitle && sp->sub.format == 0) {
  1902. if (sp->sub.pts != AV_NOPTS_VALUE)
  1903. pts = sp->sub.pts / (double)AV_TIME_BASE;
  1904. sp->pts = pts;
  1905. sp->serial = is->subdec.pkt_serial;
  1906. sp->width = is->subdec.avctx->width;
  1907. sp->height = is->subdec.avctx->height;
  1908. sp->uploaded = 0;
  1909. /* now we can update the picture count */
  1910. frame_queue_push(&is->subpq);
  1911. } else if (got_subtitle) {
  1912. avsubtitle_free(&sp->sub);
  1913. }
  1914. }
  1915. return 0;
  1916. }
  1917. /* copy samples for viewing in editor window */
  1918. static void update_sample_display(VideoState *is, short *samples, int samples_size)
  1919. {
  1920. int size, len;
  1921. size = samples_size / sizeof(short);
  1922. while (size > 0) {
  1923. len = SAMPLE_ARRAY_SIZE - is->sample_array_index;
  1924. if (len > size)
  1925. len = size;
  1926. memcpy(is->sample_array + is->sample_array_index, samples, len * sizeof(short));
  1927. samples += len;
  1928. is->sample_array_index += len;
  1929. if (is->sample_array_index >= SAMPLE_ARRAY_SIZE)
  1930. is->sample_array_index = 0;
  1931. size -= len;
  1932. }
  1933. }
  1934. /* return the wanted number of samples to get better sync if sync_type is video
  1935. * or external master clock */
  1936. static int synchronize_audio(VideoState *is, int nb_samples)
  1937. {
  1938. int wanted_nb_samples = nb_samples;
  1939. /* if not master, then we try to remove or add samples to correct the clock */
  1940. if (get_master_sync_type(is) != AV_SYNC_AUDIO_MASTER) {
  1941. double diff, avg_diff;
  1942. int min_nb_samples, max_nb_samples;
  1943. diff = get_clock(&is->audclk) - get_master_clock(is);
  1944. if (!isnan(diff) && fabs(diff) < AV_NOSYNC_THRESHOLD) {
  1945. is->audio_diff_cum = diff + is->audio_diff_avg_coef * is->audio_diff_cum;
  1946. if (is->audio_diff_avg_count < AUDIO_DIFF_AVG_NB) {
  1947. /* not enough measures to have a correct estimate */
  1948. is->audio_diff_avg_count++;
  1949. } else {
  1950. /* estimate the A-V difference */
  1951. avg_diff = is->audio_diff_cum * (1.0 - is->audio_diff_avg_coef);
  1952. if (fabs(avg_diff) >= is->audio_diff_threshold) {
  1953. wanted_nb_samples = nb_samples + (int)(diff * is->audio_src.freq);
  1954. min_nb_samples = ((nb_samples * (100 - SAMPLE_CORRECTION_PERCENT_MAX) / 100));
  1955. max_nb_samples = ((nb_samples * (100 + SAMPLE_CORRECTION_PERCENT_MAX) / 100));
  1956. wanted_nb_samples = av_clip(wanted_nb_samples, min_nb_samples, max_nb_samples);
  1957. }
  1958. av_log(NULL, AV_LOG_TRACE, "diff=%f adiff=%f sample_diff=%d apts=%0.3f %f\n",
  1959. diff, avg_diff, wanted_nb_samples - nb_samples,
  1960. is->audio_clock, is->audio_diff_threshold);
  1961. }
  1962. } else {
  1963. /* too big difference : may be initial PTS errors, so
  1964. reset A-V filter */
  1965. is->audio_diff_avg_count = 0;
  1966. is->audio_diff_cum = 0;
  1967. }
  1968. }
  1969. return wanted_nb_samples;
  1970. }
  1971. /**
  1972. * Decode one audio frame and return its uncompressed size.
  1973. *
  1974. * The processed audio frame is decoded, converted if required, and
  1975. * stored in is->audio_buf, with size in bytes given by the return
  1976. * value.
  1977. */
  1978. static int audio_decode_frame(VideoState *is)
  1979. {
  1980. int data_size, resampled_data_size;
  1981. int64_t dec_channel_layout;
  1982. av_unused double audio_clock0;
  1983. int wanted_nb_samples;
  1984. Frame *af;
  1985. if (is->paused)
  1986. return -1;
  1987. do {
  1988. #if defined(_WIN32)
  1989. while (frame_queue_nb_remaining(&is->sampq) == 0) {
  1990. if ((av_gettime_relative() - audio_callback_time) > 1000000LL * is->audio_hw_buf_size / is->audio_tgt.bytes_per_sec / 2)
  1991. return -1;
  1992. av_usleep (1000);
  1993. }
  1994. #endif
  1995. if (!(af = frame_queue_peek_readable(&is->sampq)))
  1996. return -1;
  1997. frame_queue_next(&is->sampq);
  1998. } while (af->serial != is->audioq.serial);
  1999. data_size = av_samples_get_buffer_size(NULL, av_frame_get_channels(af->frame),
  2000. af->frame->nb_samples,
  2001. af->frame->format, 1);
  2002. dec_channel_layout =
  2003. (af->frame->channel_layout && av_frame_get_channels(af->frame) == av_get_channel_layout_nb_channels(af->frame->channel_layout)) ?
  2004. af->frame->channel_layout : av_get_default_channel_layout(av_frame_get_channels(af->frame));
  2005. wanted_nb_samples = synchronize_audio(is, af->frame->nb_samples);
  2006. if (af->frame->format != is->audio_src.fmt ||
  2007. dec_channel_layout != is->audio_src.channel_layout ||
  2008. af->frame->sample_rate != is->audio_src.freq ||
  2009. (wanted_nb_samples != af->frame->nb_samples && !is->swr_ctx)) {
  2010. swr_free(&is->swr_ctx);
  2011. is->swr_ctx = swr_alloc_set_opts(NULL,
  2012. is->audio_tgt.channel_layout, is->audio_tgt.fmt, is->audio_tgt.freq,
  2013. dec_channel_layout, af->frame->format, af->frame->sample_rate,
  2014. 0, NULL);
  2015. if (!is->swr_ctx || swr_init(is->swr_ctx) < 0) {
  2016. av_log(NULL, AV_LOG_ERROR,
  2017. "Cannot create sample rate converter for conversion of %d Hz %s %d channels to %d Hz %s %d channels!\n",
  2018. af->frame->sample_rate, av_get_sample_fmt_name(af->frame->format), av_frame_get_channels(af->frame),
  2019. is->audio_tgt.freq, av_get_sample_fmt_name(is->audio_tgt.fmt), is->audio_tgt.channels);
  2020. swr_free(&is->swr_ctx);
  2021. return -1;
  2022. }
  2023. is->audio_src.channel_layout = dec_channel_layout;
  2024. is->audio_src.channels = av_frame_get_channels(af->frame);
  2025. is->audio_src.freq = af->frame->sample_rate;
  2026. is->audio_src.fmt = af->frame->format;
  2027. }
  2028. if (is->swr_ctx) {
  2029. const uint8_t **in = (const uint8_t **)af->frame->extended_data;
  2030. uint8_t **out = &is->audio_buf1;
  2031. int out_count = (int64_t)wanted_nb_samples * is->audio_tgt.freq / af->frame->sample_rate + 256;
  2032. int out_size = av_samples_get_buffer_size(NULL, is->audio_tgt.channels, out_count, is->audio_tgt.fmt, 0);
  2033. int len2;
  2034. if (out_size < 0) {
  2035. av_log(NULL, AV_LOG_ERROR, "av_samples_get_buffer_size() failed\n");
  2036. return -1;
  2037. }
  2038. if (wanted_nb_samples != af->frame->nb_samples) {
  2039. if (swr_set_compensation(is->swr_ctx, (wanted_nb_samples - af->frame->nb_samples) * is->audio_tgt.freq / af->frame->sample_rate,
  2040. wanted_nb_samples * is->audio_tgt.freq / af->frame->sample_rate) < 0) {
  2041. av_log(NULL, AV_LOG_ERROR, "swr_set_compensation() failed\n");
  2042. return -1;
  2043. }
  2044. }
  2045. av_fast_malloc(&is->audio_buf1, &is->audio_buf1_size, out_size);
  2046. if (!is->audio_buf1)
  2047. return AVERROR(ENOMEM);
  2048. len2 = swr_convert(is->swr_ctx, out, out_count, in, af->frame->nb_samples);
  2049. if (len2 < 0) {
  2050. av_log(NULL, AV_LOG_ERROR, "swr_convert() failed\n");
  2051. return -1;
  2052. }
  2053. if (len2 == out_count) {
  2054. av_log(NULL, AV_LOG_WARNING, "audio buffer is probably too small\n");
  2055. if (swr_init(is->swr_ctx) < 0)
  2056. swr_free(&is->swr_ctx);
  2057. }
  2058. is->audio_buf = is->audio_buf1;
  2059. resampled_data_size = len2 * is->audio_tgt.channels * av_get_bytes_per_sample(is->audio_tgt.fmt);
  2060. } else {
  2061. is->audio_buf = af->frame->data[0];
  2062. resampled_data_size = data_size;
  2063. }
  2064. audio_clock0 = is->audio_clock;
  2065. /* update the audio clock with the pts */
  2066. if (!isnan(af->pts))
  2067. is->audio_clock = af->pts + (double) af->frame->nb_samples / af->frame->sample_rate;
  2068. else
  2069. is->audio_clock = NAN;
  2070. is->audio_clock_serial = af->serial;
  2071. #ifdef DEBUG
  2072. {
  2073. static double last_clock;
  2074. printf("audio: delay=%0.3f clock=%0.3f clock0=%0.3f\n",
  2075. is->audio_clock - last_clock,
  2076. is->audio_clock, audio_clock0);
  2077. last_clock = is->audio_clock;
  2078. }
  2079. #endif
  2080. return resampled_data_size;
  2081. }
  2082. /* prepare a new audio buffer */
  2083. static void sdl_audio_callback(void *opaque, Uint8 *stream, int len)
  2084. {
  2085. VideoState *is = opaque;
  2086. int audio_size, len1;
  2087. audio_callback_time = av_gettime_relative();
  2088. while (len > 0) {
  2089. if (is->audio_buf_index >= is->audio_buf_size) {
  2090. audio_size = audio_decode_frame(is);
  2091. if (audio_size < 0) {
  2092. /* if error, just output silence */
  2093. is->audio_buf = NULL;
  2094. is->audio_buf_size = SDL_AUDIO_MIN_BUFFER_SIZE / is->audio_tgt.frame_size * is->audio_tgt.frame_size;
  2095. } else {
  2096. if (is->show_mode != SHOW_MODE_VIDEO)
  2097. update_sample_display(is, (int16_t *)is->audio_buf, audio_size);
  2098. is->audio_buf_size = audio_size;
  2099. }
  2100. is->audio_buf_index = 0;
  2101. }
  2102. len1 = is->audio_buf_size - is->audio_buf_index;
  2103. if (len1 > len)
  2104. len1 = len;
  2105. if (!is->muted && is->audio_buf && is->audio_volume == SDL_MIX_MAXVOLUME)
  2106. memcpy(stream, (uint8_t *)is->audio_buf + is->audio_buf_index, len1);
  2107. else {
  2108. memset(stream, 0, len1);
  2109. if (!is->muted && is->audio_buf)
  2110. SDL_MixAudio(stream, (uint8_t *)is->audio_buf + is->audio_buf_index, len1, is->audio_volume);
  2111. }
  2112. len -= len1;
  2113. stream += len1;
  2114. is->audio_buf_index += len1;
  2115. }
  2116. is->audio_write_buf_size = is->audio_buf_size - is->audio_buf_index;
  2117. /* Let's assume the audio driver that is used by SDL has two periods. */
  2118. if (!isnan(is->audio_clock)) {
  2119. set_clock_at(&is->audclk, is->audio_clock - (double)(2 * is->audio_hw_buf_size + is->audio_write_buf_size) / is->audio_tgt.bytes_per_sec, is->audio_clock_serial, audio_callback_time / 1000000.0);
  2120. sync_clock_to_slave(&is->extclk, &is->audclk);
  2121. }
  2122. }
  2123. static int audio_open(void *opaque, int64_t wanted_channel_layout, int wanted_nb_channels, int wanted_sample_rate, struct AudioParams *audio_hw_params)
  2124. {
  2125. SDL_AudioSpec wanted_spec, spec;
  2126. const char *env;
  2127. static const int next_nb_channels[] = {0, 0, 1, 6, 2, 6, 4, 6};
  2128. static const int next_sample_rates[] = {0, 44100, 48000, 96000, 192000};
  2129. int next_sample_rate_idx = FF_ARRAY_ELEMS(next_sample_rates) - 1;
  2130. env = SDL_getenv("SDL_AUDIO_CHANNELS");
  2131. if (env) {
  2132. wanted_nb_channels = atoi(env);
  2133. wanted_channel_layout = av_get_default_channel_layout(wanted_nb_channels);
  2134. }
  2135. if (!wanted_channel_layout || wanted_nb_channels != av_get_channel_layout_nb_channels(wanted_channel_layout)) {
  2136. wanted_channel_layout = av_get_default_channel_layout(wanted_nb_channels);
  2137. wanted_channel_layout &= ~AV_CH_LAYOUT_STEREO_DOWNMIX;
  2138. }
  2139. wanted_nb_channels = av_get_channel_layout_nb_channels(wanted_channel_layout);
  2140. wanted_spec.channels = wanted_nb_channels;
  2141. wanted_spec.freq = wanted_sample_rate;
  2142. if (wanted_spec.freq <= 0 || wanted_spec.channels <= 0) {
  2143. av_log(NULL, AV_LOG_ERROR, "Invalid sample rate or channel count!\n");
  2144. return -1;
  2145. }
  2146. while (next_sample_rate_idx && next_sample_rates[next_sample_rate_idx] >= wanted_spec.freq)
  2147. next_sample_rate_idx--;
  2148. wanted_spec.format = AUDIO_S16SYS;
  2149. wanted_spec.silence = 0;
  2150. wanted_spec.samples = FFMAX(SDL_AUDIO_MIN_BUFFER_SIZE, 2 << av_log2(wanted_spec.freq / SDL_AUDIO_MAX_CALLBACKS_PER_SEC));
  2151. wanted_spec.callback = sdl_audio_callback;
  2152. wanted_spec.userdata = opaque;
  2153. while (SDL_OpenAudio(&wanted_spec, &spec) < 0) {
  2154. av_log(NULL, AV_LOG_WARNING, "SDL_OpenAudio (%d channels, %d Hz): %s\n",
  2155. wanted_spec.channels, wanted_spec.freq, SDL_GetError());
  2156. wanted_spec.channels = next_nb_channels[FFMIN(7, wanted_spec.channels)];
  2157. if (!wanted_spec.channels) {
  2158. wanted_spec.freq = next_sample_rates[next_sample_rate_idx--];
  2159. wanted_spec.channels = wanted_nb_channels;
  2160. if (!wanted_spec.freq) {
  2161. av_log(NULL, AV_LOG_ERROR,
  2162. "No more combinations to try, audio open failed\n");
  2163. return -1;
  2164. }
  2165. }
  2166. wanted_channel_layout = av_get_default_channel_layout(wanted_spec.channels);
  2167. }
  2168. if (spec.format != AUDIO_S16SYS) {
  2169. av_log(NULL, AV_LOG_ERROR,
  2170. "SDL advised audio format %d is not supported!\n", spec.format);
  2171. return -1;
  2172. }
  2173. if (spec.channels != wanted_spec.channels) {
  2174. wanted_channel_layout = av_get_default_channel_layout(spec.channels);
  2175. if (!wanted_channel_layout) {
  2176. av_log(NULL, AV_LOG_ERROR,
  2177. "SDL advised channel count %d is not supported!\n", spec.channels);
  2178. return -1;
  2179. }
  2180. }
  2181. audio_hw_params->fmt = AV_SAMPLE_FMT_S16;
  2182. audio_hw_params->freq = spec.freq;
  2183. audio_hw_params->channel_layout = wanted_channel_layout;
  2184. audio_hw_params->channels = spec.channels;
  2185. audio_hw_params->frame_size = av_samples_get_buffer_size(NULL, audio_hw_params->channels, 1, audio_hw_params->fmt, 1);
  2186. audio_hw_params->bytes_per_sec = av_samples_get_buffer_size(NULL, audio_hw_params->channels, audio_hw_params->freq, audio_hw_params->fmt, 1);
  2187. if (audio_hw_params->bytes_per_sec <= 0 || audio_hw_params->frame_size <= 0) {
  2188. av_log(NULL, AV_LOG_ERROR, "av_samples_get_buffer_size failed\n");
  2189. return -1;
  2190. }
  2191. return spec.size;
  2192. }
  2193. /* open a given stream. Return 0 if OK */
  2194. static int stream_component_open(VideoState *is, int stream_index)
  2195. {
  2196. AVFormatContext *ic = is->ic;
  2197. AVCodecContext *avctx;
  2198. AVCodec *codec;
  2199. const char *forced_codec_name = NULL;
  2200. AVDictionary *opts = NULL;
  2201. AVDictionaryEntry *t = NULL;
  2202. int sample_rate, nb_channels;
  2203. int64_t channel_layout;
  2204. int ret = 0;
  2205. int stream_lowres = lowres;
  2206. if (stream_index < 0 || stream_index >= ic->nb_streams)
  2207. return -1;
  2208. avctx = avcodec_alloc_context3(NULL);
  2209. if (!avctx)
  2210. return AVERROR(ENOMEM);
  2211. ret = avcodec_parameters_to_context(avctx, ic->streams[stream_index]->codecpar);
  2212. if (ret < 0)
  2213. goto fail;
  2214. av_codec_set_pkt_timebase(avctx, ic->streams[stream_index]->time_base);
  2215. codec = avcodec_find_decoder(avctx->codec_id);
  2216. switch(avctx->codec_type){
  2217. case AVMEDIA_TYPE_AUDIO : is->last_audio_stream = stream_index; forced_codec_name = audio_codec_name; break;
  2218. case AVMEDIA_TYPE_SUBTITLE: is->last_subtitle_stream = stream_index; forced_codec_name = subtitle_codec_name; break;
  2219. case AVMEDIA_TYPE_VIDEO : is->last_video_stream = stream_index; forced_codec_name = video_codec_name; break;
  2220. }
  2221. if (forced_codec_name)
  2222. codec = avcodec_find_decoder_by_name(forced_codec_name);
  2223. if (!codec) {
  2224. if (forced_codec_name) av_log(NULL, AV_LOG_WARNING,
  2225. "No codec could be found with name '%s'\n", forced_codec_name);
  2226. else av_log(NULL, AV_LOG_WARNING,
  2227. "No codec could be found with id %d\n", avctx->codec_id);
  2228. ret = AVERROR(EINVAL);
  2229. goto fail;
  2230. }
  2231. avctx->codec_id = codec->id;
  2232. if(stream_lowres > av_codec_get_max_lowres(codec)){
  2233. av_log(avctx, AV_LOG_WARNING, "The maximum value for lowres supported by the decoder is %d\n",
  2234. av_codec_get_max_lowres(codec));
  2235. stream_lowres = av_codec_get_max_lowres(codec);
  2236. }
  2237. av_codec_set_lowres(avctx, stream_lowres);
  2238. #if FF_API_EMU_EDGE
  2239. if(stream_lowres) avctx->flags |= CODEC_FLAG_EMU_EDGE;
  2240. #endif
  2241. if (fast)
  2242. avctx->flags2 |= AV_CODEC_FLAG2_FAST;
  2243. #if FF_API_EMU_EDGE
  2244. if(codec->capabilities & AV_CODEC_CAP_DR1)
  2245. avctx->flags |= CODEC_FLAG_EMU_EDGE;
  2246. #endif
  2247. opts = filter_codec_opts(codec_opts, avctx->codec_id, ic, ic->streams[stream_index], codec);
  2248. if (!av_dict_get(opts, "threads", NULL, 0))
  2249. av_dict_set(&opts, "threads", "auto", 0);
  2250. if (stream_lowres)
  2251. av_dict_set_int(&opts, "lowres", stream_lowres, 0);
  2252. if (avctx->codec_type == AVMEDIA_TYPE_VIDEO || avctx->codec_type == AVMEDIA_TYPE_AUDIO)
  2253. av_dict_set(&opts, "refcounted_frames", "1", 0);
  2254. if ((ret = avcodec_open2(avctx, codec, &opts)) < 0) {
  2255. goto fail;
  2256. }
  2257. if ((t = av_dict_get(opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
  2258. av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
  2259. ret = AVERROR_OPTION_NOT_FOUND;
  2260. goto fail;
  2261. }
  2262. is->eof = 0;
  2263. ic->streams[stream_index]->discard = AVDISCARD_DEFAULT;
  2264. switch (avctx->codec_type) {
  2265. case AVMEDIA_TYPE_AUDIO:
  2266. #if CONFIG_AVFILTER
  2267. {
  2268. AVFilterContext *sink;
  2269. is->audio_filter_src.freq = avctx->sample_rate;
  2270. is->audio_filter_src.channels = avctx->channels;
  2271. is->audio_filter_src.channel_layout = get_valid_channel_layout(avctx->channel_layout, avctx->channels);
  2272. is->audio_filter_src.fmt = avctx->sample_fmt;
  2273. if ((ret = configure_audio_filters(is, afilters, 0)) < 0)
  2274. goto fail;
  2275. sink = is->out_audio_filter;
  2276. sample_rate = av_buffersink_get_sample_rate(sink);
  2277. nb_channels = av_buffersink_get_channels(sink);
  2278. channel_layout = av_buffersink_get_channel_layout(sink);
  2279. }
  2280. #else
  2281. sample_rate = avctx->sample_rate;
  2282. nb_channels = avctx->channels;
  2283. channel_layout = avctx->channel_layout;
  2284. #endif
  2285. /* prepare audio output */
  2286. if ((ret = audio_open(is, channel_layout, nb_channels, sample_rate, &is->audio_tgt)) < 0)
  2287. goto fail;
  2288. is->audio_hw_buf_size = ret;
  2289. is->audio_src = is->audio_tgt;
  2290. is->audio_buf_size = 0;
  2291. is->audio_buf_index = 0;
  2292. /* init averaging filter */
  2293. is->audio_diff_avg_coef = exp(log(0.01) / AUDIO_DIFF_AVG_NB);
  2294. is->audio_diff_avg_count = 0;
  2295. /* since we do not have a precise anough audio FIFO fullness,
  2296. we correct audio sync only if larger than this threshold */
  2297. is->audio_diff_threshold = (double)(is->audio_hw_buf_size) / is->audio_tgt.bytes_per_sec;
  2298. is->audio_stream = stream_index;
  2299. is->audio_st = ic->streams[stream_index];
  2300. decoder_init(&is->auddec, avctx, &is->audioq, is->continue_read_thread);
  2301. if ((is->ic->iformat->flags & (AVFMT_NOBINSEARCH | AVFMT_NOGENSEARCH | AVFMT_NO_BYTE_SEEK)) && !is->ic->iformat->read_seek) {
  2302. is->auddec.start_pts = is->audio_st->start_time;
  2303. is->auddec.start_pts_tb = is->audio_st->time_base;
  2304. }
  2305. if ((ret = decoder_start(&is->auddec, audio_thread, is)) < 0)
  2306. goto out;
  2307. SDL_PauseAudio(0);
  2308. break;
  2309. case AVMEDIA_TYPE_VIDEO:
  2310. is->video_stream = stream_index;
  2311. is->video_st = ic->streams[stream_index];
  2312. decoder_init(&is->viddec, avctx, &is->videoq, is->continue_read_thread);
  2313. if ((ret = decoder_start(&is->viddec, video_thread, is)) < 0)
  2314. goto out;
  2315. is->queue_attachments_req = 1;
  2316. break;
  2317. case AVMEDIA_TYPE_SUBTITLE:
  2318. is->subtitle_stream = stream_index;
  2319. is->subtitle_st = ic->streams[stream_index];
  2320. decoder_init(&is->subdec, avctx, &is->subtitleq, is->continue_read_thread);
  2321. if ((ret = decoder_start(&is->subdec, subtitle_thread, is)) < 0)
  2322. goto out;
  2323. break;
  2324. default:
  2325. break;
  2326. }
  2327. goto out;
  2328. fail:
  2329. avcodec_free_context(&avctx);
  2330. out:
  2331. av_dict_free(&opts);
  2332. return ret;
  2333. }
  2334. static int decode_interrupt_cb(void *ctx)
  2335. {
  2336. VideoState *is = ctx;
  2337. return is->abort_request;
  2338. }
  2339. static int stream_has_enough_packets(AVStream *st, int stream_id, PacketQueue *queue) {
  2340. return stream_id < 0 ||
  2341. queue->abort_request ||
  2342. (st->disposition & AV_DISPOSITION_ATTACHED_PIC) ||
  2343. queue->nb_packets > MIN_FRAMES && (!queue->duration || av_q2d(st->time_base) * queue->duration > 1.0);
  2344. }
  2345. static int is_realtime(AVFormatContext *s)
  2346. {
  2347. if( !strcmp(s->iformat->name, "rtp")
  2348. || !strcmp(s->iformat->name, "rtsp")
  2349. || !strcmp(s->iformat->name, "sdp")
  2350. )
  2351. return 1;
  2352. if(s->pb && ( !strncmp(s->filename, "rtp:", 4)
  2353. || !strncmp(s->filename, "udp:", 4)
  2354. )
  2355. )
  2356. return 1;
  2357. return 0;
  2358. }
  2359. /* this thread gets the stream from the disk or the network */
  2360. static int read_thread(void *arg)
  2361. {
  2362. VideoState *is = arg;
  2363. AVFormatContext *ic = NULL;
  2364. int err, i, ret;
  2365. int st_index[AVMEDIA_TYPE_NB];
  2366. AVPacket pkt1, *pkt = &pkt1;
  2367. int64_t stream_start_time;
  2368. int pkt_in_play_range = 0;
  2369. AVDictionaryEntry *t;
  2370. AVDictionary **opts;
  2371. int orig_nb_streams;
  2372. SDL_mutex *wait_mutex = SDL_CreateMutex();
  2373. int scan_all_pmts_set = 0;
  2374. int64_t pkt_ts;
  2375. if (!wait_mutex) {
  2376. av_log(NULL, AV_LOG_FATAL, "SDL_CreateMutex(): %s\n", SDL_GetError());
  2377. ret = AVERROR(ENOMEM);
  2378. goto fail;
  2379. }
  2380. memset(st_index, -1, sizeof(st_index));
  2381. is->last_video_stream = is->video_stream = -1;
  2382. is->last_audio_stream = is->audio_stream = -1;
  2383. is->last_subtitle_stream = is->subtitle_stream = -1;
  2384. is->eof = 0;
  2385. ic = avformat_alloc_context();
  2386. if (!ic) {
  2387. av_log(NULL, AV_LOG_FATAL, "Could not allocate context.\n");
  2388. ret = AVERROR(ENOMEM);
  2389. goto fail;
  2390. }
  2391. ic->interrupt_callback.callback = decode_interrupt_cb;
  2392. ic->interrupt_callback.opaque = is;
  2393. if (!av_dict_get(format_opts, "scan_all_pmts", NULL, AV_DICT_MATCH_CASE)) {
  2394. av_dict_set(&format_opts, "scan_all_pmts", "1", AV_DICT_DONT_OVERWRITE);
  2395. scan_all_pmts_set = 1;
  2396. }
  2397. err = avformat_open_input(&ic, is->filename, is->iformat, &format_opts);
  2398. if (err < 0) {
  2399. print_error(is->filename, err);
  2400. ret = -1;
  2401. goto fail;
  2402. }
  2403. if (scan_all_pmts_set)
  2404. av_dict_set(&format_opts, "scan_all_pmts", NULL, AV_DICT_MATCH_CASE);
  2405. if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
  2406. av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
  2407. ret = AVERROR_OPTION_NOT_FOUND;
  2408. goto fail;
  2409. }
  2410. is->ic = ic;
  2411. if (genpts)
  2412. ic->flags |= AVFMT_FLAG_GENPTS;
  2413. av_format_inject_global_side_data(ic);
  2414. opts = setup_find_stream_info_opts(ic, codec_opts);
  2415. orig_nb_streams = ic->nb_streams;
  2416. err = avformat_find_stream_info(ic, opts);
  2417. for (i = 0; i < orig_nb_streams; i++)
  2418. av_dict_free(&opts[i]);
  2419. av_freep(&opts);
  2420. if (err < 0) {
  2421. av_log(NULL, AV_LOG_WARNING,
  2422. "%s: could not find codec parameters\n", is->filename);
  2423. ret = -1;
  2424. goto fail;
  2425. }
  2426. if (ic->pb)
  2427. ic->pb->eof_reached = 0; // FIXME hack, ffplay maybe should not use avio_feof() to test for the end
  2428. if (seek_by_bytes < 0)
  2429. seek_by_bytes = !!(ic->iformat->flags & AVFMT_TS_DISCONT) && strcmp("ogg", ic->iformat->name);
  2430. is->max_frame_duration = (ic->iformat->flags & AVFMT_TS_DISCONT) ? 10.0 : 3600.0;
  2431. if (!window_title && (t = av_dict_get(ic->metadata, "title", NULL, 0)))
  2432. window_title = av_asprintf("%s - %s", t->value, input_filename);
  2433. /* if seeking requested, we execute it */
  2434. if (start_time != AV_NOPTS_VALUE) {
  2435. int64_t timestamp;
  2436. timestamp = start_time;
  2437. /* add the stream start time */
  2438. if (ic->start_time != AV_NOPTS_VALUE)
  2439. timestamp += ic->start_time;
  2440. ret = avformat_seek_file(ic, -1, INT64_MIN, timestamp, INT64_MAX, 0);
  2441. if (ret < 0) {
  2442. av_log(NULL, AV_LOG_WARNING, "%s: could not seek to position %0.3f\n",
  2443. is->filename, (double)timestamp / AV_TIME_BASE);
  2444. }
  2445. }
  2446. is->realtime = is_realtime(ic);
  2447. if (show_status)
  2448. av_dump_format(ic, 0, is->filename, 0);
  2449. for (i = 0; i < ic->nb_streams; i++) {
  2450. AVStream *st = ic->streams[i];
  2451. enum AVMediaType type = st->codecpar->codec_type;
  2452. st->discard = AVDISCARD_ALL;
  2453. if (type >= 0 && wanted_stream_spec[type] && st_index[type] == -1)
  2454. if (avformat_match_stream_specifier(ic, st, wanted_stream_spec[type]) > 0)
  2455. st_index[type] = i;
  2456. }
  2457. for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
  2458. if (wanted_stream_spec[i] && st_index[i] == -1) {
  2459. av_log(NULL, AV_LOG_ERROR, "Stream specifier %s does not match any %s stream\n", wanted_stream_spec[i], av_get_media_type_string(i));
  2460. st_index[i] = INT_MAX;
  2461. }
  2462. }
  2463. if (!video_disable)
  2464. st_index[AVMEDIA_TYPE_VIDEO] =
  2465. av_find_best_stream(ic, AVMEDIA_TYPE_VIDEO,
  2466. st_index[AVMEDIA_TYPE_VIDEO], -1, NULL, 0);
  2467. if (!audio_disable)
  2468. st_index[AVMEDIA_TYPE_AUDIO] =
  2469. av_find_best_stream(ic, AVMEDIA_TYPE_AUDIO,
  2470. st_index[AVMEDIA_TYPE_AUDIO],
  2471. st_index[AVMEDIA_TYPE_VIDEO],
  2472. NULL, 0);
  2473. if (!video_disable && !subtitle_disable)
  2474. st_index[AVMEDIA_TYPE_SUBTITLE] =
  2475. av_find_best_stream(ic, AVMEDIA_TYPE_SUBTITLE,
  2476. st_index[AVMEDIA_TYPE_SUBTITLE],
  2477. (st_index[AVMEDIA_TYPE_AUDIO] >= 0 ?
  2478. st_index[AVMEDIA_TYPE_AUDIO] :
  2479. st_index[AVMEDIA_TYPE_VIDEO]),
  2480. NULL, 0);
  2481. is->show_mode = show_mode;
  2482. if (st_index[AVMEDIA_TYPE_VIDEO] >= 0) {
  2483. AVStream *st = ic->streams[st_index[AVMEDIA_TYPE_VIDEO]];
  2484. AVCodecParameters *codecpar = st->codecpar;
  2485. AVRational sar = av_guess_sample_aspect_ratio(ic, st, NULL);
  2486. if (codecpar->width)
  2487. set_default_window_size(codecpar->width, codecpar->height, sar);
  2488. }
  2489. /* open the streams */
  2490. if (st_index[AVMEDIA_TYPE_AUDIO] >= 0) {
  2491. stream_component_open(is, st_index[AVMEDIA_TYPE_AUDIO]);
  2492. }
  2493. ret = -1;
  2494. if (st_index[AVMEDIA_TYPE_VIDEO] >= 0) {
  2495. ret = stream_component_open(is, st_index[AVMEDIA_TYPE_VIDEO]);
  2496. }
  2497. if (is->show_mode == SHOW_MODE_NONE)
  2498. is->show_mode = ret >= 0 ? SHOW_MODE_VIDEO : SHOW_MODE_RDFT;
  2499. if (st_index[AVMEDIA_TYPE_SUBTITLE] >= 0) {
  2500. stream_component_open(is, st_index[AVMEDIA_TYPE_SUBTITLE]);
  2501. }
  2502. if (is->video_stream < 0 && is->audio_stream < 0) {
  2503. av_log(NULL, AV_LOG_FATAL, "Failed to open file '%s' or configure filtergraph\n",
  2504. is->filename);
  2505. ret = -1;
  2506. goto fail;
  2507. }
  2508. if (infinite_buffer < 0 && is->realtime)
  2509. infinite_buffer = 1;
  2510. for (;;) {
  2511. if (is->abort_request)
  2512. break;
  2513. if (is->paused != is->last_paused) {
  2514. is->last_paused = is->paused;
  2515. if (is->paused)
  2516. is->read_pause_return = av_read_pause(ic);
  2517. else
  2518. av_read_play(ic);
  2519. }
  2520. #if CONFIG_RTSP_DEMUXER || CONFIG_MMSH_PROTOCOL
  2521. if (is->paused &&
  2522. (!strcmp(ic->iformat->name, "rtsp") ||
  2523. (ic->pb && !strncmp(input_filename, "mmsh:", 5)))) {
  2524. /* wait 10 ms to avoid trying to get another packet */
  2525. /* XXX: horrible */
  2526. SDL_Delay(10);
  2527. continue;
  2528. }
  2529. #endif
  2530. if (is->seek_req) {
  2531. int64_t seek_target = is->seek_pos;
  2532. int64_t seek_min = is->seek_rel > 0 ? seek_target - is->seek_rel + 2: INT64_MIN;
  2533. int64_t seek_max = is->seek_rel < 0 ? seek_target - is->seek_rel - 2: INT64_MAX;
  2534. // FIXME the +-2 is due to rounding being not done in the correct direction in generation
  2535. // of the seek_pos/seek_rel variables
  2536. ret = avformat_seek_file(is->ic, -1, seek_min, seek_target, seek_max, is->seek_flags);
  2537. if (ret < 0) {
  2538. av_log(NULL, AV_LOG_ERROR,
  2539. "%s: error while seeking\n", is->ic->filename);
  2540. } else {
  2541. if (is->audio_stream >= 0) {
  2542. packet_queue_flush(&is->audioq);
  2543. packet_queue_put(&is->audioq, &flush_pkt);
  2544. }
  2545. if (is->subtitle_stream >= 0) {
  2546. packet_queue_flush(&is->subtitleq);
  2547. packet_queue_put(&is->subtitleq, &flush_pkt);
  2548. }
  2549. if (is->video_stream >= 0) {
  2550. packet_queue_flush(&is->videoq);
  2551. packet_queue_put(&is->videoq, &flush_pkt);
  2552. }
  2553. if (is->seek_flags & AVSEEK_FLAG_BYTE) {
  2554. set_clock(&is->extclk, NAN, 0);
  2555. } else {
  2556. set_clock(&is->extclk, seek_target / (double)AV_TIME_BASE, 0);
  2557. }
  2558. }
  2559. is->seek_req = 0;
  2560. is->queue_attachments_req = 1;
  2561. is->eof = 0;
  2562. if (is->paused)
  2563. step_to_next_frame(is);
  2564. }
  2565. if (is->queue_attachments_req) {
  2566. if (is->video_st && is->video_st->disposition & AV_DISPOSITION_ATTACHED_PIC) {
  2567. AVPacket copy;
  2568. if ((ret = av_copy_packet(&copy, &is->video_st->attached_pic)) < 0)
  2569. goto fail;
  2570. packet_queue_put(&is->videoq, &copy);
  2571. packet_queue_put_nullpacket(&is->videoq, is->video_stream);
  2572. }
  2573. is->queue_attachments_req = 0;
  2574. }
  2575. /* if the queue are full, no need to read more */
  2576. if (infinite_buffer<1 &&
  2577. (is->audioq.size + is->videoq.size + is->subtitleq.size > MAX_QUEUE_SIZE
  2578. || (stream_has_enough_packets(is->audio_st, is->audio_stream, &is->audioq) &&
  2579. stream_has_enough_packets(is->video_st, is->video_stream, &is->videoq) &&
  2580. stream_has_enough_packets(is->subtitle_st, is->subtitle_stream, &is->subtitleq)))) {
  2581. /* wait 10 ms */
  2582. SDL_LockMutex(wait_mutex);
  2583. SDL_CondWaitTimeout(is->continue_read_thread, wait_mutex, 10);
  2584. SDL_UnlockMutex(wait_mutex);
  2585. continue;
  2586. }
  2587. if (!is->paused &&
  2588. (!is->audio_st || (is->auddec.finished == is->audioq.serial && frame_queue_nb_remaining(&is->sampq) == 0)) &&
  2589. (!is->video_st || (is->viddec.finished == is->videoq.serial && frame_queue_nb_remaining(&is->pictq) == 0))) {
  2590. if (loop != 1 && (!loop || --loop)) {
  2591. stream_seek(is, start_time != AV_NOPTS_VALUE ? start_time : 0, 0, 0);
  2592. } else if (autoexit) {
  2593. ret = AVERROR_EOF;
  2594. goto fail;
  2595. }
  2596. }
  2597. ret = av_read_frame(ic, pkt);
  2598. if (ret < 0) {
  2599. if ((ret == AVERROR_EOF || avio_feof(ic->pb)) && !is->eof) {
  2600. if (is->video_stream >= 0)
  2601. packet_queue_put_nullpacket(&is->videoq, is->video_stream);
  2602. if (is->audio_stream >= 0)
  2603. packet_queue_put_nullpacket(&is->audioq, is->audio_stream);
  2604. if (is->subtitle_stream >= 0)
  2605. packet_queue_put_nullpacket(&is->subtitleq, is->subtitle_stream);
  2606. is->eof = 1;
  2607. }
  2608. if (ic->pb && ic->pb->error)
  2609. break;
  2610. SDL_LockMutex(wait_mutex);
  2611. SDL_CondWaitTimeout(is->continue_read_thread, wait_mutex, 10);
  2612. SDL_UnlockMutex(wait_mutex);
  2613. continue;
  2614. } else {
  2615. is->eof = 0;
  2616. }
  2617. /* check if packet is in play range specified by user, then queue, otherwise discard */
  2618. stream_start_time = ic->streams[pkt->stream_index]->start_time;
  2619. pkt_ts = pkt->pts == AV_NOPTS_VALUE ? pkt->dts : pkt->pts;
  2620. pkt_in_play_range = duration == AV_NOPTS_VALUE ||
  2621. (pkt_ts - (stream_start_time != AV_NOPTS_VALUE ? stream_start_time : 0)) *
  2622. av_q2d(ic->streams[pkt->stream_index]->time_base) -
  2623. (double)(start_time != AV_NOPTS_VALUE ? start_time : 0) / 1000000
  2624. <= ((double)duration / 1000000);
  2625. if (pkt->stream_index == is->audio_stream && pkt_in_play_range) {
  2626. packet_queue_put(&is->audioq, pkt);
  2627. } else if (pkt->stream_index == is->video_stream && pkt_in_play_range
  2628. && !(is->video_st->disposition & AV_DISPOSITION_ATTACHED_PIC)) {
  2629. packet_queue_put(&is->videoq, pkt);
  2630. } else if (pkt->stream_index == is->subtitle_stream && pkt_in_play_range) {
  2631. packet_queue_put(&is->subtitleq, pkt);
  2632. } else {
  2633. av_packet_unref(pkt);
  2634. }
  2635. }
  2636. ret = 0;
  2637. fail:
  2638. if (ic && !is->ic)
  2639. avformat_close_input(&ic);
  2640. if (ret != 0) {
  2641. SDL_Event event;
  2642. event.type = FF_QUIT_EVENT;
  2643. event.user.data1 = is;
  2644. SDL_PushEvent(&event);
  2645. }
  2646. SDL_DestroyMutex(wait_mutex);
  2647. return 0;
  2648. }
  2649. static VideoState *stream_open(const char *filename, AVInputFormat *iformat)
  2650. {
  2651. VideoState *is;
  2652. is = av_mallocz(sizeof(VideoState));
  2653. if (!is)
  2654. return NULL;
  2655. is->filename = av_strdup(filename);
  2656. if (!is->filename)
  2657. goto fail;
  2658. is->iformat = iformat;
  2659. is->ytop = 0;
  2660. is->xleft = 0;
  2661. /* start video display */
  2662. if (frame_queue_init(&is->pictq, &is->videoq, VIDEO_PICTURE_QUEUE_SIZE, 1) < 0)
  2663. goto fail;
  2664. if (frame_queue_init(&is->subpq, &is->subtitleq, SUBPICTURE_QUEUE_SIZE, 0) < 0)
  2665. goto fail;
  2666. if (frame_queue_init(&is->sampq, &is->audioq, SAMPLE_QUEUE_SIZE, 1) < 0)
  2667. goto fail;
  2668. if (packet_queue_init(&is->videoq) < 0 ||
  2669. packet_queue_init(&is->audioq) < 0 ||
  2670. packet_queue_init(&is->subtitleq) < 0)
  2671. goto fail;
  2672. if (!(is->continue_read_thread = SDL_CreateCond())) {
  2673. av_log(NULL, AV_LOG_FATAL, "SDL_CreateCond(): %s\n", SDL_GetError());
  2674. goto fail;
  2675. }
  2676. init_clock(&is->vidclk, &is->videoq.serial);
  2677. init_clock(&is->audclk, &is->audioq.serial);
  2678. init_clock(&is->extclk, &is->extclk.serial);
  2679. is->audio_clock_serial = -1;
  2680. if (startup_volume < 0)
  2681. av_log(NULL, AV_LOG_WARNING, "-volume=%d < 0, setting to 0\n", startup_volume);
  2682. if (startup_volume > 100)
  2683. av_log(NULL, AV_LOG_WARNING, "-volume=%d > 100, setting to 100\n", startup_volume);
  2684. startup_volume = av_clip(startup_volume, 0, 100);
  2685. startup_volume = av_clip(SDL_MIX_MAXVOLUME * startup_volume / 100, 0, SDL_MIX_MAXVOLUME);
  2686. is->audio_volume = startup_volume;
  2687. is->muted = 0;
  2688. is->av_sync_type = av_sync_type;
  2689. is->read_tid = SDL_CreateThread(read_thread, "read_thread", is);
  2690. if (!is->read_tid) {
  2691. av_log(NULL, AV_LOG_FATAL, "SDL_CreateThread(): %s\n", SDL_GetError());
  2692. fail:
  2693. stream_close(is);
  2694. return NULL;
  2695. }
  2696. return is;
  2697. }
  2698. static void stream_cycle_channel(VideoState *is, int codec_type)
  2699. {
  2700. AVFormatContext *ic = is->ic;
  2701. int start_index, stream_index;
  2702. int old_index;
  2703. AVStream *st;
  2704. AVProgram *p = NULL;
  2705. int nb_streams = is->ic->nb_streams;
  2706. if (codec_type == AVMEDIA_TYPE_VIDEO) {
  2707. start_index = is->last_video_stream;
  2708. old_index = is->video_stream;
  2709. } else if (codec_type == AVMEDIA_TYPE_AUDIO) {
  2710. start_index = is->last_audio_stream;
  2711. old_index = is->audio_stream;
  2712. } else {
  2713. start_index = is->last_subtitle_stream;
  2714. old_index = is->subtitle_stream;
  2715. }
  2716. stream_index = start_index;
  2717. if (codec_type != AVMEDIA_TYPE_VIDEO && is->video_stream != -1) {
  2718. p = av_find_program_from_stream(ic, NULL, is->video_stream);
  2719. if (p) {
  2720. nb_streams = p->nb_stream_indexes;
  2721. for (start_index = 0; start_index < nb_streams; start_index++)
  2722. if (p->stream_index[start_index] == stream_index)
  2723. break;
  2724. if (start_index == nb_streams)
  2725. start_index = -1;
  2726. stream_index = start_index;
  2727. }
  2728. }
  2729. for (;;) {
  2730. if (++stream_index >= nb_streams)
  2731. {
  2732. if (codec_type == AVMEDIA_TYPE_SUBTITLE)
  2733. {
  2734. stream_index = -1;
  2735. is->last_subtitle_stream = -1;
  2736. goto the_end;
  2737. }
  2738. if (start_index == -1)
  2739. return;
  2740. stream_index = 0;
  2741. }
  2742. if (stream_index == start_index)
  2743. return;
  2744. st = is->ic->streams[p ? p->stream_index[stream_index] : stream_index];
  2745. if (st->codecpar->codec_type == codec_type) {
  2746. /* check that parameters are OK */
  2747. switch (codec_type) {
  2748. case AVMEDIA_TYPE_AUDIO:
  2749. if (st->codecpar->sample_rate != 0 &&
  2750. st->codecpar->channels != 0)
  2751. goto the_end;
  2752. break;
  2753. case AVMEDIA_TYPE_VIDEO:
  2754. case AVMEDIA_TYPE_SUBTITLE:
  2755. goto the_end;
  2756. default:
  2757. break;
  2758. }
  2759. }
  2760. }
  2761. the_end:
  2762. if (p && stream_index != -1)
  2763. stream_index = p->stream_index[stream_index];
  2764. av_log(NULL, AV_LOG_INFO, "Switch %s stream from #%d to #%d\n",
  2765. av_get_media_type_string(codec_type),
  2766. old_index,
  2767. stream_index);
  2768. stream_component_close(is, old_index);
  2769. stream_component_open(is, stream_index);
  2770. }
  2771. static void toggle_full_screen(VideoState *is)
  2772. {
  2773. is_full_screen = !is_full_screen;
  2774. SDL_SetWindowFullscreen(window, is_full_screen ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0);
  2775. }
  2776. static void toggle_audio_display(VideoState *is)
  2777. {
  2778. int next = is->show_mode;
  2779. do {
  2780. next = (next + 1) % SHOW_MODE_NB;
  2781. } while (next != is->show_mode && (next == SHOW_MODE_VIDEO && !is->video_st || next != SHOW_MODE_VIDEO && !is->audio_st));
  2782. if (is->show_mode != next) {
  2783. is->force_refresh = 1;
  2784. is->show_mode = next;
  2785. }
  2786. }
  2787. static void refresh_loop_wait_event(VideoState *is, SDL_Event *event) {
  2788. double remaining_time = 0.0;
  2789. SDL_PumpEvents();
  2790. while (!SDL_PeepEvents(event, 1, SDL_GETEVENT, SDL_FIRSTEVENT, SDL_LASTEVENT)) {
  2791. if (!cursor_hidden && av_gettime_relative() - cursor_last_shown > CURSOR_HIDE_DELAY) {
  2792. SDL_ShowCursor(0);
  2793. cursor_hidden = 1;
  2794. }
  2795. if (remaining_time > 0.0)
  2796. av_usleep((int64_t)(remaining_time * 1000000.0));
  2797. remaining_time = REFRESH_RATE;
  2798. if (is->show_mode != SHOW_MODE_NONE && (!is->paused || is->force_refresh))
  2799. video_refresh(is, &remaining_time);
  2800. SDL_PumpEvents();
  2801. }
  2802. }
  2803. static void seek_chapter(VideoState *is, int incr)
  2804. {
  2805. int64_t pos = get_master_clock(is) * AV_TIME_BASE;
  2806. int i;
  2807. if (!is->ic->nb_chapters)
  2808. return;
  2809. /* find the current chapter */
  2810. for (i = 0; i < is->ic->nb_chapters; i++) {
  2811. AVChapter *ch = is->ic->chapters[i];
  2812. if (av_compare_ts(pos, AV_TIME_BASE_Q, ch->start, ch->time_base) < 0) {
  2813. i--;
  2814. break;
  2815. }
  2816. }
  2817. i += incr;
  2818. i = FFMAX(i, 0);
  2819. if (i >= is->ic->nb_chapters)
  2820. return;
  2821. av_log(NULL, AV_LOG_VERBOSE, "Seeking to chapter %d.\n", i);
  2822. stream_seek(is, av_rescale_q(is->ic->chapters[i]->start, is->ic->chapters[i]->time_base,
  2823. AV_TIME_BASE_Q), 0, 0);
  2824. }
  2825. /* handle an event sent by the GUI */
  2826. static void event_loop(VideoState *cur_stream)
  2827. {
  2828. SDL_Event event;
  2829. double incr, pos, frac;
  2830. for (;;) {
  2831. double x;
  2832. refresh_loop_wait_event(cur_stream, &event);
  2833. switch (event.type) {
  2834. case SDL_KEYDOWN:
  2835. if (exit_on_keydown) {
  2836. do_exit(cur_stream);
  2837. break;
  2838. }
  2839. switch (event.key.keysym.sym) {
  2840. case SDLK_ESCAPE:
  2841. case SDLK_q:
  2842. do_exit(cur_stream);
  2843. break;
  2844. case SDLK_f:
  2845. toggle_full_screen(cur_stream);
  2846. cur_stream->force_refresh = 1;
  2847. break;
  2848. case SDLK_p:
  2849. case SDLK_SPACE:
  2850. toggle_pause(cur_stream);
  2851. break;
  2852. case SDLK_m:
  2853. toggle_mute(cur_stream);
  2854. break;
  2855. case SDLK_KP_MULTIPLY:
  2856. case SDLK_0:
  2857. update_volume(cur_stream, 1, SDL_VOLUME_STEP);
  2858. break;
  2859. case SDLK_KP_DIVIDE:
  2860. case SDLK_9:
  2861. update_volume(cur_stream, -1, SDL_VOLUME_STEP);
  2862. break;
  2863. case SDLK_s: // S: Step to next frame
  2864. step_to_next_frame(cur_stream);
  2865. break;
  2866. case SDLK_a:
  2867. stream_cycle_channel(cur_stream, AVMEDIA_TYPE_AUDIO);
  2868. break;
  2869. case SDLK_v:
  2870. stream_cycle_channel(cur_stream, AVMEDIA_TYPE_VIDEO);
  2871. break;
  2872. case SDLK_c:
  2873. stream_cycle_channel(cur_stream, AVMEDIA_TYPE_VIDEO);
  2874. stream_cycle_channel(cur_stream, AVMEDIA_TYPE_AUDIO);
  2875. stream_cycle_channel(cur_stream, AVMEDIA_TYPE_SUBTITLE);
  2876. break;
  2877. case SDLK_t:
  2878. stream_cycle_channel(cur_stream, AVMEDIA_TYPE_SUBTITLE);
  2879. break;
  2880. case SDLK_w:
  2881. #if CONFIG_AVFILTER
  2882. if (cur_stream->show_mode == SHOW_MODE_VIDEO && cur_stream->vfilter_idx < nb_vfilters - 1) {
  2883. if (++cur_stream->vfilter_idx >= nb_vfilters)
  2884. cur_stream->vfilter_idx = 0;
  2885. } else {
  2886. cur_stream->vfilter_idx = 0;
  2887. toggle_audio_display(cur_stream);
  2888. }
  2889. #else
  2890. toggle_audio_display(cur_stream);
  2891. #endif
  2892. break;
  2893. case SDLK_PAGEUP:
  2894. if (cur_stream->ic->nb_chapters <= 1) {
  2895. incr = 600.0;
  2896. goto do_seek;
  2897. }
  2898. seek_chapter(cur_stream, 1);
  2899. break;
  2900. case SDLK_PAGEDOWN:
  2901. if (cur_stream->ic->nb_chapters <= 1) {
  2902. incr = -600.0;
  2903. goto do_seek;
  2904. }
  2905. seek_chapter(cur_stream, -1);
  2906. break;
  2907. case SDLK_LEFT:
  2908. incr = -10.0;
  2909. goto do_seek;
  2910. case SDLK_RIGHT:
  2911. incr = 10.0;
  2912. goto do_seek;
  2913. case SDLK_UP:
  2914. incr = 60.0;
  2915. goto do_seek;
  2916. case SDLK_DOWN:
  2917. incr = -60.0;
  2918. do_seek:
  2919. if (seek_by_bytes) {
  2920. pos = -1;
  2921. if (pos < 0 && cur_stream->video_stream >= 0)
  2922. pos = frame_queue_last_pos(&cur_stream->pictq);
  2923. if (pos < 0 && cur_stream->audio_stream >= 0)
  2924. pos = frame_queue_last_pos(&cur_stream->sampq);
  2925. if (pos < 0)
  2926. pos = avio_tell(cur_stream->ic->pb);
  2927. if (cur_stream->ic->bit_rate)
  2928. incr *= cur_stream->ic->bit_rate / 8.0;
  2929. else
  2930. incr *= 180000.0;
  2931. pos += incr;
  2932. stream_seek(cur_stream, pos, incr, 1);
  2933. } else {
  2934. pos = get_master_clock(cur_stream);
  2935. if (isnan(pos))
  2936. pos = (double)cur_stream->seek_pos / AV_TIME_BASE;
  2937. pos += incr;
  2938. if (cur_stream->ic->start_time != AV_NOPTS_VALUE && pos < cur_stream->ic->start_time / (double)AV_TIME_BASE)
  2939. pos = cur_stream->ic->start_time / (double)AV_TIME_BASE;
  2940. stream_seek(cur_stream, (int64_t)(pos * AV_TIME_BASE), (int64_t)(incr * AV_TIME_BASE), 0);
  2941. }
  2942. break;
  2943. default:
  2944. break;
  2945. }
  2946. break;
  2947. case SDL_MOUSEBUTTONDOWN:
  2948. if (exit_on_mousedown) {
  2949. do_exit(cur_stream);
  2950. break;
  2951. }
  2952. if (event.button.button == SDL_BUTTON_LEFT) {
  2953. static int64_t last_mouse_left_click = 0;
  2954. if (av_gettime_relative() - last_mouse_left_click <= 500000) {
  2955. toggle_full_screen(cur_stream);
  2956. cur_stream->force_refresh = 1;
  2957. last_mouse_left_click = 0;
  2958. } else {
  2959. last_mouse_left_click = av_gettime_relative();
  2960. }
  2961. }
  2962. case SDL_MOUSEMOTION:
  2963. if (cursor_hidden) {
  2964. SDL_ShowCursor(1);
  2965. cursor_hidden = 0;
  2966. }
  2967. cursor_last_shown = av_gettime_relative();
  2968. if (event.type == SDL_MOUSEBUTTONDOWN) {
  2969. if (event.button.button != SDL_BUTTON_RIGHT)
  2970. break;
  2971. x = event.button.x;
  2972. } else {
  2973. if (!(event.motion.state & SDL_BUTTON_RMASK))
  2974. break;
  2975. x = event.motion.x;
  2976. }
  2977. if (seek_by_bytes || cur_stream->ic->duration <= 0) {
  2978. uint64_t size = avio_size(cur_stream->ic->pb);
  2979. stream_seek(cur_stream, size*x/cur_stream->width, 0, 1);
  2980. } else {
  2981. int64_t ts;
  2982. int ns, hh, mm, ss;
  2983. int tns, thh, tmm, tss;
  2984. tns = cur_stream->ic->duration / 1000000LL;
  2985. thh = tns / 3600;
  2986. tmm = (tns % 3600) / 60;
  2987. tss = (tns % 60);
  2988. frac = x / cur_stream->width;
  2989. ns = frac * tns;
  2990. hh = ns / 3600;
  2991. mm = (ns % 3600) / 60;
  2992. ss = (ns % 60);
  2993. av_log(NULL, AV_LOG_INFO,
  2994. "Seek to %2.0f%% (%2d:%02d:%02d) of total duration (%2d:%02d:%02d) \n", frac*100,
  2995. hh, mm, ss, thh, tmm, tss);
  2996. ts = frac * cur_stream->ic->duration;
  2997. if (cur_stream->ic->start_time != AV_NOPTS_VALUE)
  2998. ts += cur_stream->ic->start_time;
  2999. stream_seek(cur_stream, ts, 0, 0);
  3000. }
  3001. break;
  3002. case SDL_WINDOWEVENT:
  3003. switch (event.window.event) {
  3004. case SDL_WINDOWEVENT_RESIZED:
  3005. screen_width = cur_stream->width = event.window.data1;
  3006. screen_height = cur_stream->height = event.window.data2;
  3007. if (cur_stream->vis_texture) {
  3008. SDL_DestroyTexture(cur_stream->vis_texture);
  3009. cur_stream->vis_texture = NULL;
  3010. }
  3011. case SDL_WINDOWEVENT_EXPOSED:
  3012. cur_stream->force_refresh = 1;
  3013. }
  3014. break;
  3015. case SDL_QUIT:
  3016. case FF_QUIT_EVENT:
  3017. do_exit(cur_stream);
  3018. break;
  3019. default:
  3020. break;
  3021. }
  3022. }
  3023. }
  3024. static int opt_frame_size(void *optctx, const char *opt, const char *arg)
  3025. {
  3026. av_log(NULL, AV_LOG_WARNING, "Option -s is deprecated, use -video_size.\n");
  3027. return opt_default(NULL, "video_size", arg);
  3028. }
  3029. static int opt_width(void *optctx, const char *opt, const char *arg)
  3030. {
  3031. screen_width = parse_number_or_die(opt, arg, OPT_INT64, 1, INT_MAX);
  3032. return 0;
  3033. }
  3034. static int opt_height(void *optctx, const char *opt, const char *arg)
  3035. {
  3036. screen_height = parse_number_or_die(opt, arg, OPT_INT64, 1, INT_MAX);
  3037. return 0;
  3038. }
  3039. static int opt_format(void *optctx, const char *opt, const char *arg)
  3040. {
  3041. file_iformat = av_find_input_format(arg);
  3042. if (!file_iformat) {
  3043. av_log(NULL, AV_LOG_FATAL, "Unknown input format: %s\n", arg);
  3044. return AVERROR(EINVAL);
  3045. }
  3046. return 0;
  3047. }
  3048. static int opt_frame_pix_fmt(void *optctx, const char *opt, const char *arg)
  3049. {
  3050. av_log(NULL, AV_LOG_WARNING, "Option -pix_fmt is deprecated, use -pixel_format.\n");
  3051. return opt_default(NULL, "pixel_format", arg);
  3052. }
  3053. static int opt_sync(void *optctx, const char *opt, const char *arg)
  3054. {
  3055. if (!strcmp(arg, "audio"))
  3056. av_sync_type = AV_SYNC_AUDIO_MASTER;
  3057. else if (!strcmp(arg, "video"))
  3058. av_sync_type = AV_SYNC_VIDEO_MASTER;
  3059. else if (!strcmp(arg, "ext"))
  3060. av_sync_type = AV_SYNC_EXTERNAL_CLOCK;
  3061. else {
  3062. av_log(NULL, AV_LOG_ERROR, "Unknown value for %s: %s\n", opt, arg);
  3063. exit(1);
  3064. }
  3065. return 0;
  3066. }
  3067. static int opt_seek(void *optctx, const char *opt, const char *arg)
  3068. {
  3069. start_time = parse_time_or_die(opt, arg, 1);
  3070. return 0;
  3071. }
  3072. static int opt_duration(void *optctx, const char *opt, const char *arg)
  3073. {
  3074. duration = parse_time_or_die(opt, arg, 1);
  3075. return 0;
  3076. }
  3077. static int opt_show_mode(void *optctx, const char *opt, const char *arg)
  3078. {
  3079. show_mode = !strcmp(arg, "video") ? SHOW_MODE_VIDEO :
  3080. !strcmp(arg, "waves") ? SHOW_MODE_WAVES :
  3081. !strcmp(arg, "rdft" ) ? SHOW_MODE_RDFT :
  3082. parse_number_or_die(opt, arg, OPT_INT, 0, SHOW_MODE_NB-1);
  3083. return 0;
  3084. }
  3085. static void opt_input_file(void *optctx, const char *filename)
  3086. {
  3087. if (input_filename) {
  3088. av_log(NULL, AV_LOG_FATAL,
  3089. "Argument '%s' provided as input filename, but '%s' was already specified.\n",
  3090. filename, input_filename);
  3091. exit(1);
  3092. }
  3093. if (!strcmp(filename, "-"))
  3094. filename = "pipe:";
  3095. input_filename = filename;
  3096. }
  3097. static int opt_codec(void *optctx, const char *opt, const char *arg)
  3098. {
  3099. const char *spec = strchr(opt, ':');
  3100. if (!spec) {
  3101. av_log(NULL, AV_LOG_ERROR,
  3102. "No media specifier was specified in '%s' in option '%s'\n",
  3103. arg, opt);
  3104. return AVERROR(EINVAL);
  3105. }
  3106. spec++;
  3107. switch (spec[0]) {
  3108. case 'a' : audio_codec_name = arg; break;
  3109. case 's' : subtitle_codec_name = arg; break;
  3110. case 'v' : video_codec_name = arg; break;
  3111. default:
  3112. av_log(NULL, AV_LOG_ERROR,
  3113. "Invalid media specifier '%s' in option '%s'\n", spec, opt);
  3114. return AVERROR(EINVAL);
  3115. }
  3116. return 0;
  3117. }
  3118. static int dummy;
  3119. static const OptionDef options[] = {
  3120. #include "cmdutils_common_opts.h"
  3121. { "x", HAS_ARG, { .func_arg = opt_width }, "force displayed width", "width" },
  3122. { "y", HAS_ARG, { .func_arg = opt_height }, "force displayed height", "height" },
  3123. { "s", HAS_ARG | OPT_VIDEO, { .func_arg = opt_frame_size }, "set frame size (WxH or abbreviation)", "size" },
  3124. { "fs", OPT_BOOL, { &is_full_screen }, "force full screen" },
  3125. { "an", OPT_BOOL, { &audio_disable }, "disable audio" },
  3126. { "vn", OPT_BOOL, { &video_disable }, "disable video" },
  3127. { "sn", OPT_BOOL, { &subtitle_disable }, "disable subtitling" },
  3128. { "ast", OPT_STRING | HAS_ARG | OPT_EXPERT, { &wanted_stream_spec[AVMEDIA_TYPE_AUDIO] }, "select desired audio stream", "stream_specifier" },
  3129. { "vst", OPT_STRING | HAS_ARG | OPT_EXPERT, { &wanted_stream_spec[AVMEDIA_TYPE_VIDEO] }, "select desired video stream", "stream_specifier" },
  3130. { "sst", OPT_STRING | HAS_ARG | OPT_EXPERT, { &wanted_stream_spec[AVMEDIA_TYPE_SUBTITLE] }, "select desired subtitle stream", "stream_specifier" },
  3131. { "ss", HAS_ARG, { .func_arg = opt_seek }, "seek to a given position in seconds", "pos" },
  3132. { "t", HAS_ARG, { .func_arg = opt_duration }, "play \"duration\" seconds of audio/video", "duration" },
  3133. { "bytes", OPT_INT | HAS_ARG, { &seek_by_bytes }, "seek by bytes 0=off 1=on -1=auto", "val" },
  3134. { "nodisp", OPT_BOOL, { &display_disable }, "disable graphical display" },
  3135. { "noborder", OPT_BOOL, { &borderless }, "borderless window" },
  3136. { "volume", OPT_INT | HAS_ARG, { &startup_volume}, "set startup volume 0=min 100=max", "volume" },
  3137. { "f", HAS_ARG, { .func_arg = opt_format }, "force format", "fmt" },
  3138. { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO, { .func_arg = opt_frame_pix_fmt }, "set pixel format", "format" },
  3139. { "stats", OPT_BOOL | OPT_EXPERT, { &show_status }, "show status", "" },
  3140. { "fast", OPT_BOOL | OPT_EXPERT, { &fast }, "non spec compliant optimizations", "" },
  3141. { "genpts", OPT_BOOL | OPT_EXPERT, { &genpts }, "generate pts", "" },
  3142. { "drp", OPT_INT | HAS_ARG | OPT_EXPERT, { &decoder_reorder_pts }, "let decoder reorder pts 0=off 1=on -1=auto", ""},
  3143. { "lowres", OPT_INT | HAS_ARG | OPT_EXPERT, { &lowres }, "", "" },
  3144. { "sync", HAS_ARG | OPT_EXPERT, { .func_arg = opt_sync }, "set audio-video sync. type (type=audio/video/ext)", "type" },
  3145. { "autoexit", OPT_BOOL | OPT_EXPERT, { &autoexit }, "exit at the end", "" },
  3146. { "exitonkeydown", OPT_BOOL | OPT_EXPERT, { &exit_on_keydown }, "exit on key down", "" },
  3147. { "exitonmousedown", OPT_BOOL | OPT_EXPERT, { &exit_on_mousedown }, "exit on mouse down", "" },
  3148. { "loop", OPT_INT | HAS_ARG | OPT_EXPERT, { &loop }, "set number of times the playback shall be looped", "loop count" },
  3149. { "framedrop", OPT_BOOL | OPT_EXPERT, { &framedrop }, "drop frames when cpu is too slow", "" },
  3150. { "infbuf", OPT_BOOL | OPT_EXPERT, { &infinite_buffer }, "don't limit the input buffer size (useful with realtime streams)", "" },
  3151. { "window_title", OPT_STRING | HAS_ARG, { &window_title }, "set window title", "window title" },
  3152. #if CONFIG_AVFILTER
  3153. { "vf", OPT_EXPERT | HAS_ARG, { .func_arg = opt_add_vfilter }, "set video filters", "filter_graph" },
  3154. { "af", OPT_STRING | HAS_ARG, { &afilters }, "set audio filters", "filter_graph" },
  3155. #endif
  3156. { "rdftspeed", OPT_INT | HAS_ARG| OPT_AUDIO | OPT_EXPERT, { &rdftspeed }, "rdft speed", "msecs" },
  3157. { "showmode", HAS_ARG, { .func_arg = opt_show_mode}, "select show mode (0 = video, 1 = waves, 2 = RDFT)", "mode" },
  3158. { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, { .func_arg = opt_default }, "generic catch all option", "" },
  3159. { "i", OPT_BOOL, { &dummy}, "read specified file", "input_file"},
  3160. { "codec", HAS_ARG, { .func_arg = opt_codec}, "force decoder", "decoder_name" },
  3161. { "acodec", HAS_ARG | OPT_STRING | OPT_EXPERT, { &audio_codec_name }, "force audio decoder", "decoder_name" },
  3162. { "scodec", HAS_ARG | OPT_STRING | OPT_EXPERT, { &subtitle_codec_name }, "force subtitle decoder", "decoder_name" },
  3163. { "vcodec", HAS_ARG | OPT_STRING | OPT_EXPERT, { &video_codec_name }, "force video decoder", "decoder_name" },
  3164. { "autorotate", OPT_BOOL, { &autorotate }, "automatically rotate video", "" },
  3165. { NULL, },
  3166. };
  3167. static void show_usage(void)
  3168. {
  3169. av_log(NULL, AV_LOG_INFO, "Simple media player\n");
  3170. av_log(NULL, AV_LOG_INFO, "usage: %s [options] input_file\n", program_name);
  3171. av_log(NULL, AV_LOG_INFO, "\n");
  3172. }
  3173. void show_help_default(const char *opt, const char *arg)
  3174. {
  3175. av_log_set_callback(log_callback_help);
  3176. show_usage();
  3177. show_help_options(options, "Main options:", 0, OPT_EXPERT, 0);
  3178. show_help_options(options, "Advanced options:", OPT_EXPERT, 0, 0);
  3179. printf("\n");
  3180. show_help_children(avcodec_get_class(), AV_OPT_FLAG_DECODING_PARAM);
  3181. show_help_children(avformat_get_class(), AV_OPT_FLAG_DECODING_PARAM);
  3182. #if !CONFIG_AVFILTER
  3183. show_help_children(sws_get_class(), AV_OPT_FLAG_ENCODING_PARAM);
  3184. #else
  3185. show_help_children(avfilter_get_class(), AV_OPT_FLAG_FILTERING_PARAM);
  3186. #endif
  3187. printf("\nWhile playing:\n"
  3188. "q, ESC quit\n"
  3189. "f toggle full screen\n"
  3190. "p, SPC pause\n"
  3191. "m toggle mute\n"
  3192. "9, 0 decrease and increase volume respectively\n"
  3193. "/, * decrease and increase volume respectively\n"
  3194. "a cycle audio channel in the current program\n"
  3195. "v cycle video channel\n"
  3196. "t cycle subtitle channel in the current program\n"
  3197. "c cycle program\n"
  3198. "w cycle video filters or show modes\n"
  3199. "s activate frame-step mode\n"
  3200. "left/right seek backward/forward 10 seconds\n"
  3201. "down/up seek backward/forward 1 minute\n"
  3202. "page down/page up seek backward/forward 10 minutes\n"
  3203. "right mouse click seek to percentage in file corresponding to fraction of width\n"
  3204. "left double-click toggle full screen\n"
  3205. );
  3206. }
  3207. static int lockmgr(void **mtx, enum AVLockOp op)
  3208. {
  3209. switch(op) {
  3210. case AV_LOCK_CREATE:
  3211. *mtx = SDL_CreateMutex();
  3212. if(!*mtx) {
  3213. av_log(NULL, AV_LOG_FATAL, "SDL_CreateMutex(): %s\n", SDL_GetError());
  3214. return 1;
  3215. }
  3216. return 0;
  3217. case AV_LOCK_OBTAIN:
  3218. return !!SDL_LockMutex(*mtx);
  3219. case AV_LOCK_RELEASE:
  3220. return !!SDL_UnlockMutex(*mtx);
  3221. case AV_LOCK_DESTROY:
  3222. SDL_DestroyMutex(*mtx);
  3223. return 0;
  3224. }
  3225. return 1;
  3226. }
  3227. /* Called from the main */
  3228. int main(int argc, char **argv)
  3229. {
  3230. int flags;
  3231. VideoState *is;
  3232. init_dynload();
  3233. av_log_set_flags(AV_LOG_SKIP_REPEATED);
  3234. parse_loglevel(argc, argv, options);
  3235. /* register all codecs, demux and protocols */
  3236. #if CONFIG_AVDEVICE
  3237. avdevice_register_all();
  3238. #endif
  3239. #if CONFIG_AVFILTER
  3240. avfilter_register_all();
  3241. #endif
  3242. av_register_all();
  3243. avformat_network_init();
  3244. init_opts();
  3245. signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
  3246. signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
  3247. show_banner(argc, argv, options);
  3248. parse_options(NULL, argc, argv, options, opt_input_file);
  3249. if (!input_filename) {
  3250. show_usage();
  3251. av_log(NULL, AV_LOG_FATAL, "An input file must be specified\n");
  3252. av_log(NULL, AV_LOG_FATAL,
  3253. "Use -h to get full help or, even better, run 'man %s'\n", program_name);
  3254. exit(1);
  3255. }
  3256. if (display_disable) {
  3257. video_disable = 1;
  3258. }
  3259. flags = SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER;
  3260. if (audio_disable)
  3261. flags &= ~SDL_INIT_AUDIO;
  3262. else {
  3263. /* Try to work around an occasional ALSA buffer underflow issue when the
  3264. * period size is NPOT due to ALSA resampling by forcing the buffer size. */
  3265. if (!SDL_getenv("SDL_AUDIO_ALSA_SET_BUFFER_SIZE"))
  3266. SDL_setenv("SDL_AUDIO_ALSA_SET_BUFFER_SIZE","1", 1);
  3267. }
  3268. if (display_disable)
  3269. flags &= ~SDL_INIT_VIDEO;
  3270. if (SDL_Init (flags)) {
  3271. av_log(NULL, AV_LOG_FATAL, "Could not initialize SDL - %s\n", SDL_GetError());
  3272. av_log(NULL, AV_LOG_FATAL, "(Did you set the DISPLAY variable?)\n");
  3273. exit(1);
  3274. }
  3275. SDL_EventState(SDL_SYSWMEVENT, SDL_IGNORE);
  3276. SDL_EventState(SDL_USEREVENT, SDL_IGNORE);
  3277. if (av_lockmgr_register(lockmgr)) {
  3278. av_log(NULL, AV_LOG_FATAL, "Could not initialize lock manager!\n");
  3279. do_exit(NULL);
  3280. }
  3281. av_init_packet(&flush_pkt);
  3282. flush_pkt.data = (uint8_t *)&flush_pkt;
  3283. is = stream_open(input_filename, file_iformat);
  3284. if (!is) {
  3285. av_log(NULL, AV_LOG_FATAL, "Failed to initialize VideoState!\n");
  3286. do_exit(NULL);
  3287. }
  3288. event_loop(is);
  3289. /* never returns */
  3290. return 0;
  3291. }