scrcpy.c 13.1 KB
Newer Older
R
Romain Vimont 已提交
1
#include "scrcpy.h"
R
Romain Vimont 已提交
2

R
Romain Vimont 已提交
3 4
#include <stdio.h>
#include <string.h>
R
Romain Vimont 已提交
5 6
#include <unistd.h>
#include <libavformat/avformat.h>
R
Romain Vimont 已提交
7
#include <sys/time.h>
R
Romain Vimont 已提交
8 9
#include <SDL2/SDL.h>

10
#ifdef _WIN32
11 12
// not needed here, but winsock2.h must never be included AFTER windows.h
# include <winsock2.h>
13 14 15
# include <windows.h>
#endif

R
Romain Vimont 已提交
16
#include "controller.h"
R
Romain Vimont 已提交
17
#include "decoder.h"
18
#include "device.h"
R
Romain Vimont 已提交
19
#include "events.h"
N
npes87184 已提交
20
#include "file_handler.h"
21 22
#include "fps_counter.h"
#include "input_manager.h"
R
Romain Vimont 已提交
23
#include "recorder.h"
24
#include "screen.h"
R
Romain Vimont 已提交
25
#include "server.h"
R
Romain Vimont 已提交
26
#include "stream.h"
27
#include "tiny_xpm.h"
28
#include "video_buffer.h"
R
Romain Vimont 已提交
29 30
#include "util/log.h"
#include "util/net.h"
R
Romain Vimont 已提交
31

32
static struct server server;
33
static struct screen screen;
R
Romain Vimont 已提交
34
static struct fps_counter fps_counter;
35
static struct video_buffer video_buffer;
R
Romain Vimont 已提交
36
static struct stream stream;
R
Romain Vimont 已提交
37
static struct decoder decoder;
R
Romain Vimont 已提交
38
static struct recorder recorder;
R
Romain Vimont 已提交
39
static struct controller controller;
N
npes87184 已提交
40
static struct file_handler file_handler;
R
Romain Vimont 已提交
41

42 43
static struct input_manager input_manager = {
    .controller = &controller,
44
    .fps_counter = &fps_counter,
45
    .screen = &screen,
X
xeropresence 已提交
46
    .repeat = 0,
R
Romain Vimont 已提交
47 48 49 50 51 52 53

    // initialized later
    .prefer_text = false,
    .sdl_shortcut_mods = {
        .data = {0},
        .count = 0,
    },
54 55
};

56
#ifdef _WIN32
57
BOOL WINAPI windows_ctrl_handler(DWORD ctrl_type) {
58 59 60 61 62 63 64 65 66 67
    if (ctrl_type == CTRL_C_EVENT) {
        SDL_Event event;
        event.type = SDL_QUIT;
        SDL_PushEvent(&event);
        return TRUE;
    }
    return FALSE;
}
#endif // _WIN32

68 69
// init SDL and set appropriate hints
static bool
70 71
sdl_init_and_configure(bool display, const char *render_driver,
                       bool disable_screensaver) {
72 73 74 75 76 77 78 79
    uint32_t flags = display ? SDL_INIT_VIDEO : SDL_INIT_EVENTS;
    if (SDL_Init(flags)) {
        LOGC("Could not initialize SDL: %s", SDL_GetError());
        return false;
    }

    atexit(SDL_Quit);

80 81 82 83 84 85 86 87
#ifdef _WIN32
    // Clean up properly on Ctrl+C on Windows
    bool ok = SetConsoleCtrlHandler(windows_ctrl_handler, TRUE);
    if (!ok) {
        LOGW("Could not set Ctrl+C handler");
    }
#endif // _WIN32

88 89 90 91
    if (!display) {
        return true;
    }

92 93 94 95
    if (render_driver && !SDL_SetHint(SDL_HINT_RENDER_DRIVER, render_driver)) {
        LOGW("Could not set render driver");
    }

R
Romain Vimont 已提交
96 97 98
    // Linear filtering
    if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1")) {
        LOGW("Could not enable linear filtering");
99 100 101 102 103 104 105 106 107
    }

#ifdef SCRCPY_SDL_HAS_HINT_MOUSE_FOCUS_CLICKTHROUGH
    // Handle a click to gain focus as any other click
    if (!SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1")) {
        LOGW("Could not enable mouse focus clickthrough");
    }
#endif

108 109 110 111 112 113 114
#ifdef SCRCPY_SDL_HAS_HINT_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR
    // Disable compositor bypassing on X11
    if (!SDL_SetHint(SDL_HINT_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR, "0")) {
        LOGW("Could not disable X11 compositor bypass");
    }
#endif

R
Romain Vimont 已提交
115 116 117 118 119
    // Do not minimize on focus loss
    if (!SDL_SetHint(SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, "0")) {
        LOGW("Could not disable minimize on focus loss");
    }

120 121 122 123 124 125 126
    if (disable_screensaver) {
        LOGD("Screensaver disabled");
        SDL_DisableScreenSaver();
    } else {
        LOGD("Screensaver enabled");
        SDL_EnableScreenSaver();
    }
127 128 129 130 131

    return true;
}


132 133 134 135 136 137 138 139 140 141
#if defined(__APPLE__) || defined(__WINDOWS__)
# define CONTINUOUS_RESIZING_WORKAROUND
#endif

#ifdef CONTINUOUS_RESIZING_WORKAROUND
// On Windows and MacOS, resizing blocks the event loop, so resizing events are
// not triggered. As a workaround, handle them in an event handler.
//
// <https://bugzilla.libsdl.org/show_bug.cgi?id=2077>
// <https://stackoverflow.com/a/40693139/1987178>
R
Romain Vimont 已提交
142 143
static int
event_watcher(void *data, SDL_Event *event) {
R
Romain Vimont 已提交
144
    (void) data;
R
Romain Vimont 已提交
145
    if (event->type == SDL_WINDOWEVENT
146
            && event->window.event == SDL_WINDOWEVENT_RESIZED) {
R
Romain Vimont 已提交
147 148
        // In practice, it seems to always be called from the same thread in
        // that specific case. Anyway, it's just a workaround.
149
        screen_render(&screen, true);
150 151 152 153 154
    }
    return 0;
}
#endif

155
static bool
R
Romain Vimont 已提交
156
is_apk(const char *file) {
157 158 159 160
    const char *ext = strrchr(file, '.');
    return ext && !strcmp(ext, ".apk");
}

161 162 163 164 165 166 167
enum event_result {
    EVENT_RESULT_CONTINUE,
    EVENT_RESULT_STOPPED_BY_USER,
    EVENT_RESULT_STOPPED_BY_EOS,
};

static enum event_result
168
handle_event(SDL_Event *event, const struct scrcpy_options *options) {
169 170 171 172 173 174 175 176
    switch (event->type) {
        case EVENT_STREAM_STOPPED:
            LOGD("Video stream stopped");
            return EVENT_RESULT_STOPPED_BY_EOS;
        case SDL_QUIT:
            LOGD("User requested to quit");
            return EVENT_RESULT_STOPPED_BY_USER;
        case SDL_DROPFILE: {
177
            if (!options->control) {
178 179
                break;
            }
R
Romain Vimont 已提交
180 181 182 183 184 185 186
            char *file = strdup(event->drop.file);
            SDL_free(event->drop.file);
            if (!file) {
                LOGW("Could not strdup drop filename\n");
                break;
            }

187
            file_handler_action_t action;
R
Romain Vimont 已提交
188
            if (is_apk(file)) {
189 190 191 192
                action = ACTION_INSTALL_APK;
            } else {
                action = ACTION_PUSH_FILE;
            }
R
Romain Vimont 已提交
193
            file_handler_request(&file_handler, action, file);
194 195 196
            break;
        }
    }
197 198

    bool consumed = screen_handle_event(&screen, event);
199 200 201 202 203
    if (consumed) {
        goto end;
    }

    consumed = input_manager_handle_event(&input_manager, event);
204 205
    (void) consumed;

206
end:
207 208 209
    return EVENT_RESULT_CONTINUE;
}

210
static bool
211
event_loop(const struct scrcpy_options *options) {
212
#ifdef CONTINUOUS_RESIZING_WORKAROUND
213
    if (options->display) {
214 215
        SDL_AddEventWatch(event_watcher, NULL);
    }
216
#endif
R
Romain Vimont 已提交
217 218
    SDL_Event event;
    while (SDL_WaitEvent(&event)) {
219
        enum event_result result = handle_event(&event, options);
220 221
        switch (result) {
            case EVENT_RESULT_STOPPED_BY_USER:
222
                return true;
223
            case EVENT_RESULT_STOPPED_BY_EOS:
R
Romain Vimont 已提交
224
                LOGW("Device disconnected");
225
                return false;
226
            case EVENT_RESULT_CONTINUE:
227
                break;
R
Romain Vimont 已提交
228 229
        }
    }
230
    return false;
R
Romain Vimont 已提交
231 232
}

R
Romain Vimont 已提交
233 234
static SDL_LogPriority
sdl_priority_from_av_level(int level) {
R
Romain Vimont 已提交
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
    switch (level) {
        case AV_LOG_PANIC:
        case AV_LOG_FATAL:
            return SDL_LOG_PRIORITY_CRITICAL;
        case AV_LOG_ERROR:
            return SDL_LOG_PRIORITY_ERROR;
        case AV_LOG_WARNING:
            return SDL_LOG_PRIORITY_WARN;
        case AV_LOG_INFO:
            return SDL_LOG_PRIORITY_INFO;
    }
    // do not forward others, which are too verbose
    return 0;
}

static void
av_log_callback(void *avcl, int level, const char *fmt, va_list vl) {
R
Romain Vimont 已提交
252
    (void) avcl;
R
Romain Vimont 已提交
253 254 255 256
    SDL_LogPriority priority = sdl_priority_from_av_level(level);
    if (priority == 0) {
        return;
    }
R
Romain Vimont 已提交
257
    char *local_fmt = malloc(strlen(fmt) + 10);
R
Romain Vimont 已提交
258
    if (!local_fmt) {
R
Romain Vimont 已提交
259
        LOGC("Could not allocate string");
R
Romain Vimont 已提交
260 261 262 263 264 265
        return;
    }
    // strcpy is safe here, the destination is large enough
    strcpy(local_fmt, "[FFmpeg] ");
    strcpy(local_fmt + 9, fmt);
    SDL_LogMessageV(SDL_LOG_CATEGORY_VIDEO, priority, local_fmt, vl);
R
Romain Vimont 已提交
266
    free(local_fmt);
R
Romain Vimont 已提交
267 268
}

269
bool
R
Romain Vimont 已提交
270
scrcpy(const struct scrcpy_options *options) {
271 272 273 274
    if (!server_init(&server)) {
        return false;
    }

R
Romain Vimont 已提交
275 276
    bool ret = false;

277 278 279 280 281 282 283 284 285
    bool server_started = false;
    bool fps_counter_initialized = false;
    bool video_buffer_initialized = false;
    bool file_handler_initialized = false;
    bool recorder_initialized = false;
    bool stream_started = false;
    bool controller_initialized = false;
    bool controller_started = false;

286
    bool record = !!options->record_filename;
R
Romain Vimont 已提交
287
    struct server_params params = {
288
        .log_level = options->log_level,
R
Romain Vimont 已提交
289
        .crop = options->crop,
R
Romain Vimont 已提交
290
        .port_range = options->port_range,
R
Romain Vimont 已提交
291 292
        .max_size = options->max_size,
        .bit_rate = options->bit_rate,
R
Romain Vimont 已提交
293
        .max_fps = options->max_fps,
294
        .lock_video_orientation = options->lock_video_orientation,
295
        .control = options->control,
E
e_vigurskiy 已提交
296
        .display_id = options->display_id,
297
        .show_touches = options->show_touches,
298
        .stay_awake = options->stay_awake,
T
Tzah Mazuz 已提交
299
        .codec_options = options->codec_options,
T
Tzah Mazuz 已提交
300
        .encoder_name = options->encoder_name,
R
Romain Vimont 已提交
301
        .force_adb_forward = options->force_adb_forward,
Y
Yu-Chen Lin 已提交
302
        .power_off_on_close = options->power_off_on_close,
R
Romain Vimont 已提交
303 304
    };
    if (!server_start(&server, options->serial, &params)) {
305
        goto end;
R
Romain Vimont 已提交
306 307
    }

308
    server_started = true;
309

310 311
    if (!sdl_init_and_configure(options->display, options->render_driver,
                                options->disable_screensaver)) {
R
Romain Vimont 已提交
312
        goto end;
R
Romain Vimont 已提交
313 314
    }

315
    if (!server_connect_to(&server)) {
R
Romain Vimont 已提交
316
        goto end;
R
Romain Vimont 已提交
317 318 319
    }

    char device_name[DEVICE_NAME_FIELD_LENGTH];
320
    struct size frame_size;
R
Romain Vimont 已提交
321

R
Romain Vimont 已提交
322 323 324
    // screenrecord does not send frames when the screen content does not
    // change therefore, we transmit the screen size before the video stream,
    // to be able to init the window immediately
325
    if (!device_read_info(server.video_socket, device_name, &frame_size)) {
R
Romain Vimont 已提交
326
        goto end;
R
Romain Vimont 已提交
327 328
    }

R
Romain Vimont 已提交
329
    struct decoder *dec = NULL;
330
    if (options->display) {
R
Romain Vimont 已提交
331 332 333 334 335
        if (!fps_counter_init(&fps_counter)) {
            goto end;
        }
        fps_counter_initialized = true;

336
        if (!video_buffer_init(&video_buffer, options->render_expired_frames)) {
R
Romain Vimont 已提交
337
            goto end;
R
Romain Vimont 已提交
338
        }
R
Romain Vimont 已提交
339
        video_buffer_initialized = true;
R
Romain Vimont 已提交
340

341
        if (options->control) {
342 343
            if (!file_handler_init(&file_handler, server.serial,
                                   options->push_target)) {
R
Romain Vimont 已提交
344 345 346
                goto end;
            }
            file_handler_initialized = true;
R
Romain Vimont 已提交
347
        }
348

349
        decoder_init(&decoder, &video_buffer);
R
Romain Vimont 已提交
350 351
        dec = &decoder;
    }
R
Romain Vimont 已提交
352

R
Romain Vimont 已提交
353
    struct recorder *rec = NULL;
354
    if (record) {
R
Romain Vimont 已提交
355 356 357 358
        if (!recorder_init(&recorder,
                           options->record_filename,
                           options->record_format,
                           frame_size)) {
R
Romain Vimont 已提交
359
            goto end;
R
Romain Vimont 已提交
360 361
        }
        rec = &recorder;
R
Romain Vimont 已提交
362
        recorder_initialized = true;
R
Romain Vimont 已提交
363 364
    }

R
Romain Vimont 已提交
365 366
    av_log_set_callback(av_log_callback);

367
    stream_init(&stream, server.video_socket, dec, rec);
R
Romain Vimont 已提交
368

369 370
    if (options->display) {
        if (options->control) {
371
            if (!controller_init(&controller, server.control_socket)) {
R
Romain Vimont 已提交
372
                goto end;
373
            }
R
Romain Vimont 已提交
374
            controller_initialized = true;
R
Romain Vimont 已提交
375

376
            if (!controller_start(&controller)) {
R
Romain Vimont 已提交
377
                goto end;
378
            }
R
Romain Vimont 已提交
379
            controller_started = true;
R
Romain Vimont 已提交
380
        }
R
Romain Vimont 已提交
381

B
beango1 已提交
382 383 384
        const char *window_title =
            options->window_title ? options->window_title : device_name;

385 386 387 388 389 390 391 392 393 394 395 396 397
        struct screen_params screen_params = {
            .window_title = window_title,
            .frame_size = frame_size,
            .always_on_top = options->always_on_top,
            .window_x = options->window_x,
            .window_y = options->window_y,
            .window_width = options->window_width,
            .window_height = options->window_height,
            .window_borderless = options->window_borderless,
            .rotation = options->rotation,
            .mipmaps = options->mipmaps,
        };

R
Romain Vimont 已提交
398 399
        if (!screen_init(&screen, &video_buffer, &fps_counter,
                         &screen_params)) {
R
Romain Vimont 已提交
400
            goto end;
R
Romain Vimont 已提交
401 402
        }

403 404 405 406 407 408
        if (options->turn_screen_off) {
            struct control_msg msg;
            msg.type = CONTROL_MSG_TYPE_SET_SCREEN_POWER_MODE;
            msg.set_screen_power_mode.mode = SCREEN_POWER_MODE_OFF;

            if (!controller_push_msg(&controller, &msg)) {
R
Romain Vimont 已提交
409
                LOGW("Could not request 'set screen power mode'");
410 411 412
            }
        }

R
Romain Vimont 已提交
413 414 415
        if (options->fullscreen) {
            screen_switch_fullscreen(&screen);
        }
R
Romain Vimont 已提交
416
    }
R
Romain Vimont 已提交
417

418 419 420 421 422 423 424
    // now we consumed the header values, the socket receives the video stream
    // start the stream
    if (!stream_start(&stream)) {
        goto end;
    }
    stream_started = true;

425
    input_manager_init(&input_manager, options);
R
Romain Vimont 已提交
426

R
Romain Vimont 已提交
427
    ret = event_loop(options);
R
Romain Vimont 已提交
428
    LOGD("quit...");
429

430 431
    screen_destroy(&screen);

R
Romain Vimont 已提交
432 433 434 435 436 437 438
end:
    // stop stream and controller so that they don't continue once their socket
    // is shutdown
    if (stream_started) {
        stream_stop(&stream);
    }
    if (controller_started) {
R
Romain Vimont 已提交
439
        controller_stop(&controller);
R
Romain Vimont 已提交
440 441 442 443
    }
    if (file_handler_initialized) {
        file_handler_stop(&file_handler);
    }
R
Romain Vimont 已提交
444 445 446
    if (fps_counter_initialized) {
        fps_counter_interrupt(&fps_counter);
    }
R
Romain Vimont 已提交
447

448 449 450 451
    if (server_started) {
        // shutdown the sockets and kill the server
        server_stop(&server);
    }
R
Romain Vimont 已提交
452 453 454 455 456 457 458

    // now that the sockets are shutdown, the stream and controller are
    // interrupted, we can join them
    if (stream_started) {
        stream_join(&stream);
    }
    if (controller_started) {
R
Romain Vimont 已提交
459 460
        controller_join(&controller);
    }
R
Romain Vimont 已提交
461
    if (controller_initialized) {
R
Romain Vimont 已提交
462 463
        controller_destroy(&controller);
    }
R
Romain Vimont 已提交
464 465

    if (recorder_initialized) {
R
Romain Vimont 已提交
466 467
        recorder_destroy(&recorder);
    }
R
Romain Vimont 已提交
468 469

    if (file_handler_initialized) {
R
Romain Vimont 已提交
470 471 472
        file_handler_join(&file_handler);
        file_handler_destroy(&file_handler);
    }
R
Romain Vimont 已提交
473 474

    if (video_buffer_initialized) {
R
Romain Vimont 已提交
475 476
        video_buffer_destroy(&video_buffer);
    }
R
Romain Vimont 已提交
477

R
Romain Vimont 已提交
478 479 480 481 482
    if (fps_counter_initialized) {
        fps_counter_join(&fps_counter);
        fps_counter_destroy(&fps_counter);
    }

483
    server_destroy(&server);
R
Romain Vimont 已提交
484

R
Romain Vimont 已提交
485
    return ret;
R
Romain Vimont 已提交
486
}