netsync.c 9.82 KB
Newer Older
1
/*****************************************************************************
2
 * netsync.c: synchronization between several network clients.
3
 *****************************************************************************
Jean-Paul Saman's avatar
Jean-Paul Saman committed
4
 * Copyright (C) 2004-2009 the VideoLAN team
5 6 7
 * $Id$
 *
 * Authors: Gildas Bazin <gbazin@videolan.org>
Jean-Paul Saman's avatar
Jean-Paul Saman committed
8
 *          Jean-Paul Saman <jpsaman@videolan.org>
9 10 11 12 13 14 15 16 17 18 19 20 21
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
Antoine Cellerier's avatar
Antoine Cellerier committed
22
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23 24 25 26 27
 *****************************************************************************/

/*****************************************************************************
 * Preamble
 *****************************************************************************/
28 29 30
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
31
#include <assert.h>
32

33
#include <vlc_common.h>
34
#include <vlc_plugin.h>
Clément Stenac's avatar
Clément Stenac committed
35 36
#include <vlc_interface.h>
#include <vlc_input.h>
Jean-Paul Saman's avatar
Jean-Paul Saman committed
37
#include <vlc_playlist.h>
38 39 40 41

#ifdef HAVE_UNISTD_H
#    include <unistd.h>
#endif
42
#include <sys/types.h>
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
43
#ifdef HAVE_POLL
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
44 45
#   include <poll.h>
#endif
46

Clément Stenac's avatar
Clément Stenac committed
47
#include <vlc_network.h>
48

49
#define NETSYNC_PORT 9875
50 51 52 53

/*****************************************************************************
 * Module descriptor
 *****************************************************************************/
54 55
static int  Open (vlc_object_t *);
static void Close(vlc_object_t *);
56

57 58
#define NETSYNC_TEXT N_("Network master clock")
#define NETSYNC_LONGTEXT N_("When set then " \
59
  "This VLC instance shall dictate its clock for synchronization " \
60
  "over clients listening on the masters network ip address")
61

62 63
#define MIP_TEXT N_("Master server ip address")
#define MIP_LONGTEXT N_("The IP address of " \
64
  "The network master clock to use for clock synchronization.")
65

66
#define NETSYNC_TIMEOUT_TEXT N_("UDP timeout (in ms)")
67 68
#define NETSYNC_TIMEOUT_LONGTEXT N_("Length of time (in ms) " \
  "until aborting data reception.")
69

70 71
vlc_module_begin()
    set_shortname(N_("Network Sync"))
72
    set_description(N_("Network synchronization"))
73 74
    set_category(CAT_ADVANCED)
    set_subcategory(SUBCAT_ADVANCED_MISC)
75

76 77
    add_bool("netsync-master", false, NULL,
              NETSYNC_TEXT, NETSYNC_LONGTEXT, true)
78
    add_string("netsync-master-ip", NULL, MIP_TEXT, MIP_LONGTEXT,
79
                true)
80
    add_integer("netsync-timeout", 500,
81
                 NETSYNC_TIMEOUT_TEXT, NETSYNC_TIMEOUT_LONGTEXT, true)
82

83 84 85
    set_capability("interface", 0)
    set_callbacks(Open, Close)
vlc_module_end()
86 87 88 89

/*****************************************************************************
 * Local prototypes
 *****************************************************************************/
Laurent Aimar's avatar
Laurent Aimar committed
90 91 92 93 94
struct intf_sys_t {
    int            fd;
    int            timeout;
    bool           is_master;
    playlist_t     *playlist;
95 96

    /* */
Laurent Aimar's avatar
Laurent Aimar committed
97
    input_thread_t *input;
98
    vlc_thread_t   thread;
Laurent Aimar's avatar
Laurent Aimar committed
99
};
100 101 102

static int PlaylistEvent(vlc_object_t *, char const *cmd,
                         vlc_value_t oldval, vlc_value_t newval, void *data);
103 104 105 106

/*****************************************************************************
 * Activate: initialize and create stuff
 *****************************************************************************/
107
static int Open(vlc_object_t *object)
108
{
109
    intf_thread_t *intf = (intf_thread_t*)object;
Laurent Aimar's avatar
Laurent Aimar committed
110
    intf_sys_t    *sys;
111
    int fd;
112

113 114 115 116
    if (!var_InheritBool(intf, "netsync-master")) {
        char *psz_master = var_InheritString(intf, "netsync-master-ip");
        if (psz_master == NULL) {
            msg_Err(intf, "master address not specified");
117 118
            return VLC_EGENERIC;
        }
119 120
        fd = net_ConnectUDP(VLC_OBJECT(intf), psz_master, NETSYNC_PORT, -1);
        free(psz_master);
Laurent Aimar's avatar
Laurent Aimar committed
121
    } else {
122
        fd = net_ListenUDP1(VLC_OBJECT(intf), NULL, NETSYNC_PORT);
Laurent Aimar's avatar
Laurent Aimar committed
123
    }
124

125 126
    if (fd == -1) {
        msg_Err(intf, "Netsync socket failure");
127 128
        return VLC_EGENERIC;
    }
129

130
    intf->pf_run = NULL;
Laurent Aimar's avatar
Laurent Aimar committed
131 132 133 134 135 136 137 138 139 140 141
    intf->p_sys = sys = malloc(sizeof(*sys));
    if (!sys) {
        net_Close(fd);
        return VLC_ENOMEM;
    }

    sys->fd = fd;
    sys->is_master = var_InheritBool(intf, "netsync-master");
    sys->timeout = var_InheritInteger(intf, "netsync-timeout");
    if (sys->timeout < 500)
        sys->timeout = 500;
142
    sys->playlist = pl_Get(intf);
Laurent Aimar's avatar
Laurent Aimar committed
143 144
    sys->input = NULL;

145
    var_AddCallback(sys->playlist, "input-current", PlaylistEvent, intf);
146 147 148 149 150 151
    return VLC_SUCCESS;
}

/*****************************************************************************
 * Close: destroy interface
 *****************************************************************************/
152
void Close(vlc_object_t *object)
153
{
154
    intf_thread_t *intf = (intf_thread_t*)object;
Laurent Aimar's avatar
Laurent Aimar committed
155
    intf_sys_t *sys = intf->p_sys;
156

157 158
    assert(sys->input == NULL);
    var_DelCallback(sys->playlist, "input-current", PlaylistEvent, intf);
Laurent Aimar's avatar
Laurent Aimar committed
159 160
    net_Close(sys->fd);
    free(sys);
161 162
}

163
static mtime_t GetPcrSystem(input_thread_t *input)
Laurent Aimar's avatar
Laurent Aimar committed
164
{
165
    int canc = vlc_savecancel();
166
    /* TODO use the delay */
167
    mtime_t system;
168
    if (input_GetPcrSystem(input, &system, NULL))
169 170
        system = -1;
    vlc_restorecancel(canc);
Laurent Aimar's avatar
Laurent Aimar committed
171

172 173
    return system;
}
Laurent Aimar's avatar
Laurent Aimar committed
174

175 176 177 178 179 180 181 182 183 184
static void *Master(void *handle)
{
    intf_thread_t *intf = handle;
    intf_sys_t *sys = intf->p_sys;
    for (;;) {
        struct pollfd ufd = { .fd = sys->fd, .events = POLLIN, };
        uint64_t data[2];

        if (poll(&ufd, 1, -1) <= 0)
            continue;
Laurent Aimar's avatar
Laurent Aimar committed
185

186 187 188 189 190
        /* We received something */
        struct sockaddr_storage from;
        unsigned struct_size = sizeof(from);
        recvfrom(sys->fd, data, sizeof(data), 0,
                 (struct sockaddr*)&from, &struct_size);
Laurent Aimar's avatar
Laurent Aimar committed
191

192 193 194
        mtime_t master_system = GetPcrSystem(sys->input);
        if (master_system < 0)
            continue;
Laurent Aimar's avatar
Laurent Aimar committed
195

196 197
        data[0] = hton64(mdate());
        data[1] = hton64(master_system);
Laurent Aimar's avatar
Laurent Aimar committed
198

199 200 201
        /* Reply to the sender */
        sendto(sys->fd, data, sizeof(data), 0,
               (struct sockaddr *)&from, struct_size);
Laurent Aimar's avatar
Laurent Aimar committed
202
#if 0
203 204 205 206 207 208 209
        /* not sure we need the client information to sync,
           since we are the master anyway */
        mtime_t client_system = ntoh64(data[0]);
        msg_Dbg(intf, "Master clockref: %"PRId64" -> %"PRId64", from %s "
                 "(date: %"PRId64")", client_system, master_system,
                 (from.ss_family == AF_INET) ? inet_ntoa(((struct sockaddr_in *)&from)->sin_addr)
                 : "non-IPv4", /*date*/ 0);
Laurent Aimar's avatar
Laurent Aimar committed
210
#endif
211
    }
Laurent Aimar's avatar
Laurent Aimar committed
212 213
}

214
static void *Slave(void *handle)
Laurent Aimar's avatar
Laurent Aimar committed
215
{
216
    intf_thread_t *intf = handle;
Laurent Aimar's avatar
Laurent Aimar committed
217 218
    intf_sys_t *sys = intf->p_sys;

219 220 221 222 223 224
    for (;;) {
        struct pollfd ufd = { .fd = sys->fd, .events = POLLIN, };
        uint64_t data[2];

        mtime_t system = GetPcrSystem(sys->input);
        if (system < 0)
Laurent Aimar's avatar
Laurent Aimar committed
225 226
            goto wait;

227 228
        /* Send clock request to the master */
        data[0] = hton64(system);
Laurent Aimar's avatar
Laurent Aimar committed
229

230 231 232
        const mtime_t send_date = mdate();
        if (send(sys->fd, data, sizeof(data[0]), 0) <= 0)
            goto wait;
Laurent Aimar's avatar
Laurent Aimar committed
233

234 235 236 237 238 239
        /* Don't block */
        int ret = poll(&ufd, 1, sys->timeout);
        if (ret == 0)
            continue;
        if (ret < 0)
            goto wait;
Jean-Paul Saman's avatar
Jean-Paul Saman committed
240

241 242 243
        const mtime_t receive_date = mdate();
        if (recv(sys->fd, data, sizeof(data), 0) <= 0)
            goto wait;
244

245 246 247 248
        const mtime_t master_date   = ntoh64(data[0]);
        const mtime_t master_system = ntoh64(data[1]);
        const mtime_t diff_date = receive_date -
                                  ((receive_date - send_date) / 2 + master_date);
249

250 251
        if (master_system > 0) {
            int canc = vlc_savecancel();
252

253
            mtime_t client_system;
254
            if (!input_GetPcrSystem(sys->input, &client_system, NULL)) {
255 256 257 258 259 260 261 262 263 264 265 266
                const mtime_t diff_system = client_system - master_system - diff_date;
                if (diff_system != 0) {
                    input_ModifyPcrSystem(sys->input, true, master_system - diff_date);
#if 0
                    msg_Dbg(intf, "Slave clockref: %"PRId64" -> %"PRId64" -> %"PRId64","
                             " clock diff: %"PRId64", diff: %"PRId64"",
                             system, master_system, client_system,
                             diff_system, diff_date);
#endif
                }
            }
            vlc_restorecancel(canc);
267
        }
268 269
    wait:
        msleep(INTF_IDLE_SLEEP);
270
    }
271
}
272

273 274 275 276 277 278 279 280 281 282 283
static int InputEvent(vlc_object_t *object, char const *cmd,
                      vlc_value_t oldval, vlc_value_t newval, void *data)
{
    VLC_UNUSED(cmd); VLC_UNUSED(oldval); VLC_UNUSED(object);
    intf_thread_t  *intf = data;
    intf_sys_t     *sys = intf->p_sys;

    if (newval.i_int == INPUT_EVENT_DEAD && sys->input) {
        msg_Err(intf, "InputEvent DEAD");
        vlc_cancel(sys->thread);
        vlc_join(sys->thread, NULL);
Laurent Aimar's avatar
Laurent Aimar committed
284
        vlc_object_release(sys->input);
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
        sys->input = NULL;
    }
    return VLC_SUCCESS;
}

static int PlaylistEvent(vlc_object_t *object, char const *cmd,
                         vlc_value_t oldval, vlc_value_t newval, void *data)
{
    VLC_UNUSED(cmd); VLC_UNUSED(oldval); VLC_UNUSED(object);
    intf_thread_t  *intf = data;
    intf_sys_t     *sys = intf->p_sys;

    input_thread_t *input = newval.p_address;
    assert(sys->input == NULL);
    sys->input = vlc_object_hold(input);
    if (vlc_clone(&sys->thread, sys->is_master ? Master : Slave, intf,
                  VLC_THREAD_PRIORITY_INPUT)) {
        vlc_object_release(input);
        return VLC_SUCCESS;
    }
    var_AddCallback(input, "intf-event", InputEvent, intf);
    return VLC_SUCCESS;
307 308
}