]> git.sesse.net Git - ffmpeg/blob - libavdevice/sdl.c
Merge commit 'b83d1ee3b41cfe8357836e2582104db2f3364cb0'
[ffmpeg] / libavdevice / sdl.c
1 /*
2  * Copyright (c) 2011 Stefano Sabatini
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 /**
22  * @file
23  * libSDL output device
24  */
25
26 #include <SDL.h>
27 #include <SDL_thread.h>
28
29 #include "libavutil/avstring.h"
30 #include "libavutil/opt.h"
31 #include "libavutil/parseutils.h"
32 #include "libavutil/pixdesc.h"
33 #include "libavutil/time.h"
34 #include "avdevice.h"
35
36 typedef struct {
37     AVClass *class;
38     SDL_Surface *surface;
39     SDL_Overlay *overlay;
40     char *window_title;
41     char *icon_title;
42     int window_width,  window_height;  /**< size of the window */
43     int window_fullscreen;
44
45     SDL_Rect overlay_rect;
46     int overlay_fmt;
47
48     int sdl_was_already_inited;
49     SDL_Thread *event_thread;
50     SDL_mutex *mutex;
51     SDL_cond *init_cond;
52     int init_ret; /* return code used to signal initialization errors */
53     int inited;
54     int quit;
55 } SDLContext;
56
57 static const struct sdl_overlay_pix_fmt_entry {
58     enum AVPixelFormat pix_fmt; int overlay_fmt;
59 } sdl_overlay_pix_fmt_map[] = {
60     { AV_PIX_FMT_YUV420P, SDL_IYUV_OVERLAY },
61     { AV_PIX_FMT_YUYV422, SDL_YUY2_OVERLAY },
62     { AV_PIX_FMT_UYVY422, SDL_UYVY_OVERLAY },
63     { AV_PIX_FMT_NONE,    0                },
64 };
65
66 static int sdl_write_trailer(AVFormatContext *s)
67 {
68     SDLContext *sdl = s->priv_data;
69
70     sdl->quit = 1;
71
72     if (sdl->overlay)
73         SDL_FreeYUVOverlay(sdl->overlay);
74     if (sdl->event_thread)
75         SDL_WaitThread(sdl->event_thread, NULL);
76     if (sdl->mutex)
77         SDL_DestroyMutex(sdl->mutex);
78     if (sdl->init_cond)
79         SDL_DestroyCond(sdl->init_cond);
80
81     if (!sdl->sdl_was_already_inited)
82         SDL_Quit();
83
84     return 0;
85 }
86
87 static void compute_overlay_rect(AVFormatContext *s)
88 {
89     AVRational sar, dar; /* sample and display aspect ratios */
90     SDLContext *sdl = s->priv_data;
91     AVStream *st = s->streams[0];
92     AVCodecContext *encctx = st->codec;
93     SDL_Rect *overlay_rect = &sdl->overlay_rect;
94
95     /* compute overlay width and height from the codec context information */
96     sar = st->sample_aspect_ratio.num ? st->sample_aspect_ratio : (AVRational){ 1, 1 };
97     dar = av_mul_q(sar, (AVRational){ encctx->width, encctx->height });
98
99     /* we suppose the screen has a 1/1 sample aspect ratio */
100     if (sdl->window_width && sdl->window_height) {
101         /* fit in the window */
102         if (av_cmp_q(dar, (AVRational){ sdl->window_width, sdl->window_height }) > 0) {
103             /* fit in width */
104             overlay_rect->w = sdl->window_width;
105             overlay_rect->h = av_rescale(overlay_rect->w, dar.den, dar.num);
106         } else {
107             /* fit in height */
108             overlay_rect->h = sdl->window_height;
109             overlay_rect->w = av_rescale(overlay_rect->h, dar.num, dar.den);
110         }
111     } else {
112         if (sar.num > sar.den) {
113             overlay_rect->w = encctx->width;
114             overlay_rect->h = av_rescale(overlay_rect->w, dar.den, dar.num);
115         } else {
116             overlay_rect->h = encctx->height;
117             overlay_rect->w = av_rescale(overlay_rect->h, dar.num, dar.den);
118         }
119         sdl->window_width  = overlay_rect->w;
120         sdl->window_height = overlay_rect->h;
121     }
122
123     overlay_rect->x = (sdl->window_width  - overlay_rect->w) / 2;
124     overlay_rect->y = (sdl->window_height - overlay_rect->h) / 2;
125 }
126
127 #define SDL_BASE_FLAGS (SDL_SWSURFACE|SDL_RESIZABLE)
128
129 static int event_thread(void *arg)
130 {
131     AVFormatContext *s = arg;
132     SDLContext *sdl = s->priv_data;
133     int flags = SDL_BASE_FLAGS | (sdl->window_fullscreen ? SDL_FULLSCREEN : 0);
134     AVStream *st = s->streams[0];
135     AVCodecContext *encctx = st->codec;
136
137     /* initialization */
138     if (SDL_Init(SDL_INIT_VIDEO) != 0) {
139         av_log(s, AV_LOG_ERROR, "Unable to initialize SDL: %s\n", SDL_GetError());
140         sdl->init_ret = AVERROR(EINVAL);
141         goto init_end;
142     }
143
144     SDL_WM_SetCaption(sdl->window_title, sdl->icon_title);
145     sdl->surface = SDL_SetVideoMode(sdl->window_width, sdl->window_height,
146                                     24, flags);
147     if (!sdl->surface) {
148         av_log(sdl, AV_LOG_ERROR, "Unable to set video mode: %s\n", SDL_GetError());
149         sdl->init_ret = AVERROR(EINVAL);
150         goto init_end;
151     }
152
153     sdl->overlay = SDL_CreateYUVOverlay(encctx->width, encctx->height,
154                                         sdl->overlay_fmt, sdl->surface);
155     if (!sdl->overlay || sdl->overlay->pitches[0] < encctx->width) {
156         av_log(s, AV_LOG_ERROR,
157                "SDL does not support an overlay with size of %dx%d pixels\n",
158                encctx->width, encctx->height);
159         sdl->init_ret = AVERROR(EINVAL);
160         goto init_end;
161     }
162
163     sdl->init_ret = 0;
164     av_log(s, AV_LOG_VERBOSE, "w:%d h:%d fmt:%s -> w:%d h:%d\n",
165            encctx->width, encctx->height, av_get_pix_fmt_name(encctx->pix_fmt),
166            sdl->overlay_rect.w, sdl->overlay_rect.h);
167
168 init_end:
169     SDL_LockMutex(sdl->mutex);
170     sdl->inited = 1;
171     SDL_UnlockMutex(sdl->mutex);
172     SDL_CondSignal(sdl->init_cond);
173
174     if (sdl->init_ret < 0)
175         return sdl->init_ret;
176
177     /* event loop */
178     while (!sdl->quit) {
179         int ret;
180         SDL_Event event;
181         SDL_PumpEvents();
182         ret = SDL_PeepEvents(&event, 1, SDL_GETEVENT, SDL_ALLEVENTS);
183         if (ret < 0) {
184             av_log(s, AV_LOG_ERROR, "Error when getting SDL event: %s\n", SDL_GetError());
185             continue;
186         }
187         if (ret == 0) {
188             SDL_Delay(10);
189             continue;
190         }
191
192         switch (event.type) {
193         case SDL_KEYDOWN:
194             switch (event.key.keysym.sym) {
195             case SDLK_ESCAPE:
196             case SDLK_q:
197                 sdl->quit = 1;
198                 break;
199             }
200             break;
201         case SDL_QUIT:
202             sdl->quit = 1;
203             break;
204
205         case SDL_VIDEORESIZE:
206             sdl->window_width  = event.resize.w;
207             sdl->window_height = event.resize.h;
208
209             SDL_LockMutex(sdl->mutex);
210             sdl->surface = SDL_SetVideoMode(sdl->window_width, sdl->window_height, 24, SDL_BASE_FLAGS);
211             if (!sdl->surface) {
212                 av_log(s, AV_LOG_ERROR, "Failed to set SDL video mode: %s\n", SDL_GetError());
213                 sdl->quit = 1;
214             } else {
215                 compute_overlay_rect(s);
216             }
217             SDL_UnlockMutex(sdl->mutex);
218             break;
219
220         default:
221             break;
222         }
223     }
224
225     return 0;
226 }
227
228 static int sdl_write_header(AVFormatContext *s)
229 {
230     SDLContext *sdl = s->priv_data;
231     AVStream *st = s->streams[0];
232     AVCodecContext *encctx = st->codec;
233     int i, ret;
234
235     if (!sdl->window_title)
236         sdl->window_title = av_strdup(s->filename);
237     if (!sdl->icon_title)
238         sdl->icon_title = av_strdup(sdl->window_title);
239
240     if (SDL_WasInit(SDL_INIT_VIDEO)) {
241         av_log(s, AV_LOG_ERROR,
242                "SDL video subsystem was already inited, aborting\n");
243         sdl->sdl_was_already_inited = 1;
244         ret = AVERROR(EINVAL);
245         goto fail;
246     }
247
248     if (   s->nb_streams > 1
249         || encctx->codec_type != AVMEDIA_TYPE_VIDEO
250         || encctx->codec_id   != AV_CODEC_ID_RAWVIDEO) {
251         av_log(s, AV_LOG_ERROR, "Only supports one rawvideo stream\n");
252         ret = AVERROR(EINVAL);
253         goto fail;
254     }
255
256     for (i = 0; sdl_overlay_pix_fmt_map[i].pix_fmt != AV_PIX_FMT_NONE; i++) {
257         if (sdl_overlay_pix_fmt_map[i].pix_fmt == encctx->pix_fmt) {
258             sdl->overlay_fmt = sdl_overlay_pix_fmt_map[i].overlay_fmt;
259             break;
260         }
261     }
262
263     if (!sdl->overlay_fmt) {
264         av_log(s, AV_LOG_ERROR,
265                "Unsupported pixel format '%s', choose one of yuv420p, yuyv422, or uyvy422\n",
266                av_get_pix_fmt_name(encctx->pix_fmt));
267         ret = AVERROR(EINVAL);
268         goto fail;
269     }
270
271     /* compute overlay width and height from the codec context information */
272     compute_overlay_rect(s);
273
274     sdl->init_cond = SDL_CreateCond();
275     if (!sdl->init_cond) {
276         av_log(s, AV_LOG_ERROR, "Could not create SDL condition variable: %s\n", SDL_GetError());
277         ret = AVERROR_EXTERNAL;
278         goto fail;
279     }
280     sdl->mutex = SDL_CreateMutex();
281     if (!sdl->mutex) {
282         av_log(s, AV_LOG_ERROR, "Could not create SDL mutex: %s\n", SDL_GetError());
283         ret = AVERROR_EXTERNAL;
284         goto fail;
285     }
286     sdl->event_thread = SDL_CreateThread(event_thread, s);
287     if (!sdl->event_thread) {
288         av_log(s, AV_LOG_ERROR, "Could not create SDL event thread: %s\n", SDL_GetError());
289         ret = AVERROR_EXTERNAL;
290         goto fail;
291     }
292
293     /* wait until the video system has been inited */
294     SDL_LockMutex(sdl->mutex);
295     if (!sdl->inited) {
296         SDL_CondWait(sdl->init_cond, sdl->mutex);
297     }
298     SDL_UnlockMutex(sdl->mutex);
299     if (sdl->init_ret < 0) {
300         ret = sdl->init_ret;
301         goto fail;
302     }
303     return 0;
304
305 fail:
306     sdl_write_trailer(s);
307     return ret;
308 }
309
310 static int sdl_write_packet(AVFormatContext *s, AVPacket *pkt)
311 {
312     SDLContext *sdl = s->priv_data;
313     AVCodecContext *encctx = s->streams[0]->codec;
314     AVPicture pict;
315     int i;
316
317     if (sdl->quit) {
318         sdl_write_trailer(s);
319         return AVERROR(EIO);
320     }
321     avpicture_fill(&pict, pkt->data, encctx->pix_fmt, encctx->width, encctx->height);
322
323     SDL_LockMutex(sdl->mutex);
324     SDL_FillRect(sdl->surface, &sdl->surface->clip_rect,
325                  SDL_MapRGB(sdl->surface->format, 0, 0, 0));
326     SDL_LockYUVOverlay(sdl->overlay);
327     for (i = 0; i < 3; i++) {
328         sdl->overlay->pixels [i] = pict.data    [i];
329         sdl->overlay->pitches[i] = pict.linesize[i];
330     }
331     SDL_DisplayYUVOverlay(sdl->overlay, &sdl->overlay_rect);
332     SDL_UnlockYUVOverlay(sdl->overlay);
333
334     SDL_UpdateRect(sdl->surface,
335                    sdl->overlay_rect.x, sdl->overlay_rect.y,
336                    sdl->overlay_rect.w, sdl->overlay_rect.h);
337     SDL_UnlockMutex(sdl->mutex);
338
339     return 0;
340 }
341
342 #define OFFSET(x) offsetof(SDLContext,x)
343
344 static const AVOption options[] = {
345     { "window_title", "set SDL window title",           OFFSET(window_title), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_ENCODING_PARAM },
346     { "icon_title",   "set SDL iconified window title", OFFSET(icon_title)  , AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_ENCODING_PARAM },
347     { "window_size",  "set SDL window forced size",     OFFSET(window_width), AV_OPT_TYPE_IMAGE_SIZE, { .str = NULL }, 0, 0, AV_OPT_FLAG_ENCODING_PARAM },
348     { "window_fullscreen", "set SDL window fullscreen", OFFSET(window_fullscreen), AV_OPT_TYPE_INT, { .i64 = 0 }, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
349     { NULL },
350 };
351
352 static const AVClass sdl_class = {
353     .class_name = "sdl outdev",
354     .item_name  = av_default_item_name,
355     .option     = options,
356     .version    = LIBAVUTIL_VERSION_INT,
357 };
358
359 AVOutputFormat ff_sdl_muxer = {
360     .name           = "sdl",
361     .long_name      = NULL_IF_CONFIG_SMALL("SDL output device"),
362     .priv_data_size = sizeof(SDLContext),
363     .audio_codec    = AV_CODEC_ID_NONE,
364     .video_codec    = AV_CODEC_ID_RAWVIDEO,
365     .write_header   = sdl_write_header,
366     .write_packet   = sdl_write_packet,
367     .write_trailer  = sdl_write_trailer,
368     .flags          = AVFMT_NOFILE | AVFMT_VARIABLE_FPS | AVFMT_NOTIMESTAMPS,
369     .priv_class     = &sdl_class,
370 };