ffplay.c 106 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198
  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 "libavutil/avstring.h"
  30. #include "libavutil/colorspace.h"
  31. #include "libavutil/mathematics.h"
  32. #include "libavutil/pixdesc.h"
  33. #include "libavutil/imgutils.h"
  34. #include "libavutil/dict.h"
  35. #include "libavutil/parseutils.h"
  36. #include "libavutil/samplefmt.h"
  37. #include "libavutil/avassert.h"
  38. #include "libavutil/time.h"
  39. #include "libavformat/avformat.h"
  40. #include "libavdevice/avdevice.h"
  41. #include "libswscale/swscale.h"
  42. #include "libavutil/opt.h"
  43. #include "libavcodec/avfft.h"
  44. #include "libswresample/swresample.h"
  45. #if CONFIG_AVFILTER
  46. # include "libavfilter/avcodec.h"
  47. # include "libavfilter/avfilter.h"
  48. # include "libavfilter/avfiltergraph.h"
  49. # include "libavfilter/buffersink.h"
  50. # include "libavfilter/buffersrc.h"
  51. #endif
  52. #include <SDL.h>
  53. #include <SDL_thread.h>
  54. #include "cmdutils.h"
  55. #include <assert.h>
  56. const char program_name[] = "ffplay";
  57. const int program_birth_year = 2003;
  58. #define MAX_QUEUE_SIZE (15 * 1024 * 1024)
  59. #define MIN_FRAMES 5
  60. /* SDL audio buffer size, in samples. Should be small to have precise
  61. A/V sync as SDL does not have hardware buffer fullness info. */
  62. #define SDL_AUDIO_BUFFER_SIZE 1024
  63. /* no AV sync correction is done if below the AV sync threshold */
  64. #define AV_SYNC_THRESHOLD 0.01
  65. /* no AV correction is done if too big error */
  66. #define AV_NOSYNC_THRESHOLD 10.0
  67. /* maximum audio speed change to get correct sync */
  68. #define SAMPLE_CORRECTION_PERCENT_MAX 10
  69. /* we use about AUDIO_DIFF_AVG_NB A-V differences to make the average */
  70. #define AUDIO_DIFF_AVG_NB 20
  71. /* NOTE: the size must be big enough to compensate the hardware audio buffersize size */
  72. /* TODO: We assume that a decoded and resampled frame fits into this buffer */
  73. #define SAMPLE_ARRAY_SIZE (8 * 65536)
  74. static int sws_flags = SWS_BICUBIC;
  75. typedef struct PacketQueue {
  76. AVPacketList *first_pkt, *last_pkt;
  77. int nb_packets;
  78. int size;
  79. int abort_request;
  80. SDL_mutex *mutex;
  81. SDL_cond *cond;
  82. } PacketQueue;
  83. #define VIDEO_PICTURE_QUEUE_SIZE 4
  84. #define SUBPICTURE_QUEUE_SIZE 4
  85. typedef struct VideoPicture {
  86. double pts; ///< presentation time stamp for this picture
  87. int64_t pos; ///< byte position in file
  88. int skip;
  89. SDL_Overlay *bmp;
  90. int width, height; /* source height & width */
  91. AVRational sample_aspect_ratio;
  92. int allocated;
  93. int reallocate;
  94. #if CONFIG_AVFILTER
  95. AVFilterBufferRef *picref;
  96. #endif
  97. } VideoPicture;
  98. typedef struct SubPicture {
  99. double pts; /* presentation time stamp for this picture */
  100. AVSubtitle sub;
  101. } SubPicture;
  102. typedef struct AudioParams {
  103. int freq;
  104. int channels;
  105. int channel_layout;
  106. enum AVSampleFormat fmt;
  107. } AudioParams;
  108. enum {
  109. AV_SYNC_AUDIO_MASTER, /* default choice */
  110. AV_SYNC_VIDEO_MASTER,
  111. AV_SYNC_EXTERNAL_CLOCK, /* synchronize to an external clock */
  112. };
  113. typedef struct VideoState {
  114. SDL_Thread *read_tid;
  115. SDL_Thread *video_tid;
  116. SDL_Thread *refresh_tid;
  117. AVInputFormat *iformat;
  118. int no_background;
  119. int abort_request;
  120. int force_refresh;
  121. int paused;
  122. int last_paused;
  123. int que_attachments_req;
  124. int seek_req;
  125. int seek_flags;
  126. int64_t seek_pos;
  127. int64_t seek_rel;
  128. int read_pause_return;
  129. AVFormatContext *ic;
  130. int audio_stream;
  131. int av_sync_type;
  132. double external_clock; /* external clock base */
  133. int64_t external_clock_time;
  134. double audio_clock;
  135. double audio_diff_cum; /* used for AV difference average computation */
  136. double audio_diff_avg_coef;
  137. double audio_diff_threshold;
  138. int audio_diff_avg_count;
  139. AVStream *audio_st;
  140. PacketQueue audioq;
  141. int audio_hw_buf_size;
  142. DECLARE_ALIGNED(16,uint8_t,audio_buf2)[AVCODEC_MAX_AUDIO_FRAME_SIZE * 4];
  143. uint8_t silence_buf[SDL_AUDIO_BUFFER_SIZE];
  144. uint8_t *audio_buf;
  145. uint8_t *audio_buf1;
  146. unsigned int audio_buf_size; /* in bytes */
  147. int audio_buf_index; /* in bytes */
  148. int audio_write_buf_size;
  149. AVPacket audio_pkt_temp;
  150. AVPacket audio_pkt;
  151. struct AudioParams audio_src;
  152. struct AudioParams audio_tgt;
  153. struct SwrContext *swr_ctx;
  154. double audio_current_pts;
  155. double audio_current_pts_drift;
  156. int frame_drops_early;
  157. int frame_drops_late;
  158. AVFrame *frame;
  159. enum ShowMode {
  160. SHOW_MODE_NONE = -1, SHOW_MODE_VIDEO = 0, SHOW_MODE_WAVES, SHOW_MODE_RDFT, SHOW_MODE_NB
  161. } show_mode;
  162. int16_t sample_array[SAMPLE_ARRAY_SIZE];
  163. int sample_array_index;
  164. int last_i_start;
  165. RDFTContext *rdft;
  166. int rdft_bits;
  167. FFTSample *rdft_data;
  168. int xpos;
  169. SDL_Thread *subtitle_tid;
  170. int subtitle_stream;
  171. int subtitle_stream_changed;
  172. AVStream *subtitle_st;
  173. PacketQueue subtitleq;
  174. SubPicture subpq[SUBPICTURE_QUEUE_SIZE];
  175. int subpq_size, subpq_rindex, subpq_windex;
  176. SDL_mutex *subpq_mutex;
  177. SDL_cond *subpq_cond;
  178. double frame_timer;
  179. double frame_last_pts;
  180. double frame_last_duration;
  181. double frame_last_dropped_pts;
  182. double frame_last_returned_time;
  183. double frame_last_filter_delay;
  184. int64_t frame_last_dropped_pos;
  185. double video_clock; ///< pts of last decoded frame / predicted pts of next decoded frame
  186. int video_stream;
  187. AVStream *video_st;
  188. PacketQueue videoq;
  189. double video_current_pts; ///< current displayed pts (different from video_clock if frame fifos are used)
  190. double video_current_pts_drift; ///< video_current_pts - time (av_gettime) at which we updated video_current_pts - used to have running video pts
  191. int64_t video_current_pos; ///< current displayed file pos
  192. VideoPicture pictq[VIDEO_PICTURE_QUEUE_SIZE];
  193. int pictq_size, pictq_rindex, pictq_windex;
  194. SDL_mutex *pictq_mutex;
  195. SDL_cond *pictq_cond;
  196. #if !CONFIG_AVFILTER
  197. struct SwsContext *img_convert_ctx;
  198. #endif
  199. char filename[1024];
  200. int width, height, xleft, ytop;
  201. int step;
  202. #if CONFIG_AVFILTER
  203. AVFilterContext *in_video_filter; ///< the first filter in the video chain
  204. AVFilterContext *out_video_filter; ///< the last filter in the video chain
  205. int use_dr1;
  206. FrameBuffer *buffer_pool;
  207. #endif
  208. int refresh;
  209. int last_video_stream, last_audio_stream, last_subtitle_stream;
  210. SDL_cond *continue_read_thread;
  211. } VideoState;
  212. /* options specified by the user */
  213. static AVInputFormat *file_iformat;
  214. static const char *input_filename;
  215. static const char *window_title;
  216. static int fs_screen_width;
  217. static int fs_screen_height;
  218. static int screen_width = 0;
  219. static int screen_height = 0;
  220. static int audio_disable;
  221. static int video_disable;
  222. static int wanted_stream[AVMEDIA_TYPE_NB] = {
  223. [AVMEDIA_TYPE_AUDIO] = -1,
  224. [AVMEDIA_TYPE_VIDEO] = -1,
  225. [AVMEDIA_TYPE_SUBTITLE] = -1,
  226. };
  227. static int seek_by_bytes = -1;
  228. static int display_disable;
  229. static int show_status = 1;
  230. static int av_sync_type = AV_SYNC_AUDIO_MASTER;
  231. static int64_t start_time = AV_NOPTS_VALUE;
  232. static int64_t duration = AV_NOPTS_VALUE;
  233. static int workaround_bugs = 1;
  234. static int fast = 0;
  235. static int genpts = 0;
  236. static int lowres = 0;
  237. static int idct = FF_IDCT_AUTO;
  238. static enum AVDiscard skip_frame = AVDISCARD_DEFAULT;
  239. static enum AVDiscard skip_idct = AVDISCARD_DEFAULT;
  240. static enum AVDiscard skip_loop_filter = AVDISCARD_DEFAULT;
  241. static int error_concealment = 3;
  242. static int decoder_reorder_pts = -1;
  243. static int autoexit;
  244. static int exit_on_keydown;
  245. static int exit_on_mousedown;
  246. static int loop = 1;
  247. static int framedrop = -1;
  248. static int infinite_buffer = 0;
  249. static enum ShowMode show_mode = SHOW_MODE_NONE;
  250. static const char *audio_codec_name;
  251. static const char *subtitle_codec_name;
  252. static const char *video_codec_name;
  253. static int rdftspeed = 20;
  254. #if CONFIG_AVFILTER
  255. static char *vfilters = NULL;
  256. #endif
  257. /* current context */
  258. static int is_full_screen;
  259. static int64_t audio_callback_time;
  260. static AVPacket flush_pkt;
  261. #define FF_ALLOC_EVENT (SDL_USEREVENT)
  262. #define FF_REFRESH_EVENT (SDL_USEREVENT + 1)
  263. #define FF_QUIT_EVENT (SDL_USEREVENT + 2)
  264. static SDL_Surface *screen;
  265. void av_noreturn exit_program(int ret)
  266. {
  267. exit(ret);
  268. }
  269. static int packet_queue_put_private(PacketQueue *q, AVPacket *pkt)
  270. {
  271. AVPacketList *pkt1;
  272. if (q->abort_request)
  273. return -1;
  274. pkt1 = av_malloc(sizeof(AVPacketList));
  275. if (!pkt1)
  276. return -1;
  277. pkt1->pkt = *pkt;
  278. pkt1->next = NULL;
  279. if (!q->last_pkt)
  280. q->first_pkt = pkt1;
  281. else
  282. q->last_pkt->next = pkt1;
  283. q->last_pkt = pkt1;
  284. q->nb_packets++;
  285. q->size += pkt1->pkt.size + sizeof(*pkt1);
  286. /* XXX: should duplicate packet data in DV case */
  287. SDL_CondSignal(q->cond);
  288. return 0;
  289. }
  290. static int packet_queue_put(PacketQueue *q, AVPacket *pkt)
  291. {
  292. int ret;
  293. /* duplicate the packet */
  294. if (pkt != &flush_pkt && av_dup_packet(pkt) < 0)
  295. return -1;
  296. SDL_LockMutex(q->mutex);
  297. ret = packet_queue_put_private(q, pkt);
  298. SDL_UnlockMutex(q->mutex);
  299. if (pkt != &flush_pkt && ret < 0)
  300. av_free_packet(pkt);
  301. return ret;
  302. }
  303. /* packet queue handling */
  304. static void packet_queue_init(PacketQueue *q)
  305. {
  306. memset(q, 0, sizeof(PacketQueue));
  307. q->mutex = SDL_CreateMutex();
  308. q->cond = SDL_CreateCond();
  309. q->abort_request = 1;
  310. }
  311. static void packet_queue_flush(PacketQueue *q)
  312. {
  313. AVPacketList *pkt, *pkt1;
  314. SDL_LockMutex(q->mutex);
  315. for (pkt = q->first_pkt; pkt != NULL; pkt = pkt1) {
  316. pkt1 = pkt->next;
  317. av_free_packet(&pkt->pkt);
  318. av_freep(&pkt);
  319. }
  320. q->last_pkt = NULL;
  321. q->first_pkt = NULL;
  322. q->nb_packets = 0;
  323. q->size = 0;
  324. SDL_UnlockMutex(q->mutex);
  325. }
  326. static void packet_queue_destroy(PacketQueue *q)
  327. {
  328. packet_queue_flush(q);
  329. SDL_DestroyMutex(q->mutex);
  330. SDL_DestroyCond(q->cond);
  331. }
  332. static void packet_queue_abort(PacketQueue *q)
  333. {
  334. SDL_LockMutex(q->mutex);
  335. q->abort_request = 1;
  336. SDL_CondSignal(q->cond);
  337. SDL_UnlockMutex(q->mutex);
  338. }
  339. static void packet_queue_start(PacketQueue *q)
  340. {
  341. SDL_LockMutex(q->mutex);
  342. q->abort_request = 0;
  343. packet_queue_put_private(q, &flush_pkt);
  344. SDL_UnlockMutex(q->mutex);
  345. }
  346. /* return < 0 if aborted, 0 if no packet and > 0 if packet. */
  347. static int packet_queue_get(PacketQueue *q, AVPacket *pkt, int block)
  348. {
  349. AVPacketList *pkt1;
  350. int ret;
  351. SDL_LockMutex(q->mutex);
  352. for (;;) {
  353. if (q->abort_request) {
  354. ret = -1;
  355. break;
  356. }
  357. pkt1 = q->first_pkt;
  358. if (pkt1) {
  359. q->first_pkt = pkt1->next;
  360. if (!q->first_pkt)
  361. q->last_pkt = NULL;
  362. q->nb_packets--;
  363. q->size -= pkt1->pkt.size + sizeof(*pkt1);
  364. *pkt = pkt1->pkt;
  365. av_free(pkt1);
  366. ret = 1;
  367. break;
  368. } else if (!block) {
  369. ret = 0;
  370. break;
  371. } else {
  372. SDL_CondWait(q->cond, q->mutex);
  373. }
  374. }
  375. SDL_UnlockMutex(q->mutex);
  376. return ret;
  377. }
  378. static inline void fill_rectangle(SDL_Surface *screen,
  379. int x, int y, int w, int h, int color)
  380. {
  381. SDL_Rect rect;
  382. rect.x = x;
  383. rect.y = y;
  384. rect.w = w;
  385. rect.h = h;
  386. SDL_FillRect(screen, &rect, color);
  387. }
  388. #define ALPHA_BLEND(a, oldp, newp, s)\
  389. ((((oldp << s) * (255 - (a))) + (newp * (a))) / (255 << s))
  390. #define RGBA_IN(r, g, b, a, s)\
  391. {\
  392. unsigned int v = ((const uint32_t *)(s))[0];\
  393. a = (v >> 24) & 0xff;\
  394. r = (v >> 16) & 0xff;\
  395. g = (v >> 8) & 0xff;\
  396. b = v & 0xff;\
  397. }
  398. #define YUVA_IN(y, u, v, a, s, pal)\
  399. {\
  400. unsigned int val = ((const uint32_t *)(pal))[*(const uint8_t*)(s)];\
  401. a = (val >> 24) & 0xff;\
  402. y = (val >> 16) & 0xff;\
  403. u = (val >> 8) & 0xff;\
  404. v = val & 0xff;\
  405. }
  406. #define YUVA_OUT(d, y, u, v, a)\
  407. {\
  408. ((uint32_t *)(d))[0] = (a << 24) | (y << 16) | (u << 8) | v;\
  409. }
  410. #define BPP 1
  411. static void blend_subrect(AVPicture *dst, const AVSubtitleRect *rect, int imgw, int imgh)
  412. {
  413. int wrap, wrap3, width2, skip2;
  414. int y, u, v, a, u1, v1, a1, w, h;
  415. uint8_t *lum, *cb, *cr;
  416. const uint8_t *p;
  417. const uint32_t *pal;
  418. int dstx, dsty, dstw, dsth;
  419. dstw = av_clip(rect->w, 0, imgw);
  420. dsth = av_clip(rect->h, 0, imgh);
  421. dstx = av_clip(rect->x, 0, imgw - dstw);
  422. dsty = av_clip(rect->y, 0, imgh - dsth);
  423. lum = dst->data[0] + dsty * dst->linesize[0];
  424. cb = dst->data[1] + (dsty >> 1) * dst->linesize[1];
  425. cr = dst->data[2] + (dsty >> 1) * dst->linesize[2];
  426. width2 = ((dstw + 1) >> 1) + (dstx & ~dstw & 1);
  427. skip2 = dstx >> 1;
  428. wrap = dst->linesize[0];
  429. wrap3 = rect->pict.linesize[0];
  430. p = rect->pict.data[0];
  431. pal = (const uint32_t *)rect->pict.data[1]; /* Now in YCrCb! */
  432. if (dsty & 1) {
  433. lum += dstx;
  434. cb += skip2;
  435. cr += skip2;
  436. if (dstx & 1) {
  437. YUVA_IN(y, u, v, a, p, pal);
  438. lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
  439. cb[0] = ALPHA_BLEND(a >> 2, cb[0], u, 0);
  440. cr[0] = ALPHA_BLEND(a >> 2, cr[0], v, 0);
  441. cb++;
  442. cr++;
  443. lum++;
  444. p += BPP;
  445. }
  446. for (w = dstw - (dstx & 1); w >= 2; w -= 2) {
  447. YUVA_IN(y, u, v, a, p, pal);
  448. u1 = u;
  449. v1 = v;
  450. a1 = a;
  451. lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
  452. YUVA_IN(y, u, v, a, p + BPP, pal);
  453. u1 += u;
  454. v1 += v;
  455. a1 += a;
  456. lum[1] = ALPHA_BLEND(a, lum[1], y, 0);
  457. cb[0] = ALPHA_BLEND(a1 >> 2, cb[0], u1, 1);
  458. cr[0] = ALPHA_BLEND(a1 >> 2, cr[0], v1, 1);
  459. cb++;
  460. cr++;
  461. p += 2 * BPP;
  462. lum += 2;
  463. }
  464. if (w) {
  465. YUVA_IN(y, u, v, a, p, pal);
  466. lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
  467. cb[0] = ALPHA_BLEND(a >> 2, cb[0], u, 0);
  468. cr[0] = ALPHA_BLEND(a >> 2, cr[0], v, 0);
  469. p++;
  470. lum++;
  471. }
  472. p += wrap3 - dstw * BPP;
  473. lum += wrap - dstw - dstx;
  474. cb += dst->linesize[1] - width2 - skip2;
  475. cr += dst->linesize[2] - width2 - skip2;
  476. }
  477. for (h = dsth - (dsty & 1); h >= 2; h -= 2) {
  478. lum += dstx;
  479. cb += skip2;
  480. cr += skip2;
  481. if (dstx & 1) {
  482. YUVA_IN(y, u, v, a, p, pal);
  483. u1 = u;
  484. v1 = v;
  485. a1 = a;
  486. lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
  487. p += wrap3;
  488. lum += wrap;
  489. YUVA_IN(y, u, v, a, p, pal);
  490. u1 += u;
  491. v1 += v;
  492. a1 += a;
  493. lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
  494. cb[0] = ALPHA_BLEND(a1 >> 2, cb[0], u1, 1);
  495. cr[0] = ALPHA_BLEND(a1 >> 2, cr[0], v1, 1);
  496. cb++;
  497. cr++;
  498. p += -wrap3 + BPP;
  499. lum += -wrap + 1;
  500. }
  501. for (w = dstw - (dstx & 1); w >= 2; w -= 2) {
  502. YUVA_IN(y, u, v, a, p, pal);
  503. u1 = u;
  504. v1 = v;
  505. a1 = a;
  506. lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
  507. YUVA_IN(y, u, v, a, p + BPP, pal);
  508. u1 += u;
  509. v1 += v;
  510. a1 += a;
  511. lum[1] = ALPHA_BLEND(a, lum[1], y, 0);
  512. p += wrap3;
  513. lum += wrap;
  514. YUVA_IN(y, u, v, a, p, pal);
  515. u1 += u;
  516. v1 += v;
  517. a1 += a;
  518. lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
  519. YUVA_IN(y, u, v, a, p + BPP, pal);
  520. u1 += u;
  521. v1 += v;
  522. a1 += a;
  523. lum[1] = ALPHA_BLEND(a, lum[1], y, 0);
  524. cb[0] = ALPHA_BLEND(a1 >> 2, cb[0], u1, 2);
  525. cr[0] = ALPHA_BLEND(a1 >> 2, cr[0], v1, 2);
  526. cb++;
  527. cr++;
  528. p += -wrap3 + 2 * BPP;
  529. lum += -wrap + 2;
  530. }
  531. if (w) {
  532. YUVA_IN(y, u, v, a, p, pal);
  533. u1 = u;
  534. v1 = v;
  535. a1 = a;
  536. lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
  537. p += wrap3;
  538. lum += wrap;
  539. YUVA_IN(y, u, v, a, p, pal);
  540. u1 += u;
  541. v1 += v;
  542. a1 += a;
  543. lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
  544. cb[0] = ALPHA_BLEND(a1 >> 2, cb[0], u1, 1);
  545. cr[0] = ALPHA_BLEND(a1 >> 2, cr[0], v1, 1);
  546. cb++;
  547. cr++;
  548. p += -wrap3 + BPP;
  549. lum += -wrap + 1;
  550. }
  551. p += wrap3 + (wrap3 - dstw * BPP);
  552. lum += wrap + (wrap - dstw - dstx);
  553. cb += dst->linesize[1] - width2 - skip2;
  554. cr += dst->linesize[2] - width2 - skip2;
  555. }
  556. /* handle odd height */
  557. if (h) {
  558. lum += dstx;
  559. cb += skip2;
  560. cr += skip2;
  561. if (dstx & 1) {
  562. YUVA_IN(y, u, v, a, p, pal);
  563. lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
  564. cb[0] = ALPHA_BLEND(a >> 2, cb[0], u, 0);
  565. cr[0] = ALPHA_BLEND(a >> 2, cr[0], v, 0);
  566. cb++;
  567. cr++;
  568. lum++;
  569. p += BPP;
  570. }
  571. for (w = dstw - (dstx & 1); w >= 2; w -= 2) {
  572. YUVA_IN(y, u, v, a, p, pal);
  573. u1 = u;
  574. v1 = v;
  575. a1 = a;
  576. lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
  577. YUVA_IN(y, u, v, a, p + BPP, pal);
  578. u1 += u;
  579. v1 += v;
  580. a1 += a;
  581. lum[1] = ALPHA_BLEND(a, lum[1], y, 0);
  582. cb[0] = ALPHA_BLEND(a1 >> 2, cb[0], u, 1);
  583. cr[0] = ALPHA_BLEND(a1 >> 2, cr[0], v, 1);
  584. cb++;
  585. cr++;
  586. p += 2 * BPP;
  587. lum += 2;
  588. }
  589. if (w) {
  590. YUVA_IN(y, u, v, a, p, pal);
  591. lum[0] = ALPHA_BLEND(a, lum[0], y, 0);
  592. cb[0] = ALPHA_BLEND(a >> 2, cb[0], u, 0);
  593. cr[0] = ALPHA_BLEND(a >> 2, cr[0], v, 0);
  594. }
  595. }
  596. }
  597. static void free_subpicture(SubPicture *sp)
  598. {
  599. avsubtitle_free(&sp->sub);
  600. }
  601. static void calculate_display_rect(SDL_Rect *rect, int scr_xleft, int scr_ytop, int scr_width, int scr_height, VideoPicture *vp)
  602. {
  603. float aspect_ratio;
  604. int width, height, x, y;
  605. if (vp->sample_aspect_ratio.num == 0)
  606. aspect_ratio = 0;
  607. else
  608. aspect_ratio = av_q2d(vp->sample_aspect_ratio);
  609. if (aspect_ratio <= 0.0)
  610. aspect_ratio = 1.0;
  611. aspect_ratio *= (float)vp->width / (float)vp->height;
  612. /* XXX: we suppose the screen has a 1.0 pixel ratio */
  613. height = scr_height;
  614. width = ((int)rint(height * aspect_ratio)) & ~1;
  615. if (width > scr_width) {
  616. width = scr_width;
  617. height = ((int)rint(width / aspect_ratio)) & ~1;
  618. }
  619. x = (scr_width - width) / 2;
  620. y = (scr_height - height) / 2;
  621. rect->x = scr_xleft + x;
  622. rect->y = scr_ytop + y;
  623. rect->w = FFMAX(width, 1);
  624. rect->h = FFMAX(height, 1);
  625. }
  626. static void video_image_display(VideoState *is)
  627. {
  628. VideoPicture *vp;
  629. SubPicture *sp;
  630. AVPicture pict;
  631. SDL_Rect rect;
  632. int i;
  633. vp = &is->pictq[is->pictq_rindex];
  634. if (vp->bmp) {
  635. if (is->subtitle_st) {
  636. if (is->subpq_size > 0) {
  637. sp = &is->subpq[is->subpq_rindex];
  638. if (vp->pts >= sp->pts + ((float) sp->sub.start_display_time / 1000)) {
  639. SDL_LockYUVOverlay (vp->bmp);
  640. pict.data[0] = vp->bmp->pixels[0];
  641. pict.data[1] = vp->bmp->pixels[2];
  642. pict.data[2] = vp->bmp->pixels[1];
  643. pict.linesize[0] = vp->bmp->pitches[0];
  644. pict.linesize[1] = vp->bmp->pitches[2];
  645. pict.linesize[2] = vp->bmp->pitches[1];
  646. for (i = 0; i < sp->sub.num_rects; i++)
  647. blend_subrect(&pict, sp->sub.rects[i],
  648. vp->bmp->w, vp->bmp->h);
  649. SDL_UnlockYUVOverlay (vp->bmp);
  650. }
  651. }
  652. }
  653. calculate_display_rect(&rect, is->xleft, is->ytop, is->width, is->height, vp);
  654. SDL_DisplayYUVOverlay(vp->bmp, &rect);
  655. }
  656. }
  657. static inline int compute_mod(int a, int b)
  658. {
  659. return a < 0 ? a%b + b : a%b;
  660. }
  661. static void video_audio_display(VideoState *s)
  662. {
  663. int i, i_start, x, y1, y, ys, delay, n, nb_display_channels;
  664. int ch, channels, h, h2, bgcolor, fgcolor;
  665. int16_t time_diff;
  666. int rdft_bits, nb_freq;
  667. for (rdft_bits = 1; (1 << rdft_bits) < 2 * s->height; rdft_bits++)
  668. ;
  669. nb_freq = 1 << (rdft_bits - 1);
  670. /* compute display index : center on currently output samples */
  671. channels = s->audio_tgt.channels;
  672. nb_display_channels = channels;
  673. if (!s->paused) {
  674. int data_used= s->show_mode == SHOW_MODE_WAVES ? s->width : (2*nb_freq);
  675. n = 2 * channels;
  676. delay = s->audio_write_buf_size;
  677. delay /= n;
  678. /* to be more precise, we take into account the time spent since
  679. the last buffer computation */
  680. if (audio_callback_time) {
  681. time_diff = av_gettime() - audio_callback_time;
  682. delay -= (time_diff * s->audio_tgt.freq) / 1000000;
  683. }
  684. delay += 2 * data_used;
  685. if (delay < data_used)
  686. delay = data_used;
  687. i_start= x = compute_mod(s->sample_array_index - delay * channels, SAMPLE_ARRAY_SIZE);
  688. if (s->show_mode == SHOW_MODE_WAVES) {
  689. h = INT_MIN;
  690. for (i = 0; i < 1000; i += channels) {
  691. int idx = (SAMPLE_ARRAY_SIZE + x - i) % SAMPLE_ARRAY_SIZE;
  692. int a = s->sample_array[idx];
  693. int b = s->sample_array[(idx + 4 * channels) % SAMPLE_ARRAY_SIZE];
  694. int c = s->sample_array[(idx + 5 * channels) % SAMPLE_ARRAY_SIZE];
  695. int d = s->sample_array[(idx + 9 * channels) % SAMPLE_ARRAY_SIZE];
  696. int score = a - d;
  697. if (h < score && (b ^ c) < 0) {
  698. h = score;
  699. i_start = idx;
  700. }
  701. }
  702. }
  703. s->last_i_start = i_start;
  704. } else {
  705. i_start = s->last_i_start;
  706. }
  707. bgcolor = SDL_MapRGB(screen->format, 0x00, 0x00, 0x00);
  708. if (s->show_mode == SHOW_MODE_WAVES) {
  709. fill_rectangle(screen,
  710. s->xleft, s->ytop, s->width, s->height,
  711. bgcolor);
  712. fgcolor = SDL_MapRGB(screen->format, 0xff, 0xff, 0xff);
  713. /* total height for one channel */
  714. h = s->height / nb_display_channels;
  715. /* graph height / 2 */
  716. h2 = (h * 9) / 20;
  717. for (ch = 0; ch < nb_display_channels; ch++) {
  718. i = i_start + ch;
  719. y1 = s->ytop + ch * h + (h / 2); /* position of center line */
  720. for (x = 0; x < s->width; x++) {
  721. y = (s->sample_array[i] * h2) >> 15;
  722. if (y < 0) {
  723. y = -y;
  724. ys = y1 - y;
  725. } else {
  726. ys = y1;
  727. }
  728. fill_rectangle(screen,
  729. s->xleft + x, ys, 1, y,
  730. fgcolor);
  731. i += channels;
  732. if (i >= SAMPLE_ARRAY_SIZE)
  733. i -= SAMPLE_ARRAY_SIZE;
  734. }
  735. }
  736. fgcolor = SDL_MapRGB(screen->format, 0x00, 0x00, 0xff);
  737. for (ch = 1; ch < nb_display_channels; ch++) {
  738. y = s->ytop + ch * h;
  739. fill_rectangle(screen,
  740. s->xleft, y, s->width, 1,
  741. fgcolor);
  742. }
  743. SDL_UpdateRect(screen, s->xleft, s->ytop, s->width, s->height);
  744. } else {
  745. nb_display_channels= FFMIN(nb_display_channels, 2);
  746. if (rdft_bits != s->rdft_bits) {
  747. av_rdft_end(s->rdft);
  748. av_free(s->rdft_data);
  749. s->rdft = av_rdft_init(rdft_bits, DFT_R2C);
  750. s->rdft_bits = rdft_bits;
  751. s->rdft_data = av_malloc(4 * nb_freq * sizeof(*s->rdft_data));
  752. }
  753. {
  754. FFTSample *data[2];
  755. for (ch = 0; ch < nb_display_channels; ch++) {
  756. data[ch] = s->rdft_data + 2 * nb_freq * ch;
  757. i = i_start + ch;
  758. for (x = 0; x < 2 * nb_freq; x++) {
  759. double w = (x-nb_freq) * (1.0 / nb_freq);
  760. data[ch][x] = s->sample_array[i] * (1.0 - w * w);
  761. i += channels;
  762. if (i >= SAMPLE_ARRAY_SIZE)
  763. i -= SAMPLE_ARRAY_SIZE;
  764. }
  765. av_rdft_calc(s->rdft, data[ch]);
  766. }
  767. // least efficient way to do this, we should of course directly access it but its more than fast enough
  768. for (y = 0; y < s->height; y++) {
  769. double w = 1 / sqrt(nb_freq);
  770. 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]));
  771. int b = (nb_display_channels == 2 ) ? sqrt(w * sqrt(data[1][2 * y + 0] * data[1][2 * y + 0]
  772. + data[1][2 * y + 1] * data[1][2 * y + 1])) : a;
  773. a = FFMIN(a, 255);
  774. b = FFMIN(b, 255);
  775. fgcolor = SDL_MapRGB(screen->format, a, b, (a + b) / 2);
  776. fill_rectangle(screen,
  777. s->xpos, s->height-y, 1, 1,
  778. fgcolor);
  779. }
  780. }
  781. SDL_UpdateRect(screen, s->xpos, s->ytop, 1, s->height);
  782. if (!s->paused)
  783. s->xpos++;
  784. if (s->xpos >= s->width)
  785. s->xpos= s->xleft;
  786. }
  787. }
  788. static void stream_close(VideoState *is)
  789. {
  790. VideoPicture *vp;
  791. int i;
  792. /* XXX: use a special url_shutdown call to abort parse cleanly */
  793. is->abort_request = 1;
  794. SDL_WaitThread(is->read_tid, NULL);
  795. SDL_WaitThread(is->refresh_tid, NULL);
  796. packet_queue_destroy(&is->videoq);
  797. packet_queue_destroy(&is->audioq);
  798. packet_queue_destroy(&is->subtitleq);
  799. /* free all pictures */
  800. for (i = 0; i < VIDEO_PICTURE_QUEUE_SIZE; i++) {
  801. vp = &is->pictq[i];
  802. #if CONFIG_AVFILTER
  803. avfilter_unref_bufferp(&vp->picref);
  804. #endif
  805. if (vp->bmp) {
  806. SDL_FreeYUVOverlay(vp->bmp);
  807. vp->bmp = NULL;
  808. }
  809. }
  810. SDL_DestroyMutex(is->pictq_mutex);
  811. SDL_DestroyCond(is->pictq_cond);
  812. SDL_DestroyMutex(is->subpq_mutex);
  813. SDL_DestroyCond(is->subpq_cond);
  814. SDL_DestroyCond(is->continue_read_thread);
  815. #if !CONFIG_AVFILTER
  816. if (is->img_convert_ctx)
  817. sws_freeContext(is->img_convert_ctx);
  818. #endif
  819. av_free(is);
  820. }
  821. static void do_exit(VideoState *is)
  822. {
  823. if (is) {
  824. stream_close(is);
  825. }
  826. av_lockmgr_register(NULL);
  827. uninit_opts();
  828. #if CONFIG_AVFILTER
  829. avfilter_uninit();
  830. av_freep(&vfilters);
  831. #endif
  832. avformat_network_deinit();
  833. if (show_status)
  834. printf("\n");
  835. SDL_Quit();
  836. av_log(NULL, AV_LOG_QUIET, "%s", "");
  837. exit(0);
  838. }
  839. static void sigterm_handler(int sig)
  840. {
  841. exit(123);
  842. }
  843. static int video_open(VideoState *is, int force_set_video_mode)
  844. {
  845. int flags = SDL_HWSURFACE | SDL_ASYNCBLIT | SDL_HWACCEL;
  846. int w,h;
  847. VideoPicture *vp = &is->pictq[is->pictq_rindex];
  848. SDL_Rect rect;
  849. if (is_full_screen) flags |= SDL_FULLSCREEN;
  850. else flags |= SDL_RESIZABLE;
  851. if (is_full_screen && fs_screen_width) {
  852. w = fs_screen_width;
  853. h = fs_screen_height;
  854. } else if (!is_full_screen && screen_width) {
  855. w = screen_width;
  856. h = screen_height;
  857. } else if (vp->width) {
  858. calculate_display_rect(&rect, 0, 0, INT_MAX, vp->height, vp);
  859. w = rect.w;
  860. h = rect.h;
  861. } else {
  862. w = 640;
  863. h = 480;
  864. }
  865. if (screen && is->width == screen->w && screen->w == w
  866. && is->height== screen->h && screen->h == h && !force_set_video_mode)
  867. return 0;
  868. screen = SDL_SetVideoMode(w, h, 0, flags);
  869. if (!screen) {
  870. fprintf(stderr, "SDL: could not set video mode - exiting\n");
  871. do_exit(is);
  872. }
  873. if (!window_title)
  874. window_title = input_filename;
  875. SDL_WM_SetCaption(window_title, window_title);
  876. is->width = screen->w;
  877. is->height = screen->h;
  878. return 0;
  879. }
  880. /* display the current picture, if any */
  881. static void video_display(VideoState *is)
  882. {
  883. if (!screen)
  884. video_open(is, 0);
  885. if (is->audio_st && is->show_mode != SHOW_MODE_VIDEO)
  886. video_audio_display(is);
  887. else if (is->video_st)
  888. video_image_display(is);
  889. }
  890. static int refresh_thread(void *opaque)
  891. {
  892. VideoState *is= opaque;
  893. while (!is->abort_request) {
  894. SDL_Event event;
  895. event.type = FF_REFRESH_EVENT;
  896. event.user.data1 = opaque;
  897. if (!is->refresh && (!is->paused || is->force_refresh)) {
  898. is->refresh = 1;
  899. SDL_PushEvent(&event);
  900. }
  901. //FIXME ideally we should wait the correct time but SDLs event passing is so slow it would be silly
  902. av_usleep(is->audio_st && is->show_mode != SHOW_MODE_VIDEO ? rdftspeed*1000 : 5000);
  903. }
  904. return 0;
  905. }
  906. /* get the current audio clock value */
  907. static double get_audio_clock(VideoState *is)
  908. {
  909. if (is->paused) {
  910. return is->audio_current_pts;
  911. } else {
  912. return is->audio_current_pts_drift + av_gettime() / 1000000.0;
  913. }
  914. }
  915. /* get the current video clock value */
  916. static double get_video_clock(VideoState *is)
  917. {
  918. if (is->paused) {
  919. return is->video_current_pts;
  920. } else {
  921. return is->video_current_pts_drift + av_gettime() / 1000000.0;
  922. }
  923. }
  924. /* get the current external clock value */
  925. static double get_external_clock(VideoState *is)
  926. {
  927. int64_t ti;
  928. ti = av_gettime();
  929. return is->external_clock + ((ti - is->external_clock_time) * 1e-6);
  930. }
  931. /* get the current master clock value */
  932. static double get_master_clock(VideoState *is)
  933. {
  934. double val;
  935. if (is->av_sync_type == AV_SYNC_VIDEO_MASTER) {
  936. if (is->video_st)
  937. val = get_video_clock(is);
  938. else
  939. val = get_audio_clock(is);
  940. } else if (is->av_sync_type == AV_SYNC_AUDIO_MASTER) {
  941. if (is->audio_st)
  942. val = get_audio_clock(is);
  943. else
  944. val = get_video_clock(is);
  945. } else {
  946. val = get_external_clock(is);
  947. }
  948. return val;
  949. }
  950. /* seek in the stream */
  951. static void stream_seek(VideoState *is, int64_t pos, int64_t rel, int seek_by_bytes)
  952. {
  953. if (!is->seek_req) {
  954. is->seek_pos = pos;
  955. is->seek_rel = rel;
  956. is->seek_flags &= ~AVSEEK_FLAG_BYTE;
  957. if (seek_by_bytes)
  958. is->seek_flags |= AVSEEK_FLAG_BYTE;
  959. is->seek_req = 1;
  960. }
  961. }
  962. /* pause or resume the video */
  963. static void stream_toggle_pause(VideoState *is)
  964. {
  965. if (is->paused) {
  966. is->frame_timer += av_gettime() / 1000000.0 + is->video_current_pts_drift - is->video_current_pts;
  967. if (is->read_pause_return != AVERROR(ENOSYS)) {
  968. is->video_current_pts = is->video_current_pts_drift + av_gettime() / 1000000.0;
  969. }
  970. is->video_current_pts_drift = is->video_current_pts - av_gettime() / 1000000.0;
  971. }
  972. is->paused = !is->paused;
  973. }
  974. static double compute_target_delay(double delay, VideoState *is)
  975. {
  976. double sync_threshold, diff;
  977. /* update delay to follow master synchronisation source */
  978. if (((is->av_sync_type == AV_SYNC_AUDIO_MASTER && is->audio_st) ||
  979. is->av_sync_type == AV_SYNC_EXTERNAL_CLOCK)) {
  980. /* if video is slave, we try to correct big delays by
  981. duplicating or deleting a frame */
  982. diff = get_video_clock(is) - get_master_clock(is);
  983. /* skip or repeat frame. We take into account the
  984. delay to compute the threshold. I still don't know
  985. if it is the best guess */
  986. sync_threshold = FFMAX(AV_SYNC_THRESHOLD, delay);
  987. if (fabs(diff) < AV_NOSYNC_THRESHOLD) {
  988. if (diff <= -sync_threshold)
  989. delay = 0;
  990. else if (diff >= sync_threshold)
  991. delay = 2 * delay;
  992. }
  993. }
  994. av_dlog(NULL, "video: delay=%0.3f A-V=%f\n",
  995. delay, -diff);
  996. return delay;
  997. }
  998. static void pictq_next_picture(VideoState *is) {
  999. /* update queue size and signal for next picture */
  1000. if (++is->pictq_rindex == VIDEO_PICTURE_QUEUE_SIZE)
  1001. is->pictq_rindex = 0;
  1002. SDL_LockMutex(is->pictq_mutex);
  1003. is->pictq_size--;
  1004. SDL_CondSignal(is->pictq_cond);
  1005. SDL_UnlockMutex(is->pictq_mutex);
  1006. }
  1007. static void pictq_prev_picture(VideoState *is) {
  1008. VideoPicture *prevvp;
  1009. /* update queue size and signal for the previous picture */
  1010. prevvp = &is->pictq[(is->pictq_rindex + VIDEO_PICTURE_QUEUE_SIZE - 1) % VIDEO_PICTURE_QUEUE_SIZE];
  1011. if (prevvp->allocated && !prevvp->skip) {
  1012. SDL_LockMutex(is->pictq_mutex);
  1013. if (is->pictq_size < VIDEO_PICTURE_QUEUE_SIZE - 1) {
  1014. if (--is->pictq_rindex == -1)
  1015. is->pictq_rindex = VIDEO_PICTURE_QUEUE_SIZE - 1;
  1016. is->pictq_size++;
  1017. }
  1018. SDL_CondSignal(is->pictq_cond);
  1019. SDL_UnlockMutex(is->pictq_mutex);
  1020. }
  1021. }
  1022. static void update_video_pts(VideoState *is, double pts, int64_t pos) {
  1023. double time = av_gettime() / 1000000.0;
  1024. /* update current video pts */
  1025. is->video_current_pts = pts;
  1026. is->video_current_pts_drift = is->video_current_pts - time;
  1027. is->video_current_pos = pos;
  1028. is->frame_last_pts = pts;
  1029. }
  1030. /* called to display each frame */
  1031. static void video_refresh(void *opaque)
  1032. {
  1033. VideoState *is = opaque;
  1034. VideoPicture *vp;
  1035. double time;
  1036. SubPicture *sp, *sp2;
  1037. if (is->video_st) {
  1038. if (is->force_refresh)
  1039. pictq_prev_picture(is);
  1040. retry:
  1041. if (is->pictq_size == 0) {
  1042. SDL_LockMutex(is->pictq_mutex);
  1043. if (is->frame_last_dropped_pts != AV_NOPTS_VALUE && is->frame_last_dropped_pts > is->frame_last_pts) {
  1044. update_video_pts(is, is->frame_last_dropped_pts, is->frame_last_dropped_pos);
  1045. is->frame_last_dropped_pts = AV_NOPTS_VALUE;
  1046. }
  1047. SDL_UnlockMutex(is->pictq_mutex);
  1048. // nothing to do, no picture to display in the que
  1049. } else {
  1050. double last_duration, duration, delay;
  1051. /* dequeue the picture */
  1052. vp = &is->pictq[is->pictq_rindex];
  1053. if (vp->skip) {
  1054. pictq_next_picture(is);
  1055. goto retry;
  1056. }
  1057. if (is->paused)
  1058. goto display;
  1059. /* compute nominal last_duration */
  1060. last_duration = vp->pts - is->frame_last_pts;
  1061. if (last_duration > 0 && last_duration < 10.0) {
  1062. /* if duration of the last frame was sane, update last_duration in video state */
  1063. is->frame_last_duration = last_duration;
  1064. }
  1065. delay = compute_target_delay(is->frame_last_duration, is);
  1066. time= av_gettime()/1000000.0;
  1067. if (time < is->frame_timer + delay)
  1068. return;
  1069. if (delay > 0)
  1070. is->frame_timer += delay * FFMAX(1, floor((time-is->frame_timer) / delay));
  1071. SDL_LockMutex(is->pictq_mutex);
  1072. update_video_pts(is, vp->pts, vp->pos);
  1073. SDL_UnlockMutex(is->pictq_mutex);
  1074. if (is->pictq_size > 1) {
  1075. VideoPicture *nextvp = &is->pictq[(is->pictq_rindex + 1) % VIDEO_PICTURE_QUEUE_SIZE];
  1076. duration = nextvp->pts - vp->pts;
  1077. if((framedrop>0 || (framedrop && is->audio_st)) && time > is->frame_timer + duration){
  1078. is->frame_drops_late++;
  1079. pictq_next_picture(is);
  1080. goto retry;
  1081. }
  1082. }
  1083. if (is->subtitle_st) {
  1084. if (is->subtitle_stream_changed) {
  1085. SDL_LockMutex(is->subpq_mutex);
  1086. while (is->subpq_size) {
  1087. free_subpicture(&is->subpq[is->subpq_rindex]);
  1088. /* update queue size and signal for next picture */
  1089. if (++is->subpq_rindex == SUBPICTURE_QUEUE_SIZE)
  1090. is->subpq_rindex = 0;
  1091. is->subpq_size--;
  1092. }
  1093. is->subtitle_stream_changed = 0;
  1094. SDL_CondSignal(is->subpq_cond);
  1095. SDL_UnlockMutex(is->subpq_mutex);
  1096. } else {
  1097. if (is->subpq_size > 0) {
  1098. sp = &is->subpq[is->subpq_rindex];
  1099. if (is->subpq_size > 1)
  1100. sp2 = &is->subpq[(is->subpq_rindex + 1) % SUBPICTURE_QUEUE_SIZE];
  1101. else
  1102. sp2 = NULL;
  1103. if ((is->video_current_pts > (sp->pts + ((float) sp->sub.end_display_time / 1000)))
  1104. || (sp2 && is->video_current_pts > (sp2->pts + ((float) sp2->sub.start_display_time / 1000))))
  1105. {
  1106. free_subpicture(sp);
  1107. /* update queue size and signal for next picture */
  1108. if (++is->subpq_rindex == SUBPICTURE_QUEUE_SIZE)
  1109. is->subpq_rindex = 0;
  1110. SDL_LockMutex(is->subpq_mutex);
  1111. is->subpq_size--;
  1112. SDL_CondSignal(is->subpq_cond);
  1113. SDL_UnlockMutex(is->subpq_mutex);
  1114. }
  1115. }
  1116. }
  1117. }
  1118. display:
  1119. /* display picture */
  1120. if (!display_disable)
  1121. video_display(is);
  1122. pictq_next_picture(is);
  1123. }
  1124. } else if (is->audio_st) {
  1125. /* draw the next audio frame */
  1126. /* if only audio stream, then display the audio bars (better
  1127. than nothing, just to test the implementation */
  1128. /* display picture */
  1129. if (!display_disable)
  1130. video_display(is);
  1131. }
  1132. is->force_refresh = 0;
  1133. if (show_status) {
  1134. static int64_t last_time;
  1135. int64_t cur_time;
  1136. int aqsize, vqsize, sqsize;
  1137. double av_diff;
  1138. cur_time = av_gettime();
  1139. if (!last_time || (cur_time - last_time) >= 30000) {
  1140. aqsize = 0;
  1141. vqsize = 0;
  1142. sqsize = 0;
  1143. if (is->audio_st)
  1144. aqsize = is->audioq.size;
  1145. if (is->video_st)
  1146. vqsize = is->videoq.size;
  1147. if (is->subtitle_st)
  1148. sqsize = is->subtitleq.size;
  1149. av_diff = 0;
  1150. if (is->audio_st && is->video_st)
  1151. av_diff = get_audio_clock(is) - get_video_clock(is);
  1152. printf("%7.2f A-V:%7.3f fd=%4d aq=%5dKB vq=%5dKB sq=%5dB f=%"PRId64"/%"PRId64" \r",
  1153. get_master_clock(is),
  1154. av_diff,
  1155. is->frame_drops_early + is->frame_drops_late,
  1156. aqsize / 1024,
  1157. vqsize / 1024,
  1158. sqsize,
  1159. is->video_st ? is->video_st->codec->pts_correction_num_faulty_dts : 0,
  1160. is->video_st ? is->video_st->codec->pts_correction_num_faulty_pts : 0);
  1161. fflush(stdout);
  1162. last_time = cur_time;
  1163. }
  1164. }
  1165. }
  1166. /* allocate a picture (needs to do that in main thread to avoid
  1167. potential locking problems */
  1168. static void alloc_picture(VideoState *is)
  1169. {
  1170. VideoPicture *vp;
  1171. vp = &is->pictq[is->pictq_windex];
  1172. if (vp->bmp)
  1173. SDL_FreeYUVOverlay(vp->bmp);
  1174. #if CONFIG_AVFILTER
  1175. avfilter_unref_bufferp(&vp->picref);
  1176. #endif
  1177. video_open(is, 0);
  1178. vp->bmp = SDL_CreateYUVOverlay(vp->width, vp->height,
  1179. SDL_YV12_OVERLAY,
  1180. screen);
  1181. if (!vp->bmp || vp->bmp->pitches[0] < vp->width) {
  1182. /* SDL allocates a buffer smaller than requested if the video
  1183. * overlay hardware is unable to support the requested size. */
  1184. fprintf(stderr, "Error: the video system does not support an image\n"
  1185. "size of %dx%d pixels. Try using -lowres or -vf \"scale=w:h\"\n"
  1186. "to reduce the image size.\n", vp->width, vp->height );
  1187. do_exit(is);
  1188. }
  1189. SDL_LockMutex(is->pictq_mutex);
  1190. vp->allocated = 1;
  1191. SDL_CondSignal(is->pictq_cond);
  1192. SDL_UnlockMutex(is->pictq_mutex);
  1193. }
  1194. static int queue_picture(VideoState *is, AVFrame *src_frame, double pts1, int64_t pos)
  1195. {
  1196. VideoPicture *vp;
  1197. double frame_delay, pts = pts1;
  1198. /* compute the exact PTS for the picture if it is omitted in the stream
  1199. * pts1 is the dts of the pkt / pts of the frame */
  1200. if (pts != 0) {
  1201. /* update video clock with pts, if present */
  1202. is->video_clock = pts;
  1203. } else {
  1204. pts = is->video_clock;
  1205. }
  1206. /* update video clock for next frame */
  1207. frame_delay = av_q2d(is->video_st->codec->time_base);
  1208. /* for MPEG2, the frame can be repeated, so we update the
  1209. clock accordingly */
  1210. frame_delay += src_frame->repeat_pict * (frame_delay * 0.5);
  1211. is->video_clock += frame_delay;
  1212. #if defined(DEBUG_SYNC) && 0
  1213. printf("frame_type=%c clock=%0.3f pts=%0.3f\n",
  1214. av_get_picture_type_char(src_frame->pict_type), pts, pts1);
  1215. #endif
  1216. /* wait until we have space to put a new picture */
  1217. SDL_LockMutex(is->pictq_mutex);
  1218. /* keep the last already displayed picture in the queue */
  1219. while (is->pictq_size >= VIDEO_PICTURE_QUEUE_SIZE - 2 &&
  1220. !is->videoq.abort_request) {
  1221. SDL_CondWait(is->pictq_cond, is->pictq_mutex);
  1222. }
  1223. SDL_UnlockMutex(is->pictq_mutex);
  1224. if (is->videoq.abort_request)
  1225. return -1;
  1226. vp = &is->pictq[is->pictq_windex];
  1227. #if CONFIG_AVFILTER
  1228. vp->sample_aspect_ratio = ((AVFilterBufferRef *)src_frame->opaque)->video->sample_aspect_ratio;
  1229. #else
  1230. vp->sample_aspect_ratio = av_guess_sample_aspect_ratio(is->ic, is->video_st, src_frame);
  1231. #endif
  1232. /* alloc or resize hardware picture buffer */
  1233. if (!vp->bmp || vp->reallocate || !vp->allocated ||
  1234. vp->width != src_frame->width ||
  1235. vp->height != src_frame->height) {
  1236. SDL_Event event;
  1237. vp->allocated = 0;
  1238. vp->reallocate = 0;
  1239. vp->width = src_frame->width;
  1240. vp->height = src_frame->height;
  1241. /* the allocation must be done in the main thread to avoid
  1242. locking problems. */
  1243. event.type = FF_ALLOC_EVENT;
  1244. event.user.data1 = is;
  1245. SDL_PushEvent(&event);
  1246. /* wait until the picture is allocated */
  1247. SDL_LockMutex(is->pictq_mutex);
  1248. while (!vp->allocated && !is->videoq.abort_request) {
  1249. SDL_CondWait(is->pictq_cond, is->pictq_mutex);
  1250. }
  1251. /* if the queue is aborted, we have to pop the pending ALLOC event or wait for the allocation to complete */
  1252. if (is->videoq.abort_request && SDL_PeepEvents(&event, 1, SDL_GETEVENT, SDL_EVENTMASK(FF_ALLOC_EVENT)) != 1) {
  1253. while (!vp->allocated) {
  1254. SDL_CondWait(is->pictq_cond, is->pictq_mutex);
  1255. }
  1256. }
  1257. SDL_UnlockMutex(is->pictq_mutex);
  1258. if (is->videoq.abort_request)
  1259. return -1;
  1260. }
  1261. /* if the frame is not skipped, then display it */
  1262. if (vp->bmp) {
  1263. AVPicture pict = { { 0 } };
  1264. #if CONFIG_AVFILTER
  1265. avfilter_unref_bufferp(&vp->picref);
  1266. vp->picref = src_frame->opaque;
  1267. #endif
  1268. /* get a pointer on the bitmap */
  1269. SDL_LockYUVOverlay (vp->bmp);
  1270. pict.data[0] = vp->bmp->pixels[0];
  1271. pict.data[1] = vp->bmp->pixels[2];
  1272. pict.data[2] = vp->bmp->pixels[1];
  1273. pict.linesize[0] = vp->bmp->pitches[0];
  1274. pict.linesize[1] = vp->bmp->pitches[2];
  1275. pict.linesize[2] = vp->bmp->pitches[1];
  1276. #if CONFIG_AVFILTER
  1277. // FIXME use direct rendering
  1278. av_picture_copy(&pict, (AVPicture *)src_frame,
  1279. src_frame->format, vp->width, vp->height);
  1280. #else
  1281. sws_flags = av_get_int(sws_opts, "sws_flags", NULL);
  1282. is->img_convert_ctx = sws_getCachedContext(is->img_convert_ctx,
  1283. vp->width, vp->height, src_frame->format, vp->width, vp->height,
  1284. PIX_FMT_YUV420P, sws_flags, NULL, NULL, NULL);
  1285. if (is->img_convert_ctx == NULL) {
  1286. fprintf(stderr, "Cannot initialize the conversion context\n");
  1287. exit(1);
  1288. }
  1289. sws_scale(is->img_convert_ctx, src_frame->data, src_frame->linesize,
  1290. 0, vp->height, pict.data, pict.linesize);
  1291. #endif
  1292. /* update the bitmap content */
  1293. SDL_UnlockYUVOverlay(vp->bmp);
  1294. vp->pts = pts;
  1295. vp->pos = pos;
  1296. vp->skip = 0;
  1297. /* now we can update the picture count */
  1298. if (++is->pictq_windex == VIDEO_PICTURE_QUEUE_SIZE)
  1299. is->pictq_windex = 0;
  1300. SDL_LockMutex(is->pictq_mutex);
  1301. is->pictq_size++;
  1302. SDL_UnlockMutex(is->pictq_mutex);
  1303. }
  1304. return 0;
  1305. }
  1306. static int get_video_frame(VideoState *is, AVFrame *frame, int64_t *pts, AVPacket *pkt)
  1307. {
  1308. int got_picture, i;
  1309. if (packet_queue_get(&is->videoq, pkt, 1) < 0)
  1310. return -1;
  1311. if (pkt->data == flush_pkt.data) {
  1312. avcodec_flush_buffers(is->video_st->codec);
  1313. SDL_LockMutex(is->pictq_mutex);
  1314. // Make sure there are no long delay timers (ideally we should just flush the que but thats harder)
  1315. for (i = 0; i < VIDEO_PICTURE_QUEUE_SIZE; i++) {
  1316. is->pictq[i].skip = 1;
  1317. }
  1318. while (is->pictq_size && !is->videoq.abort_request) {
  1319. SDL_CondWait(is->pictq_cond, is->pictq_mutex);
  1320. }
  1321. is->video_current_pos = -1;
  1322. is->frame_last_pts = AV_NOPTS_VALUE;
  1323. is->frame_last_duration = 0;
  1324. is->frame_timer = (double)av_gettime() / 1000000.0;
  1325. is->frame_last_dropped_pts = AV_NOPTS_VALUE;
  1326. SDL_UnlockMutex(is->pictq_mutex);
  1327. return 0;
  1328. }
  1329. if(avcodec_decode_video2(is->video_st->codec, frame, &got_picture, pkt) < 0)
  1330. return 0;
  1331. if (got_picture) {
  1332. int ret = 1;
  1333. if (decoder_reorder_pts == -1) {
  1334. *pts = av_frame_get_best_effort_timestamp(frame);
  1335. } else if (decoder_reorder_pts) {
  1336. *pts = frame->pkt_pts;
  1337. } else {
  1338. *pts = frame->pkt_dts;
  1339. }
  1340. if (*pts == AV_NOPTS_VALUE) {
  1341. *pts = 0;
  1342. }
  1343. if (((is->av_sync_type == AV_SYNC_AUDIO_MASTER && is->audio_st) || is->av_sync_type == AV_SYNC_EXTERNAL_CLOCK) &&
  1344. (framedrop>0 || (framedrop && is->audio_st))) {
  1345. SDL_LockMutex(is->pictq_mutex);
  1346. if (is->frame_last_pts != AV_NOPTS_VALUE && *pts) {
  1347. double clockdiff = get_video_clock(is) - get_master_clock(is);
  1348. double dpts = av_q2d(is->video_st->time_base) * *pts;
  1349. double ptsdiff = dpts - is->frame_last_pts;
  1350. if (fabs(clockdiff) < AV_NOSYNC_THRESHOLD &&
  1351. ptsdiff > 0 && ptsdiff < AV_NOSYNC_THRESHOLD &&
  1352. clockdiff + ptsdiff - is->frame_last_filter_delay < 0) {
  1353. is->frame_last_dropped_pos = pkt->pos;
  1354. is->frame_last_dropped_pts = dpts;
  1355. is->frame_drops_early++;
  1356. ret = 0;
  1357. }
  1358. }
  1359. SDL_UnlockMutex(is->pictq_mutex);
  1360. }
  1361. return ret;
  1362. }
  1363. return 0;
  1364. }
  1365. #if CONFIG_AVFILTER
  1366. static int configure_filtergraph(AVFilterGraph *graph, const char *filtergraph,
  1367. AVFilterContext *source_ctx, AVFilterContext *sink_ctx)
  1368. {
  1369. int ret;
  1370. AVFilterInOut *outputs = NULL, *inputs = NULL;
  1371. if (filtergraph) {
  1372. outputs = avfilter_inout_alloc();
  1373. inputs = avfilter_inout_alloc();
  1374. if (!outputs || !inputs) {
  1375. ret = AVERROR(ENOMEM);
  1376. goto fail;
  1377. }
  1378. outputs->name = av_strdup("in");
  1379. outputs->filter_ctx = source_ctx;
  1380. outputs->pad_idx = 0;
  1381. outputs->next = NULL;
  1382. inputs->name = av_strdup("out");
  1383. inputs->filter_ctx = sink_ctx;
  1384. inputs->pad_idx = 0;
  1385. inputs->next = NULL;
  1386. if ((ret = avfilter_graph_parse(graph, filtergraph, &inputs, &outputs, NULL)) < 0)
  1387. goto fail;
  1388. } else {
  1389. if ((ret = avfilter_link(source_ctx, 0, sink_ctx, 0)) < 0)
  1390. goto fail;
  1391. }
  1392. return avfilter_graph_config(graph, NULL);
  1393. fail:
  1394. avfilter_inout_free(&outputs);
  1395. avfilter_inout_free(&inputs);
  1396. return ret;
  1397. }
  1398. static int configure_video_filters(AVFilterGraph *graph, VideoState *is, const char *vfilters)
  1399. {
  1400. static const enum PixelFormat pix_fmts[] = { PIX_FMT_YUV420P, PIX_FMT_NONE };
  1401. char sws_flags_str[128];
  1402. char buffersrc_args[256];
  1403. int ret;
  1404. AVBufferSinkParams *buffersink_params = av_buffersink_params_alloc();
  1405. AVFilterContext *filt_src = NULL, *filt_out = NULL, *filt_format, *filt_crop;
  1406. AVCodecContext *codec = is->video_st->codec;
  1407. snprintf(sws_flags_str, sizeof(sws_flags_str), "flags=%d", sws_flags);
  1408. graph->scale_sws_opts = av_strdup(sws_flags_str);
  1409. snprintf(buffersrc_args, sizeof(buffersrc_args),
  1410. "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
  1411. codec->width, codec->height, codec->pix_fmt,
  1412. is->video_st->time_base.num, is->video_st->time_base.den,
  1413. codec->sample_aspect_ratio.num, FFMAX(codec->sample_aspect_ratio.den, 1));
  1414. if ((ret = avfilter_graph_create_filter(&filt_src,
  1415. avfilter_get_by_name("buffer"),
  1416. "ffplay_buffer", buffersrc_args, NULL,
  1417. graph)) < 0)
  1418. return ret;
  1419. buffersink_params->pixel_fmts = pix_fmts;
  1420. ret = avfilter_graph_create_filter(&filt_out,
  1421. avfilter_get_by_name("ffbuffersink"),
  1422. "ffplay_buffersink", NULL, buffersink_params, graph);
  1423. av_freep(&buffersink_params);
  1424. if (ret < 0)
  1425. return ret;
  1426. /* SDL YUV code is not handling odd width/height for some driver
  1427. * combinations, therefore we crop the picture to an even width/height. */
  1428. if ((ret = avfilter_graph_create_filter(&filt_crop,
  1429. avfilter_get_by_name("crop"),
  1430. "ffplay_crop", "floor(in_w/2)*2:floor(in_h/2)*2", NULL, graph)) < 0)
  1431. return ret;
  1432. if ((ret = avfilter_graph_create_filter(&filt_format,
  1433. avfilter_get_by_name("format"),
  1434. "format", "yuv420p", NULL, graph)) < 0)
  1435. return ret;
  1436. if ((ret = avfilter_link(filt_crop, 0, filt_format, 0)) < 0)
  1437. return ret;
  1438. if ((ret = avfilter_link(filt_format, 0, filt_out, 0)) < 0)
  1439. return ret;
  1440. if ((ret = configure_filtergraph(graph, vfilters, filt_src, filt_crop)) < 0)
  1441. return ret;
  1442. is->in_video_filter = filt_src;
  1443. is->out_video_filter = filt_out;
  1444. return ret;
  1445. }
  1446. #endif /* CONFIG_AVFILTER */
  1447. static int video_thread(void *arg)
  1448. {
  1449. AVPacket pkt = { 0 };
  1450. VideoState *is = arg;
  1451. AVFrame *frame = avcodec_alloc_frame();
  1452. int64_t pts_int = AV_NOPTS_VALUE, pos = -1;
  1453. double pts;
  1454. int ret;
  1455. #if CONFIG_AVFILTER
  1456. AVCodecContext *codec = is->video_st->codec;
  1457. AVFilterGraph *graph = avfilter_graph_alloc();
  1458. AVFilterContext *filt_out = NULL, *filt_in = NULL;
  1459. int last_w = 0;
  1460. int last_h = 0;
  1461. enum PixelFormat last_format = -2;
  1462. if (codec->codec->capabilities & CODEC_CAP_DR1) {
  1463. is->use_dr1 = 1;
  1464. codec->get_buffer = codec_get_buffer;
  1465. codec->release_buffer = codec_release_buffer;
  1466. codec->opaque = &is->buffer_pool;
  1467. }
  1468. #endif
  1469. for (;;) {
  1470. #if CONFIG_AVFILTER
  1471. AVFilterBufferRef *picref;
  1472. AVRational tb;
  1473. #endif
  1474. while (is->paused && !is->videoq.abort_request)
  1475. SDL_Delay(10);
  1476. avcodec_get_frame_defaults(frame);
  1477. av_free_packet(&pkt);
  1478. ret = get_video_frame(is, frame, &pts_int, &pkt);
  1479. if (ret < 0)
  1480. goto the_end;
  1481. if (!ret)
  1482. continue;
  1483. #if CONFIG_AVFILTER
  1484. if ( last_w != is->video_st->codec->width
  1485. || last_h != is->video_st->codec->height
  1486. || last_format != is->video_st->codec->pix_fmt) {
  1487. av_log(NULL, AV_LOG_INFO, "Frame changed from size:%dx%d to size:%dx%d\n",
  1488. last_w, last_h, is->video_st->codec->width, is->video_st->codec->height);
  1489. avfilter_graph_free(&graph);
  1490. graph = avfilter_graph_alloc();
  1491. if ((ret = configure_video_filters(graph, is, vfilters)) < 0) {
  1492. SDL_Event event;
  1493. event.type = FF_QUIT_EVENT;
  1494. event.user.data1 = is;
  1495. SDL_PushEvent(&event);
  1496. av_free_packet(&pkt);
  1497. goto the_end;
  1498. }
  1499. filt_in = is->in_video_filter;
  1500. filt_out = is->out_video_filter;
  1501. last_w = is->video_st->codec->width;
  1502. last_h = is->video_st->codec->height;
  1503. last_format = is->video_st->codec->pix_fmt;
  1504. }
  1505. frame->pts = pts_int;
  1506. frame->sample_aspect_ratio = av_guess_sample_aspect_ratio(is->ic, is->video_st, frame);
  1507. if (is->use_dr1 && frame->opaque) {
  1508. FrameBuffer *buf = frame->opaque;
  1509. AVFilterBufferRef *fb = avfilter_get_video_buffer_ref_from_arrays(
  1510. frame->data, frame->linesize,
  1511. AV_PERM_READ | AV_PERM_PRESERVE,
  1512. frame->width, frame->height,
  1513. frame->format);
  1514. avfilter_copy_frame_props(fb, frame);
  1515. fb->buf->priv = buf;
  1516. fb->buf->free = filter_release_buffer;
  1517. buf->refcount++;
  1518. av_buffersrc_add_ref(filt_in, fb, AV_BUFFERSRC_FLAG_NO_COPY);
  1519. } else
  1520. av_buffersrc_write_frame(filt_in, frame);
  1521. av_free_packet(&pkt);
  1522. while (ret >= 0) {
  1523. is->frame_last_returned_time = av_gettime() / 1000000.0;
  1524. ret = av_buffersink_get_buffer_ref(filt_out, &picref, 0);
  1525. if (ret < 0) {
  1526. ret = 0;
  1527. break;
  1528. }
  1529. is->frame_last_filter_delay = av_gettime() / 1000000.0 - is->frame_last_returned_time;
  1530. if (fabs(is->frame_last_filter_delay) > AV_NOSYNC_THRESHOLD / 10.0)
  1531. is->frame_last_filter_delay = 0;
  1532. avfilter_copy_buf_props(frame, picref);
  1533. pts_int = picref->pts;
  1534. tb = filt_out->inputs[0]->time_base;
  1535. pos = picref->pos;
  1536. frame->opaque = picref;
  1537. if (av_cmp_q(tb, is->video_st->time_base)) {
  1538. av_unused int64_t pts1 = pts_int;
  1539. pts_int = av_rescale_q(pts_int, tb, is->video_st->time_base);
  1540. av_dlog(NULL, "video_thread(): "
  1541. "tb:%d/%d pts:%"PRId64" -> tb:%d/%d pts:%"PRId64"\n",
  1542. tb.num, tb.den, pts1,
  1543. is->video_st->time_base.num, is->video_st->time_base.den, pts_int);
  1544. }
  1545. pts = pts_int * av_q2d(is->video_st->time_base);
  1546. ret = queue_picture(is, frame, pts, pos);
  1547. }
  1548. #else
  1549. pts = pts_int * av_q2d(is->video_st->time_base);
  1550. ret = queue_picture(is, frame, pts, pkt.pos);
  1551. #endif
  1552. if (ret < 0)
  1553. goto the_end;
  1554. if (is->step)
  1555. stream_toggle_pause(is);
  1556. }
  1557. the_end:
  1558. avcodec_flush_buffers(is->video_st->codec);
  1559. #if CONFIG_AVFILTER
  1560. avfilter_graph_free(&graph);
  1561. #endif
  1562. av_free_packet(&pkt);
  1563. avcodec_free_frame(&frame);
  1564. return 0;
  1565. }
  1566. static int subtitle_thread(void *arg)
  1567. {
  1568. VideoState *is = arg;
  1569. SubPicture *sp;
  1570. AVPacket pkt1, *pkt = &pkt1;
  1571. int got_subtitle;
  1572. double pts;
  1573. int i, j;
  1574. int r, g, b, y, u, v, a;
  1575. for (;;) {
  1576. while (is->paused && !is->subtitleq.abort_request) {
  1577. SDL_Delay(10);
  1578. }
  1579. if (packet_queue_get(&is->subtitleq, pkt, 1) < 0)
  1580. break;
  1581. if (pkt->data == flush_pkt.data) {
  1582. avcodec_flush_buffers(is->subtitle_st->codec);
  1583. continue;
  1584. }
  1585. SDL_LockMutex(is->subpq_mutex);
  1586. while (is->subpq_size >= SUBPICTURE_QUEUE_SIZE &&
  1587. !is->subtitleq.abort_request) {
  1588. SDL_CondWait(is->subpq_cond, is->subpq_mutex);
  1589. }
  1590. SDL_UnlockMutex(is->subpq_mutex);
  1591. if (is->subtitleq.abort_request)
  1592. return 0;
  1593. sp = &is->subpq[is->subpq_windex];
  1594. /* NOTE: ipts is the PTS of the _first_ picture beginning in
  1595. this packet, if any */
  1596. pts = 0;
  1597. if (pkt->pts != AV_NOPTS_VALUE)
  1598. pts = av_q2d(is->subtitle_st->time_base) * pkt->pts;
  1599. avcodec_decode_subtitle2(is->subtitle_st->codec, &sp->sub,
  1600. &got_subtitle, pkt);
  1601. if (got_subtitle && sp->sub.format == 0) {
  1602. if (sp->sub.pts != AV_NOPTS_VALUE)
  1603. pts = sp->sub.pts / (double)AV_TIME_BASE;
  1604. sp->pts = pts;
  1605. for (i = 0; i < sp->sub.num_rects; i++)
  1606. {
  1607. for (j = 0; j < sp->sub.rects[i]->nb_colors; j++)
  1608. {
  1609. RGBA_IN(r, g, b, a, (uint32_t*)sp->sub.rects[i]->pict.data[1] + j);
  1610. y = RGB_TO_Y_CCIR(r, g, b);
  1611. u = RGB_TO_U_CCIR(r, g, b, 0);
  1612. v = RGB_TO_V_CCIR(r, g, b, 0);
  1613. YUVA_OUT((uint32_t*)sp->sub.rects[i]->pict.data[1] + j, y, u, v, a);
  1614. }
  1615. }
  1616. /* now we can update the picture count */
  1617. if (++is->subpq_windex == SUBPICTURE_QUEUE_SIZE)
  1618. is->subpq_windex = 0;
  1619. SDL_LockMutex(is->subpq_mutex);
  1620. is->subpq_size++;
  1621. SDL_UnlockMutex(is->subpq_mutex);
  1622. }
  1623. av_free_packet(pkt);
  1624. }
  1625. return 0;
  1626. }
  1627. /* copy samples for viewing in editor window */
  1628. static void update_sample_display(VideoState *is, short *samples, int samples_size)
  1629. {
  1630. int size, len;
  1631. size = samples_size / sizeof(short);
  1632. while (size > 0) {
  1633. len = SAMPLE_ARRAY_SIZE - is->sample_array_index;
  1634. if (len > size)
  1635. len = size;
  1636. memcpy(is->sample_array + is->sample_array_index, samples, len * sizeof(short));
  1637. samples += len;
  1638. is->sample_array_index += len;
  1639. if (is->sample_array_index >= SAMPLE_ARRAY_SIZE)
  1640. is->sample_array_index = 0;
  1641. size -= len;
  1642. }
  1643. }
  1644. /* return the wanted number of samples to get better sync if sync_type is video
  1645. * or external master clock */
  1646. static int synchronize_audio(VideoState *is, int nb_samples)
  1647. {
  1648. int wanted_nb_samples = nb_samples;
  1649. /* if not master, then we try to remove or add samples to correct the clock */
  1650. if (((is->av_sync_type == AV_SYNC_VIDEO_MASTER && is->video_st) ||
  1651. is->av_sync_type == AV_SYNC_EXTERNAL_CLOCK)) {
  1652. double diff, avg_diff;
  1653. int min_nb_samples, max_nb_samples;
  1654. diff = get_audio_clock(is) - get_master_clock(is);
  1655. if (diff < AV_NOSYNC_THRESHOLD) {
  1656. is->audio_diff_cum = diff + is->audio_diff_avg_coef * is->audio_diff_cum;
  1657. if (is->audio_diff_avg_count < AUDIO_DIFF_AVG_NB) {
  1658. /* not enough measures to have a correct estimate */
  1659. is->audio_diff_avg_count++;
  1660. } else {
  1661. /* estimate the A-V difference */
  1662. avg_diff = is->audio_diff_cum * (1.0 - is->audio_diff_avg_coef);
  1663. if (fabs(avg_diff) >= is->audio_diff_threshold) {
  1664. wanted_nb_samples = nb_samples + (int)(diff * is->audio_src.freq);
  1665. min_nb_samples = ((nb_samples * (100 - SAMPLE_CORRECTION_PERCENT_MAX) / 100));
  1666. max_nb_samples = ((nb_samples * (100 + SAMPLE_CORRECTION_PERCENT_MAX) / 100));
  1667. wanted_nb_samples = FFMIN(FFMAX(wanted_nb_samples, min_nb_samples), max_nb_samples);
  1668. }
  1669. av_dlog(NULL, "diff=%f adiff=%f sample_diff=%d apts=%0.3f vpts=%0.3f %f\n",
  1670. diff, avg_diff, wanted_nb_samples - nb_samples,
  1671. is->audio_clock, is->video_clock, is->audio_diff_threshold);
  1672. }
  1673. } else {
  1674. /* too big difference : may be initial PTS errors, so
  1675. reset A-V filter */
  1676. is->audio_diff_avg_count = 0;
  1677. is->audio_diff_cum = 0;
  1678. }
  1679. }
  1680. return wanted_nb_samples;
  1681. }
  1682. /* decode one audio frame and returns its uncompressed size */
  1683. static int audio_decode_frame(VideoState *is, double *pts_ptr)
  1684. {
  1685. AVPacket *pkt_temp = &is->audio_pkt_temp;
  1686. AVPacket *pkt = &is->audio_pkt;
  1687. AVCodecContext *dec = is->audio_st->codec;
  1688. int len1, len2, data_size, resampled_data_size;
  1689. int64_t dec_channel_layout;
  1690. int got_frame;
  1691. double pts;
  1692. int new_packet = 0;
  1693. int flush_complete = 0;
  1694. int wanted_nb_samples;
  1695. for (;;) {
  1696. /* NOTE: the audio packet can contain several frames */
  1697. while (pkt_temp->size > 0 || (!pkt_temp->data && new_packet)) {
  1698. if (!is->frame) {
  1699. if (!(is->frame = avcodec_alloc_frame()))
  1700. return AVERROR(ENOMEM);
  1701. } else
  1702. avcodec_get_frame_defaults(is->frame);
  1703. if (is->paused)
  1704. return -1;
  1705. if (flush_complete)
  1706. break;
  1707. new_packet = 0;
  1708. len1 = avcodec_decode_audio4(dec, is->frame, &got_frame, pkt_temp);
  1709. if (len1 < 0) {
  1710. /* if error, we skip the frame */
  1711. pkt_temp->size = 0;
  1712. break;
  1713. }
  1714. pkt_temp->data += len1;
  1715. pkt_temp->size -= len1;
  1716. if (!got_frame) {
  1717. /* stop sending empty packets if the decoder is finished */
  1718. if (!pkt_temp->data && dec->codec->capabilities & CODEC_CAP_DELAY)
  1719. flush_complete = 1;
  1720. continue;
  1721. }
  1722. data_size = av_samples_get_buffer_size(NULL, dec->channels,
  1723. is->frame->nb_samples,
  1724. dec->sample_fmt, 1);
  1725. dec_channel_layout =
  1726. (dec->channel_layout && dec->channels == av_get_channel_layout_nb_channels(dec->channel_layout)) ?
  1727. dec->channel_layout : av_get_default_channel_layout(dec->channels);
  1728. wanted_nb_samples = synchronize_audio(is, is->frame->nb_samples);
  1729. if (dec->sample_fmt != is->audio_src.fmt ||
  1730. dec_channel_layout != is->audio_src.channel_layout ||
  1731. dec->sample_rate != is->audio_src.freq ||
  1732. (wanted_nb_samples != is->frame->nb_samples && !is->swr_ctx)) {
  1733. swr_free(&is->swr_ctx);
  1734. is->swr_ctx = swr_alloc_set_opts(NULL,
  1735. is->audio_tgt.channel_layout, is->audio_tgt.fmt, is->audio_tgt.freq,
  1736. dec_channel_layout, dec->sample_fmt, dec->sample_rate,
  1737. 0, NULL);
  1738. if (!is->swr_ctx || swr_init(is->swr_ctx) < 0) {
  1739. fprintf(stderr, "Cannot create sample rate converter for conversion of %d Hz %s %d channels to %d Hz %s %d channels!\n",
  1740. dec->sample_rate, av_get_sample_fmt_name(dec->sample_fmt), dec->channels,
  1741. is->audio_tgt.freq, av_get_sample_fmt_name(is->audio_tgt.fmt), is->audio_tgt.channels);
  1742. break;
  1743. }
  1744. is->audio_src.channel_layout = dec_channel_layout;
  1745. is->audio_src.channels = dec->channels;
  1746. is->audio_src.freq = dec->sample_rate;
  1747. is->audio_src.fmt = dec->sample_fmt;
  1748. }
  1749. if (is->swr_ctx) {
  1750. const uint8_t **in = (const uint8_t **)is->frame->extended_data;
  1751. uint8_t *out[] = {is->audio_buf2};
  1752. int out_count = sizeof(is->audio_buf2) / is->audio_tgt.channels / av_get_bytes_per_sample(is->audio_tgt.fmt);
  1753. if (wanted_nb_samples != is->frame->nb_samples) {
  1754. if (swr_set_compensation(is->swr_ctx, (wanted_nb_samples - is->frame->nb_samples) * is->audio_tgt.freq / dec->sample_rate,
  1755. wanted_nb_samples * is->audio_tgt.freq / dec->sample_rate) < 0) {
  1756. fprintf(stderr, "swr_set_compensation() failed\n");
  1757. break;
  1758. }
  1759. }
  1760. len2 = swr_convert(is->swr_ctx, out, out_count, in, is->frame->nb_samples);
  1761. if (len2 < 0) {
  1762. fprintf(stderr, "swr_convert() failed\n");
  1763. break;
  1764. }
  1765. if (len2 == out_count) {
  1766. fprintf(stderr, "warning: audio buffer is probably too small\n");
  1767. swr_init(is->swr_ctx);
  1768. }
  1769. is->audio_buf = is->audio_buf2;
  1770. resampled_data_size = len2 * is->audio_tgt.channels * av_get_bytes_per_sample(is->audio_tgt.fmt);
  1771. } else {
  1772. is->audio_buf = is->frame->data[0];
  1773. resampled_data_size = data_size;
  1774. }
  1775. /* if no pts, then compute it */
  1776. pts = is->audio_clock;
  1777. *pts_ptr = pts;
  1778. is->audio_clock += (double)data_size /
  1779. (dec->channels * dec->sample_rate * av_get_bytes_per_sample(dec->sample_fmt));
  1780. #ifdef DEBUG
  1781. {
  1782. static double last_clock;
  1783. printf("audio: delay=%0.3f clock=%0.3f pts=%0.3f\n",
  1784. is->audio_clock - last_clock,
  1785. is->audio_clock, pts);
  1786. last_clock = is->audio_clock;
  1787. }
  1788. #endif
  1789. return resampled_data_size;
  1790. }
  1791. /* free the current packet */
  1792. if (pkt->data)
  1793. av_free_packet(pkt);
  1794. memset(pkt_temp, 0, sizeof(*pkt_temp));
  1795. if (is->paused || is->audioq.abort_request) {
  1796. return -1;
  1797. }
  1798. if (is->audioq.nb_packets == 0)
  1799. SDL_CondSignal(is->continue_read_thread);
  1800. /* read next packet */
  1801. if ((new_packet = packet_queue_get(&is->audioq, pkt, 1)) < 0)
  1802. return -1;
  1803. if (pkt->data == flush_pkt.data) {
  1804. avcodec_flush_buffers(dec);
  1805. flush_complete = 0;
  1806. }
  1807. *pkt_temp = *pkt;
  1808. /* if update the audio clock with the pts */
  1809. if (pkt->pts != AV_NOPTS_VALUE) {
  1810. is->audio_clock = av_q2d(is->audio_st->time_base)*pkt->pts;
  1811. }
  1812. }
  1813. }
  1814. /* prepare a new audio buffer */
  1815. static void sdl_audio_callback(void *opaque, Uint8 *stream, int len)
  1816. {
  1817. VideoState *is = opaque;
  1818. int audio_size, len1;
  1819. int bytes_per_sec;
  1820. int frame_size = av_samples_get_buffer_size(NULL, is->audio_tgt.channels, 1, is->audio_tgt.fmt, 1);
  1821. double pts;
  1822. audio_callback_time = av_gettime();
  1823. while (len > 0) {
  1824. if (is->audio_buf_index >= is->audio_buf_size) {
  1825. audio_size = audio_decode_frame(is, &pts);
  1826. if (audio_size < 0) {
  1827. /* if error, just output silence */
  1828. is->audio_buf = is->silence_buf;
  1829. is->audio_buf_size = sizeof(is->silence_buf) / frame_size * frame_size;
  1830. } else {
  1831. if (is->show_mode != SHOW_MODE_VIDEO)
  1832. update_sample_display(is, (int16_t *)is->audio_buf, audio_size);
  1833. is->audio_buf_size = audio_size;
  1834. }
  1835. is->audio_buf_index = 0;
  1836. }
  1837. len1 = is->audio_buf_size - is->audio_buf_index;
  1838. if (len1 > len)
  1839. len1 = len;
  1840. memcpy(stream, (uint8_t *)is->audio_buf + is->audio_buf_index, len1);
  1841. len -= len1;
  1842. stream += len1;
  1843. is->audio_buf_index += len1;
  1844. }
  1845. bytes_per_sec = is->audio_tgt.freq * is->audio_tgt.channels * av_get_bytes_per_sample(is->audio_tgt.fmt);
  1846. is->audio_write_buf_size = is->audio_buf_size - is->audio_buf_index;
  1847. /* Let's assume the audio driver that is used by SDL has two periods. */
  1848. is->audio_current_pts = is->audio_clock - (double)(2 * is->audio_hw_buf_size + is->audio_write_buf_size) / bytes_per_sec;
  1849. is->audio_current_pts_drift = is->audio_current_pts - audio_callback_time / 1000000.0;
  1850. }
  1851. static int audio_open(void *opaque, int64_t wanted_channel_layout, int wanted_nb_channels, int wanted_sample_rate, struct AudioParams *audio_hw_params)
  1852. {
  1853. SDL_AudioSpec wanted_spec, spec;
  1854. const char *env;
  1855. const int next_nb_channels[] = {0, 0, 1, 6, 2, 6, 4, 6};
  1856. env = SDL_getenv("SDL_AUDIO_CHANNELS");
  1857. if (env) {
  1858. wanted_nb_channels = atoi(env);
  1859. wanted_channel_layout = av_get_default_channel_layout(wanted_nb_channels);
  1860. }
  1861. if (!wanted_channel_layout || wanted_nb_channels != av_get_channel_layout_nb_channels(wanted_channel_layout)) {
  1862. wanted_channel_layout = av_get_default_channel_layout(wanted_nb_channels);
  1863. wanted_channel_layout &= ~AV_CH_LAYOUT_STEREO_DOWNMIX;
  1864. }
  1865. wanted_spec.channels = av_get_channel_layout_nb_channels(wanted_channel_layout);
  1866. wanted_spec.freq = wanted_sample_rate;
  1867. if (wanted_spec.freq <= 0 || wanted_spec.channels <= 0) {
  1868. fprintf(stderr, "Invalid sample rate or channel count!\n");
  1869. return -1;
  1870. }
  1871. wanted_spec.format = AUDIO_S16SYS;
  1872. wanted_spec.silence = 0;
  1873. wanted_spec.samples = SDL_AUDIO_BUFFER_SIZE;
  1874. wanted_spec.callback = sdl_audio_callback;
  1875. wanted_spec.userdata = opaque;
  1876. while (SDL_OpenAudio(&wanted_spec, &spec) < 0) {
  1877. fprintf(stderr, "SDL_OpenAudio (%d channels): %s\n", wanted_spec.channels, SDL_GetError());
  1878. wanted_spec.channels = next_nb_channels[FFMIN(7, wanted_spec.channels)];
  1879. if (!wanted_spec.channels) {
  1880. fprintf(stderr, "No more channel combinations to try, audio open failed\n");
  1881. return -1;
  1882. }
  1883. wanted_channel_layout = av_get_default_channel_layout(wanted_spec.channels);
  1884. }
  1885. if (spec.format != AUDIO_S16SYS) {
  1886. fprintf(stderr, "SDL advised audio format %d is not supported!\n", spec.format);
  1887. return -1;
  1888. }
  1889. if (spec.channels != wanted_spec.channels) {
  1890. wanted_channel_layout = av_get_default_channel_layout(spec.channels);
  1891. if (!wanted_channel_layout) {
  1892. fprintf(stderr, "SDL advised channel count %d is not supported!\n", spec.channels);
  1893. return -1;
  1894. }
  1895. }
  1896. audio_hw_params->fmt = AV_SAMPLE_FMT_S16;
  1897. audio_hw_params->freq = spec.freq;
  1898. audio_hw_params->channel_layout = wanted_channel_layout;
  1899. audio_hw_params->channels = spec.channels;
  1900. return spec.size;
  1901. }
  1902. /* open a given stream. Return 0 if OK */
  1903. static int stream_component_open(VideoState *is, int stream_index)
  1904. {
  1905. AVFormatContext *ic = is->ic;
  1906. AVCodecContext *avctx;
  1907. AVCodec *codec;
  1908. AVDictionary *opts;
  1909. AVDictionaryEntry *t = NULL;
  1910. if (stream_index < 0 || stream_index >= ic->nb_streams)
  1911. return -1;
  1912. avctx = ic->streams[stream_index]->codec;
  1913. codec = avcodec_find_decoder(avctx->codec_id);
  1914. opts = filter_codec_opts(codec_opts, avctx->codec_id, ic, ic->streams[stream_index], codec);
  1915. switch(avctx->codec_type){
  1916. case AVMEDIA_TYPE_AUDIO : is->last_audio_stream = stream_index; if(audio_codec_name ) codec= avcodec_find_decoder_by_name( audio_codec_name); break;
  1917. case AVMEDIA_TYPE_SUBTITLE: is->last_subtitle_stream = stream_index; if(subtitle_codec_name) codec= avcodec_find_decoder_by_name(subtitle_codec_name); break;
  1918. case AVMEDIA_TYPE_VIDEO : is->last_video_stream = stream_index; if(video_codec_name ) codec= avcodec_find_decoder_by_name( video_codec_name); break;
  1919. }
  1920. if (!codec)
  1921. return -1;
  1922. avctx->workaround_bugs = workaround_bugs;
  1923. avctx->lowres = lowres;
  1924. if(avctx->lowres > codec->max_lowres){
  1925. av_log(avctx, AV_LOG_WARNING, "The maximum value for lowres supported by the decoder is %d\n",
  1926. codec->max_lowres);
  1927. avctx->lowres= codec->max_lowres;
  1928. }
  1929. avctx->idct_algo = idct;
  1930. avctx->skip_frame = skip_frame;
  1931. avctx->skip_idct = skip_idct;
  1932. avctx->skip_loop_filter = skip_loop_filter;
  1933. avctx->error_concealment = error_concealment;
  1934. if(avctx->lowres) avctx->flags |= CODEC_FLAG_EMU_EDGE;
  1935. if (fast) avctx->flags2 |= CODEC_FLAG2_FAST;
  1936. if(codec->capabilities & CODEC_CAP_DR1)
  1937. avctx->flags |= CODEC_FLAG_EMU_EDGE;
  1938. if (!av_dict_get(opts, "threads", NULL, 0))
  1939. av_dict_set(&opts, "threads", "auto", 0);
  1940. if (!codec ||
  1941. avcodec_open2(avctx, codec, &opts) < 0)
  1942. return -1;
  1943. if ((t = av_dict_get(opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
  1944. av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
  1945. return AVERROR_OPTION_NOT_FOUND;
  1946. }
  1947. /* prepare audio output */
  1948. if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
  1949. int audio_hw_buf_size = audio_open(is, avctx->channel_layout, avctx->channels, avctx->sample_rate, &is->audio_src);
  1950. if (audio_hw_buf_size < 0)
  1951. return -1;
  1952. is->audio_hw_buf_size = audio_hw_buf_size;
  1953. is->audio_tgt = is->audio_src;
  1954. }
  1955. ic->streams[stream_index]->discard = AVDISCARD_DEFAULT;
  1956. switch (avctx->codec_type) {
  1957. case AVMEDIA_TYPE_AUDIO:
  1958. is->audio_stream = stream_index;
  1959. is->audio_st = ic->streams[stream_index];
  1960. is->audio_buf_size = 0;
  1961. is->audio_buf_index = 0;
  1962. /* init averaging filter */
  1963. is->audio_diff_avg_coef = exp(log(0.01) / AUDIO_DIFF_AVG_NB);
  1964. is->audio_diff_avg_count = 0;
  1965. /* since we do not have a precise anough audio fifo fullness,
  1966. we correct audio sync only if larger than this threshold */
  1967. is->audio_diff_threshold = 2.0 * is->audio_hw_buf_size / av_samples_get_buffer_size(NULL, is->audio_tgt.channels, is->audio_tgt.freq, is->audio_tgt.fmt, 1);
  1968. memset(&is->audio_pkt, 0, sizeof(is->audio_pkt));
  1969. memset(&is->audio_pkt_temp, 0, sizeof(is->audio_pkt_temp));
  1970. packet_queue_start(&is->audioq);
  1971. SDL_PauseAudio(0);
  1972. break;
  1973. case AVMEDIA_TYPE_VIDEO:
  1974. is->video_stream = stream_index;
  1975. is->video_st = ic->streams[stream_index];
  1976. packet_queue_start(&is->videoq);
  1977. is->video_tid = SDL_CreateThread(video_thread, is);
  1978. break;
  1979. case AVMEDIA_TYPE_SUBTITLE:
  1980. is->subtitle_stream = stream_index;
  1981. is->subtitle_st = ic->streams[stream_index];
  1982. packet_queue_start(&is->subtitleq);
  1983. is->subtitle_tid = SDL_CreateThread(subtitle_thread, is);
  1984. break;
  1985. default:
  1986. break;
  1987. }
  1988. return 0;
  1989. }
  1990. static void stream_component_close(VideoState *is, int stream_index)
  1991. {
  1992. AVFormatContext *ic = is->ic;
  1993. AVCodecContext *avctx;
  1994. if (stream_index < 0 || stream_index >= ic->nb_streams)
  1995. return;
  1996. avctx = ic->streams[stream_index]->codec;
  1997. switch (avctx->codec_type) {
  1998. case AVMEDIA_TYPE_AUDIO:
  1999. packet_queue_abort(&is->audioq);
  2000. SDL_CloseAudio();
  2001. packet_queue_flush(&is->audioq);
  2002. av_free_packet(&is->audio_pkt);
  2003. swr_free(&is->swr_ctx);
  2004. av_freep(&is->audio_buf1);
  2005. is->audio_buf = NULL;
  2006. avcodec_free_frame(&is->frame);
  2007. if (is->rdft) {
  2008. av_rdft_end(is->rdft);
  2009. av_freep(&is->rdft_data);
  2010. is->rdft = NULL;
  2011. is->rdft_bits = 0;
  2012. }
  2013. break;
  2014. case AVMEDIA_TYPE_VIDEO:
  2015. packet_queue_abort(&is->videoq);
  2016. /* note: we also signal this mutex to make sure we deblock the
  2017. video thread in all cases */
  2018. SDL_LockMutex(is->pictq_mutex);
  2019. SDL_CondSignal(is->pictq_cond);
  2020. SDL_UnlockMutex(is->pictq_mutex);
  2021. SDL_WaitThread(is->video_tid, NULL);
  2022. packet_queue_flush(&is->videoq);
  2023. break;
  2024. case AVMEDIA_TYPE_SUBTITLE:
  2025. packet_queue_abort(&is->subtitleq);
  2026. /* note: we also signal this mutex to make sure we deblock the
  2027. video thread in all cases */
  2028. SDL_LockMutex(is->subpq_mutex);
  2029. is->subtitle_stream_changed = 1;
  2030. SDL_CondSignal(is->subpq_cond);
  2031. SDL_UnlockMutex(is->subpq_mutex);
  2032. SDL_WaitThread(is->subtitle_tid, NULL);
  2033. packet_queue_flush(&is->subtitleq);
  2034. break;
  2035. default:
  2036. break;
  2037. }
  2038. ic->streams[stream_index]->discard = AVDISCARD_ALL;
  2039. avcodec_close(avctx);
  2040. #if CONFIG_AVFILTER
  2041. free_buffer_pool(&is->buffer_pool);
  2042. #endif
  2043. switch (avctx->codec_type) {
  2044. case AVMEDIA_TYPE_AUDIO:
  2045. is->audio_st = NULL;
  2046. is->audio_stream = -1;
  2047. break;
  2048. case AVMEDIA_TYPE_VIDEO:
  2049. is->video_st = NULL;
  2050. is->video_stream = -1;
  2051. break;
  2052. case AVMEDIA_TYPE_SUBTITLE:
  2053. is->subtitle_st = NULL;
  2054. is->subtitle_stream = -1;
  2055. break;
  2056. default:
  2057. break;
  2058. }
  2059. }
  2060. static int decode_interrupt_cb(void *ctx)
  2061. {
  2062. VideoState *is = ctx;
  2063. return is->abort_request;
  2064. }
  2065. /* this thread gets the stream from the disk or the network */
  2066. static int read_thread(void *arg)
  2067. {
  2068. VideoState *is = arg;
  2069. AVFormatContext *ic = NULL;
  2070. int err, i, ret;
  2071. int st_index[AVMEDIA_TYPE_NB];
  2072. AVPacket pkt1, *pkt = &pkt1;
  2073. int eof = 0;
  2074. int pkt_in_play_range = 0;
  2075. AVDictionaryEntry *t;
  2076. AVDictionary **opts;
  2077. int orig_nb_streams;
  2078. SDL_mutex *wait_mutex = SDL_CreateMutex();
  2079. memset(st_index, -1, sizeof(st_index));
  2080. is->last_video_stream = is->video_stream = -1;
  2081. is->last_audio_stream = is->audio_stream = -1;
  2082. is->last_subtitle_stream = is->subtitle_stream = -1;
  2083. ic = avformat_alloc_context();
  2084. ic->interrupt_callback.callback = decode_interrupt_cb;
  2085. ic->interrupt_callback.opaque = is;
  2086. err = avformat_open_input(&ic, is->filename, is->iformat, &format_opts);
  2087. if (err < 0) {
  2088. print_error(is->filename, err);
  2089. ret = -1;
  2090. goto fail;
  2091. }
  2092. if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
  2093. av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
  2094. ret = AVERROR_OPTION_NOT_FOUND;
  2095. goto fail;
  2096. }
  2097. is->ic = ic;
  2098. if (genpts)
  2099. ic->flags |= AVFMT_FLAG_GENPTS;
  2100. opts = setup_find_stream_info_opts(ic, codec_opts);
  2101. orig_nb_streams = ic->nb_streams;
  2102. err = avformat_find_stream_info(ic, opts);
  2103. if (err < 0) {
  2104. fprintf(stderr, "%s: could not find codec parameters\n", is->filename);
  2105. ret = -1;
  2106. goto fail;
  2107. }
  2108. for (i = 0; i < orig_nb_streams; i++)
  2109. av_dict_free(&opts[i]);
  2110. av_freep(&opts);
  2111. if (ic->pb)
  2112. ic->pb->eof_reached = 0; // FIXME hack, ffplay maybe should not use url_feof() to test for the end
  2113. if (seek_by_bytes < 0)
  2114. seek_by_bytes = !!(ic->iformat->flags & AVFMT_TS_DISCONT);
  2115. /* if seeking requested, we execute it */
  2116. if (start_time != AV_NOPTS_VALUE) {
  2117. int64_t timestamp;
  2118. timestamp = start_time;
  2119. /* add the stream start time */
  2120. if (ic->start_time != AV_NOPTS_VALUE)
  2121. timestamp += ic->start_time;
  2122. ret = avformat_seek_file(ic, -1, INT64_MIN, timestamp, INT64_MAX, 0);
  2123. if (ret < 0) {
  2124. fprintf(stderr, "%s: could not seek to position %0.3f\n",
  2125. is->filename, (double)timestamp / AV_TIME_BASE);
  2126. }
  2127. }
  2128. for (i = 0; i < ic->nb_streams; i++)
  2129. ic->streams[i]->discard = AVDISCARD_ALL;
  2130. if (!video_disable)
  2131. st_index[AVMEDIA_TYPE_VIDEO] =
  2132. av_find_best_stream(ic, AVMEDIA_TYPE_VIDEO,
  2133. wanted_stream[AVMEDIA_TYPE_VIDEO], -1, NULL, 0);
  2134. if (!audio_disable)
  2135. st_index[AVMEDIA_TYPE_AUDIO] =
  2136. av_find_best_stream(ic, AVMEDIA_TYPE_AUDIO,
  2137. wanted_stream[AVMEDIA_TYPE_AUDIO],
  2138. st_index[AVMEDIA_TYPE_VIDEO],
  2139. NULL, 0);
  2140. if (!video_disable)
  2141. st_index[AVMEDIA_TYPE_SUBTITLE] =
  2142. av_find_best_stream(ic, AVMEDIA_TYPE_SUBTITLE,
  2143. wanted_stream[AVMEDIA_TYPE_SUBTITLE],
  2144. (st_index[AVMEDIA_TYPE_AUDIO] >= 0 ?
  2145. st_index[AVMEDIA_TYPE_AUDIO] :
  2146. st_index[AVMEDIA_TYPE_VIDEO]),
  2147. NULL, 0);
  2148. if (show_status) {
  2149. av_dump_format(ic, 0, is->filename, 0);
  2150. }
  2151. is->show_mode = show_mode;
  2152. /* open the streams */
  2153. if (st_index[AVMEDIA_TYPE_AUDIO] >= 0) {
  2154. stream_component_open(is, st_index[AVMEDIA_TYPE_AUDIO]);
  2155. }
  2156. ret = -1;
  2157. if (st_index[AVMEDIA_TYPE_VIDEO] >= 0) {
  2158. ret = stream_component_open(is, st_index[AVMEDIA_TYPE_VIDEO]);
  2159. }
  2160. is->refresh_tid = SDL_CreateThread(refresh_thread, is);
  2161. if (is->show_mode == SHOW_MODE_NONE)
  2162. is->show_mode = ret >= 0 ? SHOW_MODE_VIDEO : SHOW_MODE_RDFT;
  2163. if (st_index[AVMEDIA_TYPE_SUBTITLE] >= 0) {
  2164. stream_component_open(is, st_index[AVMEDIA_TYPE_SUBTITLE]);
  2165. }
  2166. if (is->video_stream < 0 && is->audio_stream < 0) {
  2167. fprintf(stderr, "%s: could not open codecs\n", is->filename);
  2168. ret = -1;
  2169. goto fail;
  2170. }
  2171. for (;;) {
  2172. if (is->abort_request)
  2173. break;
  2174. if (is->paused != is->last_paused) {
  2175. is->last_paused = is->paused;
  2176. if (is->paused)
  2177. is->read_pause_return = av_read_pause(ic);
  2178. else
  2179. av_read_play(ic);
  2180. }
  2181. #if CONFIG_RTSP_DEMUXER || CONFIG_MMSH_PROTOCOL
  2182. if (is->paused &&
  2183. (!strcmp(ic->iformat->name, "rtsp") ||
  2184. (ic->pb && !strncmp(input_filename, "mmsh:", 5)))) {
  2185. /* wait 10 ms to avoid trying to get another packet */
  2186. /* XXX: horrible */
  2187. SDL_Delay(10);
  2188. continue;
  2189. }
  2190. #endif
  2191. if (is->seek_req) {
  2192. int64_t seek_target = is->seek_pos;
  2193. int64_t seek_min = is->seek_rel > 0 ? seek_target - is->seek_rel + 2: INT64_MIN;
  2194. int64_t seek_max = is->seek_rel < 0 ? seek_target - is->seek_rel - 2: INT64_MAX;
  2195. // FIXME the +-2 is due to rounding being not done in the correct direction in generation
  2196. // of the seek_pos/seek_rel variables
  2197. ret = avformat_seek_file(is->ic, -1, seek_min, seek_target, seek_max, is->seek_flags);
  2198. if (ret < 0) {
  2199. fprintf(stderr, "%s: error while seeking\n", is->ic->filename);
  2200. } else {
  2201. if (is->audio_stream >= 0) {
  2202. packet_queue_flush(&is->audioq);
  2203. packet_queue_put(&is->audioq, &flush_pkt);
  2204. }
  2205. if (is->subtitle_stream >= 0) {
  2206. packet_queue_flush(&is->subtitleq);
  2207. packet_queue_put(&is->subtitleq, &flush_pkt);
  2208. }
  2209. if (is->video_stream >= 0) {
  2210. packet_queue_flush(&is->videoq);
  2211. packet_queue_put(&is->videoq, &flush_pkt);
  2212. }
  2213. }
  2214. is->seek_req = 0;
  2215. eof = 0;
  2216. }
  2217. if (is->que_attachments_req) {
  2218. avformat_queue_attached_pictures(ic);
  2219. is->que_attachments_req = 0;
  2220. }
  2221. /* if the queue are full, no need to read more */
  2222. if (!infinite_buffer &&
  2223. (is->audioq.size + is->videoq.size + is->subtitleq.size > MAX_QUEUE_SIZE
  2224. || ( (is->audioq .nb_packets > MIN_FRAMES || is->audio_stream < 0 || is->audioq.abort_request)
  2225. && (is->videoq .nb_packets > MIN_FRAMES || is->video_stream < 0 || is->videoq.abort_request)
  2226. && (is->subtitleq.nb_packets > MIN_FRAMES || is->subtitle_stream < 0 || is->subtitleq.abort_request)))) {
  2227. /* wait 10 ms */
  2228. SDL_LockMutex(wait_mutex);
  2229. SDL_CondWaitTimeout(is->continue_read_thread, wait_mutex, 10);
  2230. SDL_UnlockMutex(wait_mutex);
  2231. continue;
  2232. }
  2233. if (eof) {
  2234. if (is->video_stream >= 0) {
  2235. av_init_packet(pkt);
  2236. pkt->data = NULL;
  2237. pkt->size = 0;
  2238. pkt->stream_index = is->video_stream;
  2239. packet_queue_put(&is->videoq, pkt);
  2240. }
  2241. if (is->audio_stream >= 0 &&
  2242. is->audio_st->codec->codec->capabilities & CODEC_CAP_DELAY) {
  2243. av_init_packet(pkt);
  2244. pkt->data = NULL;
  2245. pkt->size = 0;
  2246. pkt->stream_index = is->audio_stream;
  2247. packet_queue_put(&is->audioq, pkt);
  2248. }
  2249. SDL_Delay(10);
  2250. if (is->audioq.size + is->videoq.size + is->subtitleq.size == 0) {
  2251. if (loop != 1 && (!loop || --loop)) {
  2252. stream_seek(is, start_time != AV_NOPTS_VALUE ? start_time : 0, 0, 0);
  2253. } else if (autoexit) {
  2254. ret = AVERROR_EOF;
  2255. goto fail;
  2256. }
  2257. }
  2258. eof=0;
  2259. continue;
  2260. }
  2261. ret = av_read_frame(ic, pkt);
  2262. if (ret < 0) {
  2263. if (ret == AVERROR_EOF || url_feof(ic->pb))
  2264. eof = 1;
  2265. if (ic->pb && ic->pb->error)
  2266. break;
  2267. SDL_LockMutex(wait_mutex);
  2268. SDL_CondWaitTimeout(is->continue_read_thread, wait_mutex, 10);
  2269. SDL_UnlockMutex(wait_mutex);
  2270. continue;
  2271. }
  2272. /* check if packet is in play range specified by user, then queue, otherwise discard */
  2273. pkt_in_play_range = duration == AV_NOPTS_VALUE ||
  2274. (pkt->pts - ic->streams[pkt->stream_index]->start_time) *
  2275. av_q2d(ic->streams[pkt->stream_index]->time_base) -
  2276. (double)(start_time != AV_NOPTS_VALUE ? start_time : 0) / 1000000
  2277. <= ((double)duration / 1000000);
  2278. if (pkt->stream_index == is->audio_stream && pkt_in_play_range) {
  2279. packet_queue_put(&is->audioq, pkt);
  2280. } else if (pkt->stream_index == is->video_stream && pkt_in_play_range) {
  2281. packet_queue_put(&is->videoq, pkt);
  2282. } else if (pkt->stream_index == is->subtitle_stream && pkt_in_play_range) {
  2283. packet_queue_put(&is->subtitleq, pkt);
  2284. } else {
  2285. av_free_packet(pkt);
  2286. }
  2287. }
  2288. /* wait until the end */
  2289. while (!is->abort_request) {
  2290. SDL_Delay(100);
  2291. }
  2292. ret = 0;
  2293. fail:
  2294. /* close each stream */
  2295. if (is->audio_stream >= 0)
  2296. stream_component_close(is, is->audio_stream);
  2297. if (is->video_stream >= 0)
  2298. stream_component_close(is, is->video_stream);
  2299. if (is->subtitle_stream >= 0)
  2300. stream_component_close(is, is->subtitle_stream);
  2301. if (is->ic) {
  2302. avformat_close_input(&is->ic);
  2303. }
  2304. if (ret != 0) {
  2305. SDL_Event event;
  2306. event.type = FF_QUIT_EVENT;
  2307. event.user.data1 = is;
  2308. SDL_PushEvent(&event);
  2309. }
  2310. SDL_DestroyMutex(wait_mutex);
  2311. return 0;
  2312. }
  2313. static VideoState *stream_open(const char *filename, AVInputFormat *iformat)
  2314. {
  2315. VideoState *is;
  2316. is = av_mallocz(sizeof(VideoState));
  2317. if (!is)
  2318. return NULL;
  2319. av_strlcpy(is->filename, filename, sizeof(is->filename));
  2320. is->iformat = iformat;
  2321. is->ytop = 0;
  2322. is->xleft = 0;
  2323. /* start video display */
  2324. is->pictq_mutex = SDL_CreateMutex();
  2325. is->pictq_cond = SDL_CreateCond();
  2326. is->subpq_mutex = SDL_CreateMutex();
  2327. is->subpq_cond = SDL_CreateCond();
  2328. packet_queue_init(&is->videoq);
  2329. packet_queue_init(&is->audioq);
  2330. packet_queue_init(&is->subtitleq);
  2331. is->continue_read_thread = SDL_CreateCond();
  2332. is->av_sync_type = av_sync_type;
  2333. is->read_tid = SDL_CreateThread(read_thread, is);
  2334. if (!is->read_tid) {
  2335. av_free(is);
  2336. return NULL;
  2337. }
  2338. return is;
  2339. }
  2340. static void stream_cycle_channel(VideoState *is, int codec_type)
  2341. {
  2342. AVFormatContext *ic = is->ic;
  2343. int start_index, stream_index;
  2344. int old_index;
  2345. AVStream *st;
  2346. if (codec_type == AVMEDIA_TYPE_VIDEO) {
  2347. start_index = is->last_video_stream;
  2348. old_index = is->video_stream;
  2349. } else if (codec_type == AVMEDIA_TYPE_AUDIO) {
  2350. start_index = is->last_audio_stream;
  2351. old_index = is->audio_stream;
  2352. } else {
  2353. start_index = is->last_subtitle_stream;
  2354. old_index = is->subtitle_stream;
  2355. }
  2356. stream_index = start_index;
  2357. for (;;) {
  2358. if (++stream_index >= is->ic->nb_streams)
  2359. {
  2360. if (codec_type == AVMEDIA_TYPE_SUBTITLE)
  2361. {
  2362. stream_index = -1;
  2363. is->last_subtitle_stream = -1;
  2364. goto the_end;
  2365. }
  2366. if (start_index == -1)
  2367. return;
  2368. stream_index = 0;
  2369. }
  2370. if (stream_index == start_index)
  2371. return;
  2372. st = ic->streams[stream_index];
  2373. if (st->codec->codec_type == codec_type) {
  2374. /* check that parameters are OK */
  2375. switch (codec_type) {
  2376. case AVMEDIA_TYPE_AUDIO:
  2377. if (st->codec->sample_rate != 0 &&
  2378. st->codec->channels != 0)
  2379. goto the_end;
  2380. break;
  2381. case AVMEDIA_TYPE_VIDEO:
  2382. case AVMEDIA_TYPE_SUBTITLE:
  2383. goto the_end;
  2384. default:
  2385. break;
  2386. }
  2387. }
  2388. }
  2389. the_end:
  2390. stream_component_close(is, old_index);
  2391. stream_component_open(is, stream_index);
  2392. if (codec_type == AVMEDIA_TYPE_VIDEO)
  2393. is->que_attachments_req = 1;
  2394. }
  2395. static void toggle_full_screen(VideoState *is)
  2396. {
  2397. #if defined(__APPLE__) && SDL_VERSION_ATLEAST(1, 2, 14)
  2398. /* OS X needs to reallocate the SDL overlays */
  2399. int i;
  2400. for (i = 0; i < VIDEO_PICTURE_QUEUE_SIZE; i++)
  2401. is->pictq[i].reallocate = 1;
  2402. #endif
  2403. is_full_screen = !is_full_screen;
  2404. video_open(is, 1);
  2405. }
  2406. static void toggle_pause(VideoState *is)
  2407. {
  2408. stream_toggle_pause(is);
  2409. is->step = 0;
  2410. }
  2411. static void step_to_next_frame(VideoState *is)
  2412. {
  2413. /* if the stream is paused unpause it, then step */
  2414. if (is->paused)
  2415. stream_toggle_pause(is);
  2416. is->step = 1;
  2417. }
  2418. static void toggle_audio_display(VideoState *is)
  2419. {
  2420. int bgcolor = SDL_MapRGB(screen->format, 0x00, 0x00, 0x00);
  2421. is->show_mode = (is->show_mode + 1) % SHOW_MODE_NB;
  2422. fill_rectangle(screen,
  2423. is->xleft, is->ytop, is->width, is->height,
  2424. bgcolor);
  2425. SDL_UpdateRect(screen, is->xleft, is->ytop, is->width, is->height);
  2426. }
  2427. /* handle an event sent by the GUI */
  2428. static void event_loop(VideoState *cur_stream)
  2429. {
  2430. SDL_Event event;
  2431. double incr, pos, frac;
  2432. for (;;) {
  2433. double x;
  2434. SDL_WaitEvent(&event);
  2435. switch (event.type) {
  2436. case SDL_KEYDOWN:
  2437. if (exit_on_keydown) {
  2438. do_exit(cur_stream);
  2439. break;
  2440. }
  2441. switch (event.key.keysym.sym) {
  2442. case SDLK_ESCAPE:
  2443. case SDLK_q:
  2444. do_exit(cur_stream);
  2445. break;
  2446. case SDLK_f:
  2447. toggle_full_screen(cur_stream);
  2448. cur_stream->force_refresh = 1;
  2449. break;
  2450. case SDLK_p:
  2451. case SDLK_SPACE:
  2452. toggle_pause(cur_stream);
  2453. break;
  2454. case SDLK_s: // S: Step to next frame
  2455. step_to_next_frame(cur_stream);
  2456. break;
  2457. case SDLK_a:
  2458. stream_cycle_channel(cur_stream, AVMEDIA_TYPE_AUDIO);
  2459. break;
  2460. case SDLK_v:
  2461. stream_cycle_channel(cur_stream, AVMEDIA_TYPE_VIDEO);
  2462. break;
  2463. case SDLK_t:
  2464. stream_cycle_channel(cur_stream, AVMEDIA_TYPE_SUBTITLE);
  2465. break;
  2466. case SDLK_w:
  2467. toggle_audio_display(cur_stream);
  2468. cur_stream->force_refresh = 1;
  2469. break;
  2470. case SDLK_PAGEUP:
  2471. incr = 600.0;
  2472. goto do_seek;
  2473. case SDLK_PAGEDOWN:
  2474. incr = -600.0;
  2475. goto do_seek;
  2476. case SDLK_LEFT:
  2477. incr = -10.0;
  2478. goto do_seek;
  2479. case SDLK_RIGHT:
  2480. incr = 10.0;
  2481. goto do_seek;
  2482. case SDLK_UP:
  2483. incr = 60.0;
  2484. goto do_seek;
  2485. case SDLK_DOWN:
  2486. incr = -60.0;
  2487. do_seek:
  2488. if (seek_by_bytes) {
  2489. if (cur_stream->video_stream >= 0 && cur_stream->video_current_pos >= 0) {
  2490. pos = cur_stream->video_current_pos;
  2491. } else if (cur_stream->audio_stream >= 0 && cur_stream->audio_pkt.pos >= 0) {
  2492. pos = cur_stream->audio_pkt.pos;
  2493. } else
  2494. pos = avio_tell(cur_stream->ic->pb);
  2495. if (cur_stream->ic->bit_rate)
  2496. incr *= cur_stream->ic->bit_rate / 8.0;
  2497. else
  2498. incr *= 180000.0;
  2499. pos += incr;
  2500. stream_seek(cur_stream, pos, incr, 1);
  2501. } else {
  2502. pos = get_master_clock(cur_stream);
  2503. pos += incr;
  2504. stream_seek(cur_stream, (int64_t)(pos * AV_TIME_BASE), (int64_t)(incr * AV_TIME_BASE), 0);
  2505. }
  2506. break;
  2507. default:
  2508. break;
  2509. }
  2510. break;
  2511. case SDL_VIDEOEXPOSE:
  2512. cur_stream->force_refresh = 1;
  2513. break;
  2514. case SDL_MOUSEBUTTONDOWN:
  2515. if (exit_on_mousedown) {
  2516. do_exit(cur_stream);
  2517. break;
  2518. }
  2519. case SDL_MOUSEMOTION:
  2520. if (event.type == SDL_MOUSEBUTTONDOWN) {
  2521. x = event.button.x;
  2522. } else {
  2523. if (event.motion.state != SDL_PRESSED)
  2524. break;
  2525. x = event.motion.x;
  2526. }
  2527. if (seek_by_bytes || cur_stream->ic->duration <= 0) {
  2528. uint64_t size = avio_size(cur_stream->ic->pb);
  2529. stream_seek(cur_stream, size*x/cur_stream->width, 0, 1);
  2530. } else {
  2531. int64_t ts;
  2532. int ns, hh, mm, ss;
  2533. int tns, thh, tmm, tss;
  2534. tns = cur_stream->ic->duration / 1000000LL;
  2535. thh = tns / 3600;
  2536. tmm = (tns % 3600) / 60;
  2537. tss = (tns % 60);
  2538. frac = x / cur_stream->width;
  2539. ns = frac * tns;
  2540. hh = ns / 3600;
  2541. mm = (ns % 3600) / 60;
  2542. ss = (ns % 60);
  2543. fprintf(stderr, "Seek to %2.0f%% (%2d:%02d:%02d) of total duration (%2d:%02d:%02d) \n", frac*100,
  2544. hh, mm, ss, thh, tmm, tss);
  2545. ts = frac * cur_stream->ic->duration;
  2546. if (cur_stream->ic->start_time != AV_NOPTS_VALUE)
  2547. ts += cur_stream->ic->start_time;
  2548. stream_seek(cur_stream, ts, 0, 0);
  2549. }
  2550. break;
  2551. case SDL_VIDEORESIZE:
  2552. screen = SDL_SetVideoMode(event.resize.w, event.resize.h, 0,
  2553. SDL_HWSURFACE|SDL_RESIZABLE|SDL_ASYNCBLIT|SDL_HWACCEL);
  2554. screen_width = cur_stream->width = event.resize.w;
  2555. screen_height = cur_stream->height = event.resize.h;
  2556. cur_stream->force_refresh = 1;
  2557. break;
  2558. case SDL_QUIT:
  2559. case FF_QUIT_EVENT:
  2560. do_exit(cur_stream);
  2561. break;
  2562. case FF_ALLOC_EVENT:
  2563. alloc_picture(event.user.data1);
  2564. break;
  2565. case FF_REFRESH_EVENT:
  2566. video_refresh(event.user.data1);
  2567. cur_stream->refresh = 0;
  2568. break;
  2569. default:
  2570. break;
  2571. }
  2572. }
  2573. }
  2574. static int opt_frame_size(void *optctx, const char *opt, const char *arg)
  2575. {
  2576. av_log(NULL, AV_LOG_WARNING, "Option -s is deprecated, use -video_size.\n");
  2577. return opt_default(NULL, "video_size", arg);
  2578. }
  2579. static int opt_width(void *optctx, const char *opt, const char *arg)
  2580. {
  2581. screen_width = parse_number_or_die(opt, arg, OPT_INT64, 1, INT_MAX);
  2582. return 0;
  2583. }
  2584. static int opt_height(void *optctx, const char *opt, const char *arg)
  2585. {
  2586. screen_height = parse_number_or_die(opt, arg, OPT_INT64, 1, INT_MAX);
  2587. return 0;
  2588. }
  2589. static int opt_format(void *optctx, const char *opt, const char *arg)
  2590. {
  2591. file_iformat = av_find_input_format(arg);
  2592. if (!file_iformat) {
  2593. fprintf(stderr, "Unknown input format: %s\n", arg);
  2594. return AVERROR(EINVAL);
  2595. }
  2596. return 0;
  2597. }
  2598. static int opt_frame_pix_fmt(void *optctx, const char *opt, const char *arg)
  2599. {
  2600. av_log(NULL, AV_LOG_WARNING, "Option -pix_fmt is deprecated, use -pixel_format.\n");
  2601. return opt_default(NULL, "pixel_format", arg);
  2602. }
  2603. static int opt_sync(void *optctx, const char *opt, const char *arg)
  2604. {
  2605. if (!strcmp(arg, "audio"))
  2606. av_sync_type = AV_SYNC_AUDIO_MASTER;
  2607. else if (!strcmp(arg, "video"))
  2608. av_sync_type = AV_SYNC_VIDEO_MASTER;
  2609. else if (!strcmp(arg, "ext"))
  2610. av_sync_type = AV_SYNC_EXTERNAL_CLOCK;
  2611. else {
  2612. fprintf(stderr, "Unknown value for %s: %s\n", opt, arg);
  2613. exit(1);
  2614. }
  2615. return 0;
  2616. }
  2617. static int opt_seek(void *optctx, const char *opt, const char *arg)
  2618. {
  2619. start_time = parse_time_or_die(opt, arg, 1);
  2620. return 0;
  2621. }
  2622. static int opt_duration(void *optctx, const char *opt, const char *arg)
  2623. {
  2624. duration = parse_time_or_die(opt, arg, 1);
  2625. return 0;
  2626. }
  2627. static int opt_show_mode(void *optctx, const char *opt, const char *arg)
  2628. {
  2629. show_mode = !strcmp(arg, "video") ? SHOW_MODE_VIDEO :
  2630. !strcmp(arg, "waves") ? SHOW_MODE_WAVES :
  2631. !strcmp(arg, "rdft" ) ? SHOW_MODE_RDFT :
  2632. parse_number_or_die(opt, arg, OPT_INT, 0, SHOW_MODE_NB-1);
  2633. return 0;
  2634. }
  2635. static void opt_input_file(void *optctx, const char *filename)
  2636. {
  2637. if (input_filename) {
  2638. fprintf(stderr, "Argument '%s' provided as input filename, but '%s' was already specified.\n",
  2639. filename, input_filename);
  2640. exit_program(1);
  2641. }
  2642. if (!strcmp(filename, "-"))
  2643. filename = "pipe:";
  2644. input_filename = filename;
  2645. }
  2646. static int opt_codec(void *o, const char *opt, const char *arg)
  2647. {
  2648. switch(opt[strlen(opt)-1]){
  2649. case 'a' : audio_codec_name = arg; break;
  2650. case 's' : subtitle_codec_name = arg; break;
  2651. case 'v' : video_codec_name = arg; break;
  2652. }
  2653. return 0;
  2654. }
  2655. static int dummy;
  2656. static const OptionDef options[] = {
  2657. #include "cmdutils_common_opts.h"
  2658. { "x", HAS_ARG, { .func_arg = opt_width }, "force displayed width", "width" },
  2659. { "y", HAS_ARG, { .func_arg = opt_height }, "force displayed height", "height" },
  2660. { "s", HAS_ARG | OPT_VIDEO, { .func_arg = opt_frame_size }, "set frame size (WxH or abbreviation)", "size" },
  2661. { "fs", OPT_BOOL, { &is_full_screen }, "force full screen" },
  2662. { "an", OPT_BOOL, { &audio_disable }, "disable audio" },
  2663. { "vn", OPT_BOOL, { &video_disable }, "disable video" },
  2664. { "ast", OPT_INT | HAS_ARG | OPT_EXPERT, { &wanted_stream[AVMEDIA_TYPE_AUDIO] }, "select desired audio stream", "stream_number" },
  2665. { "vst", OPT_INT | HAS_ARG | OPT_EXPERT, { &wanted_stream[AVMEDIA_TYPE_VIDEO] }, "select desired video stream", "stream_number" },
  2666. { "sst", OPT_INT | HAS_ARG | OPT_EXPERT, { &wanted_stream[AVMEDIA_TYPE_SUBTITLE] }, "select desired subtitle stream", "stream_number" },
  2667. { "ss", HAS_ARG, { .func_arg = opt_seek }, "seek to a given position in seconds", "pos" },
  2668. { "t", HAS_ARG, { .func_arg = opt_duration }, "play \"duration\" seconds of audio/video", "duration" },
  2669. { "bytes", OPT_INT | HAS_ARG, { &seek_by_bytes }, "seek by bytes 0=off 1=on -1=auto", "val" },
  2670. { "nodisp", OPT_BOOL, { &display_disable }, "disable graphical display" },
  2671. { "f", HAS_ARG, { .func_arg = opt_format }, "force format", "fmt" },
  2672. { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO, { .func_arg = opt_frame_pix_fmt }, "set pixel format", "format" },
  2673. { "stats", OPT_BOOL | OPT_EXPERT, { &show_status }, "show status", "" },
  2674. { "bug", OPT_INT | HAS_ARG | OPT_EXPERT, { &workaround_bugs }, "workaround bugs", "" },
  2675. { "fast", OPT_BOOL | OPT_EXPERT, { &fast }, "non spec compliant optimizations", "" },
  2676. { "genpts", OPT_BOOL | OPT_EXPERT, { &genpts }, "generate pts", "" },
  2677. { "drp", OPT_INT | HAS_ARG | OPT_EXPERT, { &decoder_reorder_pts }, "let decoder reorder pts 0=off 1=on -1=auto", ""},
  2678. { "lowres", OPT_INT | HAS_ARG | OPT_EXPERT, { &lowres }, "", "" },
  2679. { "skiploop", OPT_INT | HAS_ARG | OPT_EXPERT, { &skip_loop_filter }, "", "" },
  2680. { "skipframe", OPT_INT | HAS_ARG | OPT_EXPERT, { &skip_frame }, "", "" },
  2681. { "skipidct", OPT_INT | HAS_ARG | OPT_EXPERT, { &skip_idct }, "", "" },
  2682. { "idct", OPT_INT | HAS_ARG | OPT_EXPERT, { &idct }, "set idct algo", "algo" },
  2683. { "ec", OPT_INT | HAS_ARG | OPT_EXPERT, { &error_concealment }, "set error concealment options", "bit_mask" },
  2684. { "sync", HAS_ARG | OPT_EXPERT, { .func_arg = opt_sync }, "set audio-video sync. type (type=audio/video/ext)", "type" },
  2685. { "autoexit", OPT_BOOL | OPT_EXPERT, { &autoexit }, "exit at the end", "" },
  2686. { "exitonkeydown", OPT_BOOL | OPT_EXPERT, { &exit_on_keydown }, "exit on key down", "" },
  2687. { "exitonmousedown", OPT_BOOL | OPT_EXPERT, { &exit_on_mousedown }, "exit on mouse down", "" },
  2688. { "loop", OPT_INT | HAS_ARG | OPT_EXPERT, { &loop }, "set number of times the playback shall be looped", "loop count" },
  2689. { "framedrop", OPT_BOOL | OPT_EXPERT, { &framedrop }, "drop frames when cpu is too slow", "" },
  2690. { "infbuf", OPT_BOOL | OPT_EXPERT, { &infinite_buffer }, "don't limit the input buffer size (useful with realtime streams)", "" },
  2691. { "window_title", OPT_STRING | HAS_ARG, { &window_title }, "set window title", "window title" },
  2692. #if CONFIG_AVFILTER
  2693. { "vf", OPT_STRING | HAS_ARG, { &vfilters }, "video filters", "filter list" },
  2694. #endif
  2695. { "rdftspeed", OPT_INT | HAS_ARG| OPT_AUDIO | OPT_EXPERT, { &rdftspeed }, "rdft speed", "msecs" },
  2696. { "showmode", HAS_ARG, { .func_arg = opt_show_mode}, "select show mode (0 = video, 1 = waves, 2 = RDFT)", "mode" },
  2697. { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, { .func_arg = opt_default }, "generic catch all option", "" },
  2698. { "i", OPT_BOOL, { &dummy}, "read specified file", "input_file"},
  2699. { "codec", HAS_ARG, { .func_arg = opt_codec}, "force decoder", "decoder" },
  2700. { NULL, },
  2701. };
  2702. static void show_usage(void)
  2703. {
  2704. av_log(NULL, AV_LOG_INFO, "Simple media player\n");
  2705. av_log(NULL, AV_LOG_INFO, "usage: %s [options] input_file\n", program_name);
  2706. av_log(NULL, AV_LOG_INFO, "\n");
  2707. }
  2708. void show_help_default(const char *opt, const char *arg)
  2709. {
  2710. av_log_set_callback(log_callback_help);
  2711. show_usage();
  2712. show_help_options(options, "Main options:", 0, OPT_EXPERT, 0);
  2713. show_help_options(options, "Advanced options:", OPT_EXPERT, 0, 0);
  2714. printf("\n");
  2715. show_help_children(avcodec_get_class(), AV_OPT_FLAG_DECODING_PARAM);
  2716. show_help_children(avformat_get_class(), AV_OPT_FLAG_DECODING_PARAM);
  2717. #if !CONFIG_AVFILTER
  2718. show_help_children(sws_get_class(), AV_OPT_FLAG_ENCODING_PARAM);
  2719. #else
  2720. show_help_children(avfilter_get_class(), AV_OPT_FLAG_FILTERING_PARAM);
  2721. #endif
  2722. printf("\nWhile playing:\n"
  2723. "q, ESC quit\n"
  2724. "f toggle full screen\n"
  2725. "p, SPC pause\n"
  2726. "a cycle audio channel\n"
  2727. "v cycle video channel\n"
  2728. "t cycle subtitle channel\n"
  2729. "w show audio waves\n"
  2730. "s activate frame-step mode\n"
  2731. "left/right seek backward/forward 10 seconds\n"
  2732. "down/up seek backward/forward 1 minute\n"
  2733. "page down/page up seek backward/forward 10 minutes\n"
  2734. "mouse click seek to percentage in file corresponding to fraction of width\n"
  2735. );
  2736. }
  2737. static int lockmgr(void **mtx, enum AVLockOp op)
  2738. {
  2739. switch(op) {
  2740. case AV_LOCK_CREATE:
  2741. *mtx = SDL_CreateMutex();
  2742. if(!*mtx)
  2743. return 1;
  2744. return 0;
  2745. case AV_LOCK_OBTAIN:
  2746. return !!SDL_LockMutex(*mtx);
  2747. case AV_LOCK_RELEASE:
  2748. return !!SDL_UnlockMutex(*mtx);
  2749. case AV_LOCK_DESTROY:
  2750. SDL_DestroyMutex(*mtx);
  2751. return 0;
  2752. }
  2753. return 1;
  2754. }
  2755. /* Called from the main */
  2756. int main(int argc, char **argv)
  2757. {
  2758. int flags;
  2759. VideoState *is;
  2760. char dummy_videodriver[] = "SDL_VIDEODRIVER=dummy";
  2761. av_log_set_flags(AV_LOG_SKIP_REPEATED);
  2762. parse_loglevel(argc, argv, options);
  2763. /* register all codecs, demux and protocols */
  2764. avcodec_register_all();
  2765. #if CONFIG_AVDEVICE
  2766. avdevice_register_all();
  2767. #endif
  2768. #if CONFIG_AVFILTER
  2769. avfilter_register_all();
  2770. #endif
  2771. av_register_all();
  2772. avformat_network_init();
  2773. init_opts();
  2774. signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
  2775. signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
  2776. show_banner(argc, argv, options);
  2777. parse_options(NULL, argc, argv, options, opt_input_file);
  2778. if (!input_filename) {
  2779. show_usage();
  2780. fprintf(stderr, "An input file must be specified\n");
  2781. fprintf(stderr, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
  2782. exit(1);
  2783. }
  2784. if (display_disable) {
  2785. video_disable = 1;
  2786. }
  2787. flags = SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER;
  2788. if (audio_disable)
  2789. flags &= ~SDL_INIT_AUDIO;
  2790. if (display_disable)
  2791. SDL_putenv(dummy_videodriver); /* For the event queue, we always need a video driver. */
  2792. #if !defined(__MINGW32__) && !defined(__APPLE__)
  2793. flags |= SDL_INIT_EVENTTHREAD; /* Not supported on Windows or Mac OS X */
  2794. #endif
  2795. if (SDL_Init (flags)) {
  2796. fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError());
  2797. fprintf(stderr, "(Did you set the DISPLAY variable?)\n");
  2798. exit(1);
  2799. }
  2800. if (!display_disable) {
  2801. #if HAVE_SDL_VIDEO_SIZE
  2802. const SDL_VideoInfo *vi = SDL_GetVideoInfo();
  2803. fs_screen_width = vi->current_w;
  2804. fs_screen_height = vi->current_h;
  2805. #endif
  2806. }
  2807. SDL_EventState(SDL_ACTIVEEVENT, SDL_IGNORE);
  2808. SDL_EventState(SDL_SYSWMEVENT, SDL_IGNORE);
  2809. SDL_EventState(SDL_USEREVENT, SDL_IGNORE);
  2810. if (av_lockmgr_register(lockmgr)) {
  2811. fprintf(stderr, "Could not initialize lock manager!\n");
  2812. do_exit(NULL);
  2813. }
  2814. av_init_packet(&flush_pkt);
  2815. flush_pkt.data = (char *)(intptr_t)"FLUSH";
  2816. is = stream_open(input_filename, file_iformat);
  2817. if (!is) {
  2818. fprintf(stderr, "Failed to initialize VideoState!\n");
  2819. do_exit(NULL);
  2820. }
  2821. event_loop(is);
  2822. /* never returns */
  2823. return 0;
  2824. }