ffplay.c 134 KB

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