sdl.c 11.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
/*
 * Copyright (c) 2011 Stefano Sabatini
 *
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * FFmpeg is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with FFmpeg; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

/**
 * @file
 * libSDL output device
 */

#include <SDL.h>
27 28
#include <SDL_thread.h>

29 30 31 32
#include "libavutil/avstring.h"
#include "libavutil/opt.h"
#include "libavutil/parseutils.h"
#include "libavutil/pixdesc.h"
33
#include "libavutil/time.h"
34 35 36 37 38 39 40 41
#include "avdevice.h"

typedef struct {
    AVClass *class;
    SDL_Surface *surface;
    SDL_Overlay *overlay;
    char *window_title;
    char *icon_title;
Nicolas George's avatar
Nicolas George committed
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 50 51 52 53 54
    SDL_Thread *event_thread;
    SDL_mutex *mutex;
    SDL_cond *init_cond;
    int init_ret; /* return code used to signal initialization errors */
    int inited;
    int quit;
55 56
} SDLContext;

57
static const struct sdl_overlay_pix_fmt_entry {
58
    enum AVPixelFormat pix_fmt; int overlay_fmt;
59
} sdl_overlay_pix_fmt_map[] = {
60 61 62 63
    { AV_PIX_FMT_YUV420P, SDL_IYUV_OVERLAY },
    { AV_PIX_FMT_YUYV422, SDL_YUY2_OVERLAY },
    { AV_PIX_FMT_UYVY422, SDL_UYVY_OVERLAY },
    { AV_PIX_FMT_NONE,    0                },
64 65 66 67 68 69
};

static int sdl_write_trailer(AVFormatContext *s)
{
    SDLContext *sdl = s->priv_data;

70 71 72
    sdl->quit = 1;

    if (sdl->overlay)
73
        SDL_FreeYUVOverlay(sdl->overlay);
74
    sdl->overlay = NULL;
75 76
    if (sdl->event_thread)
        SDL_WaitThread(sdl->event_thread, NULL);
77
    sdl->event_thread = NULL;
78 79
    if (sdl->mutex)
        SDL_DestroyMutex(sdl->mutex);
80
    sdl->mutex = NULL;
81 82
    if (sdl->init_cond)
        SDL_DestroyCond(sdl->init_cond);
83
    sdl->init_cond = NULL;
84

85 86 87 88 89 90
    if (!sdl->sdl_was_already_inited)
        SDL_Quit();

    return 0;
}

91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
static void compute_overlay_rect(AVFormatContext *s)
{
    AVRational sar, dar; /* sample and display aspect ratios */
    SDLContext *sdl = s->priv_data;
    AVStream *st = s->streams[0];
    AVCodecContext *encctx = st->codec;
    SDL_Rect *overlay_rect = &sdl->overlay_rect;

    /* compute overlay width and height from the codec context information */
    sar = st->sample_aspect_ratio.num ? st->sample_aspect_ratio : (AVRational){ 1, 1 };
    dar = av_mul_q(sar, (AVRational){ encctx->width, encctx->height });

    /* we suppose the screen has a 1/1 sample aspect ratio */
    if (sdl->window_width && sdl->window_height) {
        /* fit in the window */
        if (av_cmp_q(dar, (AVRational){ sdl->window_width, sdl->window_height }) > 0) {
            /* fit in width */
            overlay_rect->w = sdl->window_width;
            overlay_rect->h = av_rescale(overlay_rect->w, dar.den, dar.num);
        } else {
            /* fit in height */
            overlay_rect->h = sdl->window_height;
            overlay_rect->w = av_rescale(overlay_rect->h, dar.num, dar.den);
        }
    } else {
        if (sar.num > sar.den) {
            overlay_rect->w = encctx->width;
            overlay_rect->h = av_rescale(overlay_rect->w, dar.den, dar.num);
        } else {
            overlay_rect->h = encctx->height;
            overlay_rect->w = av_rescale(overlay_rect->h, dar.num, dar.den);
        }
        sdl->window_width  = overlay_rect->w;
        sdl->window_height = overlay_rect->h;
    }

    overlay_rect->x = (sdl->window_width  - overlay_rect->w) / 2;
    overlay_rect->y = (sdl->window_height - overlay_rect->h) / 2;
}

131 132
#define SDL_BASE_FLAGS (SDL_SWSURFACE|SDL_RESIZABLE)

133 134 135 136
static int event_thread(void *arg)
{
    AVFormatContext *s = arg;
    SDLContext *sdl = s->priv_data;
137
    int flags = SDL_BASE_FLAGS | (sdl->window_fullscreen ? SDL_FULLSCREEN : 0);
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
    AVStream *st = s->streams[0];
    AVCodecContext *encctx = st->codec;

    /* initialization */
    if (SDL_Init(SDL_INIT_VIDEO) != 0) {
        av_log(s, AV_LOG_ERROR, "Unable to initialize SDL: %s\n", SDL_GetError());
        sdl->init_ret = AVERROR(EINVAL);
        goto init_end;
    }

    SDL_WM_SetCaption(sdl->window_title, sdl->icon_title);
    sdl->surface = SDL_SetVideoMode(sdl->window_width, sdl->window_height,
                                    24, flags);
    if (!sdl->surface) {
        av_log(sdl, AV_LOG_ERROR, "Unable to set video mode: %s\n", SDL_GetError());
        sdl->init_ret = AVERROR(EINVAL);
        goto init_end;
    }

    sdl->overlay = SDL_CreateYUVOverlay(encctx->width, encctx->height,
                                        sdl->overlay_fmt, sdl->surface);
    if (!sdl->overlay || sdl->overlay->pitches[0] < encctx->width) {
        av_log(s, AV_LOG_ERROR,
               "SDL does not support an overlay with size of %dx%d pixels\n",
               encctx->width, encctx->height);
        sdl->init_ret = AVERROR(EINVAL);
        goto init_end;
    }

    sdl->init_ret = 0;
    av_log(s, AV_LOG_VERBOSE, "w:%d h:%d fmt:%s -> w:%d h:%d\n",
           encctx->width, encctx->height, av_get_pix_fmt_name(encctx->pix_fmt),
170
           sdl->overlay_rect.w, sdl->overlay_rect.h);
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186

init_end:
    SDL_LockMutex(sdl->mutex);
    sdl->inited = 1;
    SDL_UnlockMutex(sdl->mutex);
    SDL_CondSignal(sdl->init_cond);

    if (sdl->init_ret < 0)
        return sdl->init_ret;

    /* event loop */
    while (!sdl->quit) {
        int ret;
        SDL_Event event;
        SDL_PumpEvents();
        ret = SDL_PeepEvents(&event, 1, SDL_GETEVENT, SDL_ALLEVENTS);
187
        if (ret < 0) {
188 189
            av_log(s, AV_LOG_ERROR, "Error when getting SDL event: %s\n", SDL_GetError());
            continue;
190 191 192 193 194
        }
        if (ret == 0) {
            SDL_Delay(10);
            continue;
        }
195 196 197 198 199 200 201 202 203 204 205 206 207

        switch (event.type) {
        case SDL_KEYDOWN:
            switch (event.key.keysym.sym) {
            case SDLK_ESCAPE:
            case SDLK_q:
                sdl->quit = 1;
                break;
            }
            break;
        case SDL_QUIT:
            sdl->quit = 1;
            break;
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223

        case SDL_VIDEORESIZE:
            sdl->window_width  = event.resize.w;
            sdl->window_height = event.resize.h;

            SDL_LockMutex(sdl->mutex);
            sdl->surface = SDL_SetVideoMode(sdl->window_width, sdl->window_height, 24, SDL_BASE_FLAGS);
            if (!sdl->surface) {
                av_log(s, AV_LOG_ERROR, "Failed to set SDL video mode: %s\n", SDL_GetError());
                sdl->quit = 1;
            } else {
                compute_overlay_rect(s);
            }
            SDL_UnlockMutex(sdl->mutex);
            break;

224 225 226 227 228 229 230 231
        default:
            break;
        }
    }

    return 0;
}

232 233 234 235 236 237 238
static int sdl_write_header(AVFormatContext *s)
{
    SDLContext *sdl = s->priv_data;
    AVStream *st = s->streams[0];
    AVCodecContext *encctx = st->codec;
    int i, ret;

239 240
    if (!sdl->window_title)
        sdl->window_title = av_strdup(s->filename);
241 242 243 244 245
    if (!sdl->icon_title)
        sdl->icon_title = av_strdup(sdl->window_title);

    if (SDL_WasInit(SDL_INIT_VIDEO)) {
        av_log(s, AV_LOG_ERROR,
246
               "SDL video subsystem was already inited, aborting\n");
247 248 249 250 251 252 253
        sdl->sdl_was_already_inited = 1;
        ret = AVERROR(EINVAL);
        goto fail;
    }

    if (   s->nb_streams > 1
        || encctx->codec_type != AVMEDIA_TYPE_VIDEO
254
        || encctx->codec_id   != AV_CODEC_ID_RAWVIDEO) {
255 256 257 258 259
        av_log(s, AV_LOG_ERROR, "Only supports one rawvideo stream\n");
        ret = AVERROR(EINVAL);
        goto fail;
    }

260
    for (i = 0; sdl_overlay_pix_fmt_map[i].pix_fmt != AV_PIX_FMT_NONE; i++) {
261 262 263 264 265 266 267 268
        if (sdl_overlay_pix_fmt_map[i].pix_fmt == encctx->pix_fmt) {
            sdl->overlay_fmt = sdl_overlay_pix_fmt_map[i].overlay_fmt;
            break;
        }
    }

    if (!sdl->overlay_fmt) {
        av_log(s, AV_LOG_ERROR,
269
               "Unsupported pixel format '%s', choose one of yuv420p, yuyv422, or uyvy422\n",
270 271 272 273 274 275
               av_get_pix_fmt_name(encctx->pix_fmt));
        ret = AVERROR(EINVAL);
        goto fail;
    }

    /* compute overlay width and height from the codec context information */
276
    compute_overlay_rect(s);
277

278 279 280 281
    sdl->init_cond = SDL_CreateCond();
    if (!sdl->init_cond) {
        av_log(s, AV_LOG_ERROR, "Could not create SDL condition variable: %s\n", SDL_GetError());
        ret = AVERROR_EXTERNAL;
282 283
        goto fail;
    }
284 285 286 287 288 289 290 291 292 293
    sdl->mutex = SDL_CreateMutex();
    if (!sdl->mutex) {
        av_log(s, AV_LOG_ERROR, "Could not create SDL mutex: %s\n", SDL_GetError());
        ret = AVERROR_EXTERNAL;
        goto fail;
    }
    sdl->event_thread = SDL_CreateThread(event_thread, s);
    if (!sdl->event_thread) {
        av_log(s, AV_LOG_ERROR, "Could not create SDL event thread: %s\n", SDL_GetError());
        ret = AVERROR_EXTERNAL;
294 295 296
        goto fail;
    }

297 298
    /* wait until the video system has been inited */
    SDL_LockMutex(sdl->mutex);
299
    while (!sdl->inited) {
300 301 302 303 304 305 306
        SDL_CondWait(sdl->init_cond, sdl->mutex);
    }
    SDL_UnlockMutex(sdl->mutex);
    if (sdl->init_ret < 0) {
        ret = sdl->init_ret;
        goto fail;
    }
307 308 309 310 311 312 313 314 315 316 317 318 319 320
    return 0;

fail:
    sdl_write_trailer(s);
    return ret;
}

static int sdl_write_packet(AVFormatContext *s, AVPacket *pkt)
{
    SDLContext *sdl = s->priv_data;
    AVCodecContext *encctx = s->streams[0]->codec;
    AVPicture pict;
    int i;

321 322
    if (sdl->quit) {
        sdl_write_trailer(s);
323
        return AVERROR(EIO);
324
    }
325 326
    avpicture_fill(&pict, pkt->data, encctx->pix_fmt, encctx->width, encctx->height);

327
    SDL_LockMutex(sdl->mutex);
328 329 330 331 332 333 334
    SDL_FillRect(sdl->surface, &sdl->surface->clip_rect,
                 SDL_MapRGB(sdl->surface->format, 0, 0, 0));
    SDL_LockYUVOverlay(sdl->overlay);
    for (i = 0; i < 3; i++) {
        sdl->overlay->pixels [i] = pict.data    [i];
        sdl->overlay->pitches[i] = pict.linesize[i];
    }
335
    SDL_DisplayYUVOverlay(sdl->overlay, &sdl->overlay_rect);
336 337
    SDL_UnlockYUVOverlay(sdl->overlay);

338 339 340
    SDL_UpdateRect(sdl->surface,
                   sdl->overlay_rect.x, sdl->overlay_rect.y,
                   sdl->overlay_rect.w, sdl->overlay_rect.h);
341
    SDL_UnlockMutex(sdl->mutex);
342 343 344 345 346 347 348

    return 0;
}

#define OFFSET(x) offsetof(SDLContext,x)

static const AVOption options[] = {
349 350 351 352
    { "window_title", "set SDL window title",           OFFSET(window_title), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_ENCODING_PARAM },
    { "icon_title",   "set SDL iconified window title", OFFSET(icon_title)  , AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_ENCODING_PARAM },
    { "window_size",  "set SDL window forced size",     OFFSET(window_width), AV_OPT_TYPE_IMAGE_SIZE, { .str = NULL }, 0, 0, AV_OPT_FLAG_ENCODING_PARAM },
    { "window_fullscreen", "set SDL window fullscreen", OFFSET(window_fullscreen), AV_OPT_TYPE_INT, { .i64 = 0 }, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
353 354 355 356 357 358 359 360
    { NULL },
};

static const AVClass sdl_class = {
    .class_name = "sdl outdev",
    .item_name  = av_default_item_name,
    .option     = options,
    .version    = LIBAVUTIL_VERSION_INT,
361
    .category   = AV_CLASS_CATEGORY_DEVICE_VIDEO_OUTPUT,
362 363 364 365 366 367
};

AVOutputFormat ff_sdl_muxer = {
    .name           = "sdl",
    .long_name      = NULL_IF_CONFIG_SMALL("SDL output device"),
    .priv_data_size = sizeof(SDLContext),
368 369
    .audio_codec    = AV_CODEC_ID_NONE,
    .video_codec    = AV_CODEC_ID_RAWVIDEO,
370 371 372
    .write_header   = sdl_write_header,
    .write_packet   = sdl_write_packet,
    .write_trailer  = sdl_write_trailer,
373
    .flags          = AVFMT_NOFILE | AVFMT_VARIABLE_FPS | AVFMT_NOTIMESTAMPS,
374 375
    .priv_class     = &sdl_class,
};