ffplay.c 133 KB

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