ffplay.c 133 KB

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