SDL Library Documentation - v1.2.3-rev1, Sep 2001

Sam Lantinga

Martin Donlon

Mattias Engdegård
Julian Peterson
Ken Jordan
Maxim Sobolev
Wesley Poole
Michael Vance
Andreas Umbach
Andreas Hofmeister

"Simple, efficient, and portable"

Table of Contents
I. SDL Guide
About SDL
About SDLdoc
1. The Basics
Initializing SDL
2. Graphics and Video
Introduction to SDL Video
Using OpenGL With SDL
3. Input handling
Handling Joysticks
Handling the Keyboard
4. Examples
Event Examples
Audio Examples
CDROM Examples
Time Examples
II. SDL Reference
5. General
SDL_Init — Initializes SDL
SDL_InitSubSystem — Initialize subsystems
SDL_QuitSubSystem — Shut down a subsystem
SDL_Quit — Shut down SDL
SDL_WasInit — Check which subsystems are initialized
SDL_GetError — Get SDL error string
SDL_envvars — SDL environment variables
6. Video
SDL_GetVideoSurface — returns a pointer to the current display surface
SDL_GetVideoInfo — returns a pointer to information about the video hardware
SDL_VideoDriverName — Obtain the name of the video driver
SDL_ListModes — Returns a pointer to an array of available screen dimensions for the given format and video flags
SDL_VideoModeOK — Check to see if a particular video mode is supported.
SDL_SetVideoMode — Set up a video mode with the specified width, height and bits-per-pixel.
SDL_UpdateRect — Makes sure the given area is updated on the given screen.
SDL_UpdateRects — Makes sure the given list of rectangles is updated on the given screen.
SDL_Flip — Swaps screen buffers
SDL_SetColors — Sets a portion of the colormap for the given 8-bit surface.
SDL_SetPalette — Sets the colors in the palette of an 8-bit surface.
SDL_SetGamma — Sets the color gamma function for the display
SDL_GetGammaRamp — Gets the color gamma lookup tables for the display
SDL_SetGammaRamp — Sets the color gamma lookup tables for the display
SDL_MapRGB — Map a RGB color value to a pixel format.
SDL_MapRGBA — Map a RGBA color value to a pixel format.
SDL_GetRGB — Get RGB values from a pixel in the specified pixel format.
SDL_GetRGBA — Get RGBA values from a pixel in the specified pixel format.
SDL_CreateRGBSurface — Create an empty SDL_Surface
SDL_CreateRGBSurfaceFrom — Create an SDL_Surface from pixel data
SDL_FreeSurface — Frees (deletes) a SDL_Surface
SDL_LockSurface — Lock a surface for directly access.
SDL_UnlockSurface — Unlocks a previously locked surface.
SDL_LoadBMP — Load a Windows BMP file into an SDL_Surface.
SDL_SaveBMP — Save an SDL_Surface as a Windows BMP file.
SDL_SetColorKey — Sets the color key (transparent pixel) in a blittable surface and RLE acceleration.
SDL_SetAlpha — Adjust the alpha properties of a surface
SDL_SetClipRect — Sets the clipping rectangle for a surface.
SDL_GetClipRect — Gets the clipping rectangle for a surface.
SDL_ConvertSurface — Converts a surface to the same format as another surface.
SDL_BlitSurface — This performs a fast blit from the source surface to the destination surface.
SDL_FillRect — This function performs a fast fill of the given rectangle with some color
SDL_DisplayFormat — Convert a surface to the display format
SDL_DisplayFormatAlpha — Convert a surface to the display format
SDL_WarpMouse — Set the position of the mouse cursor.
SDL_CreateCursor — Creates a new mouse cursor.
SDL_FreeCursor — Frees a cursor created with SDL_CreateCursor.
SDL_SetCursor — Set the currently active mouse cursor.
SDL_GetCursor — Get the currently active mouse cursor.
SDL_ShowCursor — Toggle whether or not the cursor is shown on the screen.
SDL_GL_LoadLibrary — Specify an OpenGL library
SDL_GL_GetProcAddress — Get the address of a GL function
SDL_GL_GetAttribute — Get the value of a special SDL/OpenGL attribute
SDL_GL_SetAttribute — Set a special SDL/OpenGL attribute
SDL_GL_SwapBuffers — Swap OpenGL framebuffers/Update Display
SDL_CreateYUVOverlay — Create a YUV video overlay
SDL_LockYUVOverlay — Lock an overlay
SDL_UnlockYUVOverlay — Unlock an overlay
SDL_DisplayYUVOverlay — Blit the overlay to the display
SDL_FreeYUVOverlay — Free a YUV video overlay
SDL_GLattr — SDL GL Attributes
SDL_Rect — Defines a rectangular area
SDL_Color — Format independent color description
SDL_Palette — Color palette for 8-bit pixel formats
SDL_PixelFormat — Stores surface format information
SDL_Surface — Graphical Surface Structure
SDL_VideoInfo — Video Target information
SDL_Overlay — YUV video overlay
7. Window Management
SDL_WM_SetCaption — Sets the window tile and icon name.
SDL_WM_GetCaption — Gets the window title and icon name.
SDL_WM_SetIcon — Sets the icon for the display window.
SDL_WM_IconifyWindow — Iconify/Minimise the window
SDL_WM_ToggleFullScreen — Toggles fullscreen mode
SDL_WM_GrabInput — Grabs mouse and keyboard input.
8. Events
SDL Event Structures.
Event Functions.
9. Joystick
SDL_NumJoysticks — Count available joysticks.
SDL_JoystickName — Get joystick name.
SDL_JoystickOpen — Opens a joystick for use.
SDL_JoystickOpened — Determine if a joystick has been opened
SDL_JoystickIndex — Get the index of an SDL_Joystick.
SDL_JoystickNumAxes — Get the number of joystick axes
SDL_JoystickNumBalls — Get the number of joystick trackballs
SDL_JoystickNumHats — Get the number of joystick hats
SDL_JoystickNumButtons — Get the number of joysitck buttons
SDL_JoystickUpdate — Updates the state of all joysticks
SDL_JoystickGetAxis — Get the current state of an axis
SDL_JoystickGetHat — Get the current state of a joystick hat
SDL_JoystickGetButton — Get the current state of a given button on a given joystick
SDL_JoystickGetBall — Get relative trackball motion
SDL_JoystickClose — Closes a previously opened joystick
10. Audio
SDL_AudioSpec — Audio Specification Structure
SDL_OpenAudio — Opens the audio device with the desired parameters.
SDL_PauseAudio — Pauses and unpauses the audio callback processing
SDL_GetAudioStatus — Get the current audio state
SDL_LoadWAV — Load a WAVE file
SDL_FreeWAV — Frees previously opened WAV data
SDL_AudioCVT — Audio Conversion Structure
SDL_BuildAudioCVT — Initializes a SDL_AudioCVT structure for conversion
SDL_ConvertAudio — Convert audio data to a desired audio format.
SDL_MixAudio — Mix audio data
SDL_LockAudio — Lock out the callback function
SDL_UnlockAudio — Unlock the callback function
SDL_CloseAudio — Shuts down audio processing and closes the audio device.
11. CD-ROM
SDL_CDNumDrives — Returns the number of CD-ROM drives on the system.
SDL_CDName — Returns a human-readable, system-dependent identifier for the CD-ROM.
SDL_CDOpen — Opens a CD-ROM drive for access.
SDL_CDStatus — Returns the current status of the given drive.
SDL_CDPlay — Play a CD
SDL_CDPlayTracks — Play the given CD track(s)
SDL_CDPause — Pauses a CDROM
SDL_CDResume — Resumes a CDROM
SDL_CDStop — Stops a CDROM
SDL_CDEject — Ejects a CDROM
SDL_CDClose — Closes a SDL_CD handle
SDL_CD — CDROM Drive Information
SDL_CDtrack — CD Track Information Structure
12. Multi-threaded Programming
SDL_CreateThread — Creates a new thread of execution that shares its parent's properties.
SDL_ThreadID — Get the 32-bit thread identifier for the current thread.
SDL_GetThreadID — Get the SDL thread ID of a SDL_Thread
SDL_WaitThread — Wait for a thread to finish.
SDL_KillThread — Gracelessly terminates the thread.
SDL_CreateMutex — Create a mutex
SDL_DestroyMutex — Destroy a mutex
SDL_mutexP — Lock a mutex
SDL_mutexV — Unlock a mutex
SDL_CreateSemaphore — Creates a new semaphore and assigns an initial value to it.
SDL_DestroySemaphore — Destroys a semaphore that was created by SDL_CreateSemaphore.
SDL_SemWait — Lock a semaphore and suspend the thread if the semaphore value is zero.
SDL_SemTryWait — Attempt to lock a semaphore but don't suspend the thread.
SDL_SemWaitTimeout — Lock a semaphore, but only wait up to a specified maximum time.
SDL_SemPost — Unlock a semaphore.
SDL_SemValue — Return the current value of a semaphore.
SDL_CreateCond — Create a condition variable
SDL_DestroyCond — Destroy a condition variable
SDL_CondSignal — Restart a thread wait on a condition variable
SDL_CondBroadcast — Restart all threads waiting on a condition variable
SDL_CondWait — Wait on a condition variable
SDL_CondWaitTimeout — Wait on a condition variable, with timeout
13. Time
SDL_GetTicks — Get the number of milliseconds since the SDL library initialization.
SDL_Delay — Wait a specified number of milliseconds before returning.
SDL_AddTimer — Add a timer which will call a callback after the specified number of milliseconds has elapsed.
SDL_RemoveTimer — Remove a timer which was added with SDL_AddTimer.
SDL_SetTimer — Set a callback to run after the specified number of milliseconds has elapsed.
List of Tables
8-1. SDL Keysym definitions
8-2. SDL modifier definitions
List of Examples
1-1. Initializing SDL
2-1. Initializing the Video Display
2-2. Initializing the Best Video Mode
2-3. Loading and Displaying a BMP File
2-4. getpixel()
2-5. putpixel()
2-6. Using putpixel()
2-7. Initializing SDL with OpenGL
2-8. SDL and OpenGL
3-1. Initializing SDL with Joystick Support
3-2. Querying the Number of Available Joysticks
3-3. Opening a Joystick
3-4. Joystick Axis Events
3-5. More Joystick Axis Events
3-6. Joystick Button Events
3-7. Joystick Ball Events
3-8. Joystick Hat Events
3-9. Querying Joystick Characteristics
3-10. Reading Keyboard Events
3-11. Interpreting Key Event Information
3-12. Proper Game Movement

User Contributed Notes
akawaka at
2003-12-11 18:19:48
Testing 1..2..3
wortmann at
2003-12-22 02:47:09
Is there any way to download the whole documentation?
riadh at
2003-12-23 16:37:28
good job! but a zip file or a pdf one will be better!!
me at
2004-01-07 03:36:38
felt like adding my own tests

testing ... 1 . 2 .3 
lguegan at
2004-01-07 18:32:08
where to download the whole at once ?
ecosta at
2004-01-08 02:39:34
It's more intuitive if the functions are on alphabetical order...
morten at
2004-01-10 22:45:31
A chapter on keyboard input (e.g. SDL_EnableKeyRepeat, SDL_GetKeyState,
SDL_GetModState, SDL_SetModState, and SDL_GetKeyName) seems to be
missing from the table of contents. Was that on purpose or is it on
todo list?

Morten Perriard
Wonder-Boy at
2004-01-20 02:14:52
¡Traducción al español, por favor! ;-D

The Documentation is Great :-D but...
I will was pleased if this was writted in Spanish... :-D
(Pardon my english)

Anyway, Thanx!

- Wonder Boy -
styxo at
2004-01-25 23:02:44
niiiice :)
Great doc
jshrive3 at
2004-01-29 07:47:05
Would be useful to see how things work together. Right now I'm trying to
figure out how to make a color in an image transparent before blitting.
Best I've guessed it use SDL_SetColorKey, but to get the key I dug and
found SDL_MapRGB, but now I need to figure out how to use PixelFormat.
IT's a little confusing figuring out how it all fits together.

spamsink at
2004-02-03 01:25:24
An example of synchronizing video and audio (with minimal audio delay)
would be nice.
fadosolre at
2004-02-03 13:43:18
I tried to run the first example both in visual c++ 6 and borland c++
builder 6 but I got the same linker error.
It can't find the " int main() " method.
It isn't a compiler error so I think the compiler can find and use the
What's wrong??
Thanks so much
bauhmaut at
2004-02-08 21:05:58
how do I install the libraries, I see nothing on installing them
LordZe at
2004-02-09 17:53:31
Niceeee.. :)

but.. more transparence info :))
b_lindeijer at
2004-02-10 14:59:56
Typo in 'title': "Sets the window tile and icon name"
joaosilva42 at
2004-02-10 16:20:05
This documentation project is a great effort. It has been very helpful.

I'm new to SDL, so I'm not aware of what has changed between versions.
I'm using v1.2.6, while this documentation is for v1.2.3. I have
checked the changelog, and I haven't seen any big changes in the API.
Still, an updated version would be nice. Also, a link to download the
whole documentation would be welcome.

Kudos to the maintainers of the documentation.
chrise at
2004-02-10 20:04:19
I've started to have serious doubts about whether anyone actually is
maintaining this documentation :P
kuroueie at
2004-02-11 16:18:48

tar.gz , zip  and etc docs are there
no at mail
2004-02-19 23:23:38
I need some speed pointers if anyone can help me, I wrote an app. which
originally used XDGA. I was using MIT-SHM for a software buffer, and a
assembly level MMX routine for transfer to the framebuffer. I thought
with SDL's hardware blits I'd get a performance increase, NO NO NO.. I
ended up with a whopping decrease, like 5 to 10 times slower. I really
hope I'm doing something wrong, I'm setting all the HW flags, not
running a 24 bpp mode, if anyone knows any common newbie mistakes or
has any advice I'm all ears.. Thank You.
chrise at
2004-02-21 12:34:23
Does your program do much pixel-level data access on the display
That would cause a performance decrease with a hardware buffer, since
it is often much slower sending individual pixels across the video
Also, you might not actually be getting a hardware surface - check to
see whether SDL_HWSURFACE is set in the flags field of the surface
returned by SDL_SetVideoMode.
And double buffering actually slows things down, so try it without the
no at mail
2004-02-24 07:29:24
I forgot to set SDL_VIDEODRIVER="dga", oops.. now it smokes, anyway
thanks for the tips chrise.
descenterace at
2004-02-28 17:05:28
So... how does one go about using DirectX 9 with SDL?  I would use OGL
(and I certainly intend to learn at some point) but I'm currently more
familiar with DirectX.

That DX9 SDK took me two weeks to get across 56k, so I'm gonna use
it... <:)
dont_like_sam at
2004-03-01 12:40:53
v1.2.3-rev1, Sep 2001 it is quite out of date :( What about movieg
documentation to wiki system?
functions headers and data structures can be extracted automaticaly
form the source to avoid mess witch absolute or removed staff (there
are some in this doc)
no at
2004-03-04 19:59:41
Is there any way to know the refresh rate of the monitor by using SDL
function calls. None the listed API seems to provide this.
jbbeauf at
2004-03-07 11:09:07
The function printf doesn't work when the graphic mode is initalized. Is
there an other function to print text on the screen ?
none at
2004-03-09 23:16:50
You have to implement some kind of font/graphics engine to get text in
darkvizier at
2004-03-11 03:01:40
"Programming Linux Games," by John R. Hall goes over many of the topics
listed here, and gives some info on alpha blending and transparencies
as well.  It also covers using gcc, cvs, gdb, and makefiles in Linux,
which are nice things to know.  It's not all inclusive by any means,
but it covers everything enough to get you started making useful
programs.  Nice to have it on paper too, if you're sick of staring at
your monitor.  :)

ISBN 1-886411-49-2 if anyone is interested.

As far as installing the libraries, there are some tutorials for that

You can also download the libraries from there.  :)
qwasty at
2004-03-13 04:06:54
Wow, this is antique. When is this going to be wiki'd or otherwise
updated? Bill Clinton was president when this was last updated.
kenwury at
2004-03-26 14:49:36
when I run my programme,it return that:
SDL can not initialize:cannot open mouse 
I programme under linux framebuffer mode
kenwury at
2004-03-29 15:32:03
How can I make a menu like freevo using sdl under framebuffer mode?
toomuchspam at
2004-03-29 23:13:20
I've written a (Win9x) program that allows switching between windowed
and fullscreen mode while running. When in fullscreen and one presses
Alt+Tab to iconify the screen, maximizes it again, and then changes to
windowed mode, the window stays hidden. It appears in the taskbar and
still reacts to keypresses, but it won't show up again, no matter what
you do. One can still switch back to fullscreen (which is working), but
the window is lost forever! Happens with both SDL 1.2.6 and 1.2.7.
garret4 at
2004-04-05 16:59:49
Hi there!
I got one small problem - i am using borland c++ builder 5.0 with SDL
1.0 and everything works just fine ( audio, cdrom and other stuff)
except the video! When i initialize SDL_Init( SDL_INIT_VIDEO )  i am
receiving error like : "couldnt create window".. Darn..
etienne at
2004-04-13 12:56:04
Line Drawing

I have implemented a line drawing mechanism using the
midpoint algorithm (Computer Graphics Principles and Practice 1990)
but all goes wrong with my 3d projections (I don't use GL), could
somebody please share an effective but good (quality over speed) line
drawing algorithm which preferably takes x,y coordinates for two
without assumptions which x or y is largest.

no at mail
2004-04-21 11:39:00
drawline(int x, int y, int x2, int y2)
  bool yL = false;
  int sL = y2-y;
  int lL = x2-x;
    int swap = sL;
    sL = lL;
    lL = swap;
    yL = true;
  int dI;
  if(lL == 0) dI = 0;
  else dI = (sL << 16)/lL;
      lL += y;
      for(int j=0x8000+(x << 16); y<=lL; ++y){
        putpixel(j >> 16, y); //define your own putPix mofo
	j += dI;
    lL += y;
    for(int j=0x8000+(x << 16); y>=lL; --y){
      putpixel(j >> 16, y);
      j -= dI;
    lL += x;
    for(int j=0x8000+(y << 16); x<=lL; ++x){
      putpixel(x, j >> 16);
      j += dI;
  lL += x;
  for(int j=0x8000+(y << 16); x>=lL; --x){
    putpixel(x, j >> 16);
    j -= dI;
etam at
2004-04-21 11:43:47
How can I display text on the screen without creating any bitmap fonts?
Is it possible?
no at nail
2004-05-01 21:44:55
when if & what version will the new hardware visible surface flag be
available ??
none at
2004-05-06 13:24:17
you can display text through sdl_ttf, download it under 'libraries' link
df at
2004-05-13 10:16:49
Is it possible to make SDL created window to be RootWindow of the
For example, i have Display pointer and Window handler. Is it possible
to change created window handler with one, I need?

void func (Display * dpy, Window win)
/// How can I use `win`???
leffe at
2004-05-14 12:53:09
Using Direct3D with SDL is easy, just set up the SDL window as usual,
then set up Direct3D as usual, to get the hwnd you do this:

SDL_SysWMinfo WMInfo;

You might have to #include <SDL/SDL_syswm.h>.
sadf at asdf.asdf
2004-05-21 18:58:04
			if(event.key.state == SDL_PRESSED)
				 case SDLK_ESCAPE:
					 run = false;
nareth_cerimar at
2004-05-21 21:24:52
another thing..

the FPS is around 72 while visual basic and directdraw7 is around 92
fps... isnt that faster?
non at none.none
2004-05-23 20:33:09
there are some functions missing in the reference. where can i find
them? ( like SDL_GetKeyState )
dsf at
2004-06-01 18:29:18
põe essa porra em outras línguas
none at
2004-06-02 01:43:07
SDL automatically limits its framerate to the fastest that it can
actually display, which is your monitor's refresh rate.  Thus, it's
likely that you have your monitor's refresh set to 72 Hz.  DirectDraw
likely doesn't do this, so it's displaying how many frames have been
created, whether or not it was able to display them all.

So, try adding more complexity to your simulation and see if the
framerate drops.
postmaster at
2004-06-10 16:42:34
Waiting for an update to 1.2.7 ...

Is there still somebody working out there ?
Wandererxp at
2004-06-12 01:23:41
In download format, please...
none at
2004-06-16 04:14:32
here is a better line drawing function that I wrote using the
"point-slope" form of a line which we all learned in math class

void drawline(SDL_Surface *surface, int x1, int y1, int x2, int y2,
Uint32 color)
	double m = (double)(y2 - y1) / (double)(x2 - x1); // define the slope
	int y; // this will change as we vary x
	for (int x = x1; x <= x2; x++)
		y = (int)(m * (x - x1)) + y1;
		putpixel(surface, x, y, color);
none at
2004-06-16 04:32:58
oops, that code wont if x1 > x2 so just add this code to the top of the

	// swap points
	if (x1 > x2)
		int temp = x1;
		x1 = x2;
		x2 = temp;
		temp = y1;
		y1 = y2;
		y2 = temp;
s_ridenour at
2004-06-22 19:53:07
To whoever it was (#12 I think) who said VC++ couldn't find "int
main()": that's because your main() function should be
  int main(int argc, char **argv)
instead, even if your program doesn't use argc and argv.
osvaldo at
2004-07-05 15:05:11
I need help to creat a multiplayer chess, realy I have "Multimedia
Fusion" and I have to creat a DLL in C++ for this...


Osvaldo Neto
madcoder at
2004-07-07 02:08:21
well, do you need help creating the dll or the chess game itself ?
dnsb653 at
2004-07-14 15:46:07
I have file in which is many 8x8 size pictures whose are 16 colour.And I
want load these pictures to surface.So I first load this file with
fread(Buffer, 32, NumOfPictures, InputFile) to char buffer and I try to
create surface from this buffer with SDL_CreateRGBSurfaceFrom.But there
is one problem that when I am trying to create surface I get empty
black surface:
SDL_CreateRGBSurfaceFrom((void*)Buffer, 8, 8, 4, 4, 0, 0, 0, 0);
Can someone tell what is wrong or tell another way how to do that is
FASTEST way?Thanks...

Add Note
All text is treated as preformatted text, it should appear identical to how you enter it.
This is not a message board system or a guestbook. This system is here to allow you to add details or helpful advice that you feel may be missing from a certain part of the documentation.