ffplay.c 129 KB

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