<commit_before>/*****************************************************************************
 * rtsp.c: RTSP support for RTP stream output module
 *****************************************************************************
 * Copyright (C) 2003-2004, 2010 the VideoLAN team
 * Copyright © 2007 <NAME>
 *
 * $Id$
 *
 * Authors: <NAME> <<EMAIL>>
 *          <NAME>
 *
 * 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
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

/*****************************************************************************
 * Preamble
 *****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include <vlc_common.h>
#include <vlc_sout.h>

#include <vlc_httpd.h>
#include <vlc_url.h>
#include <vlc_charset.h>
#include <vlc_fs.h>
#include <vlc_network.h>
#include <vlc_rand.h>
#include <assert.h>
#include <errno.h>
#include <stdlib.h>

#ifndef WIN32
# include <locale.h>
#endif
#ifdef HAVE_XLOCALE_H
# include <xlocale.h>
#endif

#include "rtp.h"

typedef struct rtsp_session_t rtsp_session_t;

struct rtsp_stream_t
{
    vlc_mutex_t     lock;
    vlc_object_t   *owner;
    vod_media_t    *vod_media;
    httpd_host_t   *host;
    httpd_url_t    *url;
    char           *psz_path;
    unsigned        track_id;
    unsigned        port;

    int             sessionc;
    rtsp_session_t **sessionv;

    int             timeout;
    vlc_timer_t     timer;
};


static int  RtspCallback( httpd_callback_sys_t *p_args,
                          httpd_client_t *cl, httpd_message_t *answer,
                          const httpd_message_t *query );
static int  RtspCallbackId( httpd_callback_sys_t *p_args,
                            httpd_client_t *cl, httpd_message_t *answer,
                            const httpd_message_t *query );
static void RtspClientDel( rtsp_stream_t *rtsp, rtsp_session_t *session );

static void RtspTimeOut( void *data );

rtsp_stream_t *RtspSetup( vlc_object_t *owner, vod_media_t *media,
                          const vlc_url_t *url )
{
    rtsp_stream_t *rtsp = malloc( sizeof( *rtsp ) );

    if( rtsp == NULL || ( url->i_port > 99999 ) )
    {
        free( rtsp );
        return NULL;
    }

    rtsp->owner = owner;
    rtsp->vod_media = media;
    rtsp->sessionc = 0;
    rtsp->sessionv = NULL;
    rtsp->host = NULL;
    rtsp->url = NULL;
    rtsp->psz_path = NULL;
    rtsp->track_id = 0;
    vlc_mutex_init( &rtsp->lock );

    rtsp->timeout = var_InheritInteger(owner, "rtsp-timeout");
    if (rtsp->timeout > 0)
    {
        if (vlc_timer_create(&rtsp->timer, RtspTimeOut, rtsp))
            goto error;
    }

    rtsp->port = (url->i_port > 0) ? url->i_port : 554;
    rtsp->psz_path = strdup( ( url->psz_path != NULL ) ? url->psz_path : "/" );
    if( rtsp->psz_path == NULL )
        goto error;

    msg_Dbg( owner, "RTSP stream: host %s port %d at %s",
             url->psz_host, rtsp->port, rtsp->psz_path );

    rtsp->host = httpd_HostNew( VLC_OBJECT(owner), url->psz_host,
                                rtsp->port );
    if( rtsp->host == NULL )
        goto error;

    rtsp->url = httpd_UrlNewUnique( rtsp->host, rtsp->psz_path,
                                    NULL, NULL, NULL );
    if( rtsp->url == NULL )
        goto error;

    httpd_UrlCatch( rtsp->url, HTTPD_MSG_DESCRIBE, RtspCallback, (void*)rtsp );
    httpd_UrlCatch( rtsp->url, HTTPD_MSG_SETUP,    RtspCallback, (void*)rtsp );
    httpd_UrlCatch( rtsp->url, HTTPD_MSG_PLAY,     RtspCallback, (void*)rtsp );
    httpd_UrlCatch( rtsp->url, HTTPD_MSG_PAUSE,    RtspCallback, (void*)rtsp );
    httpd_UrlCatch( rtsp->url, HTTPD_MSG_GETPARAMETER, RtspCallback,
                    (void*)rtsp );
    httpd_UrlCatch( rtsp->url, HTTPD_MSG_TEARDOWN, RtspCallback, (void*)rtsp );
    return rtsp;

error:
    RtspUnsetup( rtsp );
    return NULL;
}


void RtspUnsetup( rtsp_stream_t *rtsp )
{
    if( rtsp->url )
        httpd_UrlDelete( rtsp->url );

    if( rtsp->host )
        httpd_HostDelete( rtsp->host );

    while( rtsp->sessionc > 0 )
        RtspClientDel( rtsp, rtsp->sessionv[0] );

    if (rtsp->timeout > 0)
        vlc_timer_destroy(rtsp->timer);

    free( rtsp->psz_path );
    vlc_mutex_destroy( &rtsp->lock );

    free( rtsp );
}


struct rtsp_stream_id_t
{
    rtsp_stream_t    *stream;
    sout_stream_id_t *sout_id;
    httpd_url_t      *url;
    unsigned          track_id;
    uint32_t          ssrc;
    unsigned          clock_rate; /* needed to compute rtptime in RTP-Info */
    int               mcast_fd;
};


typedef struct rtsp_strack_t rtsp_strack_t;

/* For unicast streaming */
struct rtsp_session_t
{
    rtsp_stream_t *stream;
    uint64_t       id;
    mtime_t        last_seen; /* for timeouts */

    /* output (id-access) */
    int            trackc;
    rtsp_strack_t *trackv;
};


/* Unicast session track */
struct rtsp_strack_t
{
    rtsp_stream_id_t  *id;
    sout_stream_id_t  *sout_id;
    int          setup_fd;  /* socket created by the SETUP request */
    int          rtp_fd;    /* socket used by the RTP output, when playing */
    uint32_t     ssrc;
    uint16_t     seq_init;
};

static void RtspTrackClose( rtsp_strack_t *tr );

#define TRACK_PATH_SIZE (sizeof("/trackID=999") - 1)

char *RtspAppendTrackPath( rtsp_stream_id_t *id, const char *base )
{
    const char *sep = strlen( base ) > 0 && base[strlen( base ) - 1] == '/' ?
                      "" : "/";
    char *url;

    if( asprintf( &url, "%s%strackID=%u", base, sep, id->track_id ) == -1 )
        url = NULL;
    return url;
}


rtsp_stream_id_t *RtspAddId( rtsp_stream_t *rtsp, sout_stream_id_t *sid,
                             uint32_t ssrc, unsigned clock_rate,
                             int mcast_fd)
{
    if (rtsp->track_id > 999)
    {
        msg_Err(rtsp->owner, "RTSP: too many IDs!");
        return NULL;
    }

    char *urlbuf;
    rtsp_stream_id_t *id = malloc( sizeof( *id ) );
    httpd_url_t *url;

    if( id == NULL )
        return NULL;

    id->stream = rtsp;
    id->sout_id = sid;
    id->track_id = rtsp->track_id;
    id->ssrc = ssrc;
    id->clock_rate = clock_rate;
    id->mcast_fd = mcast_fd;

    urlbuf = RtspAppendTrackPath( id, rtsp->psz_path );
    if( urlbuf == NULL )
    {
        free( id );
        return NULL;
    }

    msg_Dbg( rtsp->owner, "RTSP: adding %s", urlbuf );
    url = id->url = httpd_UrlNewUnique( rtsp->host, urlbuf, NULL, NULL, NULL );
    free( urlbuf );

    if( url == NULL )
    {
        free( id );
        return NULL;
    }

    httpd_UrlCatch( url, HTTPD_MSG_DESCRIBE, RtspCallbackId, (void *)id );
    httpd_UrlCatch( url, HTTPD_MSG_SETUP,    RtspCallbackId, (void *)id );
    httpd_UrlCatch( url, HTTPD_MSG_PLAY,     RtspCallbackId, (void *)id );
    httpd_UrlCatch( url, HTTPD_MSG_PAUSE,    RtspCallbackId, (void *)id );
    httpd_UrlCatch( url, HTTPD_MSG_GETPARAMETER, RtspCallbackId, (void *)id );
    httpd_UrlCatch( url, HTTPD_MSG_TEARDOWN, RtspCallbackId, (void *)id );

    rtsp->track_id++;

    return id;
}


void RtspDelId( rtsp_stream_t *rtsp, rtsp_stream_id_t *id )
{
    httpd_UrlDelete( id->url );

    vlc_mutex_lock( &rtsp->lock );
    for( int i = 0; i < rtsp->sessionc; i++ )
    {
        rtsp_session_t *ses = rtsp->sessionv[i];

        for( int j = 0; j < ses->trackc; j++ )
        {
            if( ses->trackv[j].id == id )
            {
                rtsp_strack_t *tr = ses->trackv + j;
                RtspTrackClose( tr );
                REMOVE_ELEM( ses->trackv, ses->trackc, j );
            }
        }
    }

    vlc_mutex_unlock( &rtsp->lock );
    free( id );
}


/** rtsp must be locked */
static void RtspUpdateTimer( rtsp_stream_t *rtsp )
{
    if (rtsp->timeout <= 0)
        return;

    mtime_t timeout = 0;
    for (int i = 0; i < rtsp->sessionc; i++)
    {
        if (timeout == 0 || rtsp->sessionv[i]->last_seen < timeout)
            timeout = rtsp->sessionv[i]->last_seen;
    }
    if (timeout != 0)
        timeout += rtsp->timeout * CLOCK_FREQ;
    vlc_timer_schedule(rtsp->timer, true, timeout, 0);
}


static void RtspTimeOut( void *data )
{
    rtsp_stream_t *rtsp = data;

    vlc_mutex_lock(&rtsp->lock);
    mtime_t now = mdate();
    for (int i = rtsp->sessionc - 1; i >= 0; i--)
    {
        if (rtsp->sessionv[i]->last_seen + rtsp->timeout * CLOCK_FREQ < now)
        {
            if (rtsp->vod_media != NULL)
            {
                char psz_sesbuf[17];
                snprintf( psz_sesbuf, sizeof( psz_sesbuf ), "%"PRIx64,
                          rtsp->sessionv[i]->id );
                vod_stop(rtsp->vod_media, psz_sesbuf);
            }
            RtspClientDel(rtsp, rtsp->sessionv[i]);
        }
    }
    RtspUpdateTimer(rtsp);
    vlc_mutex_unlock(&rtsp->lock);
}


/** rtsp must be locked */
static
rtsp_session_t *RtspClientNew( rtsp_stream_t *rtsp )
{
    rtsp_session_t *s = malloc( sizeof( *s ) );
    if( s == NULL )
        return NULL;

    s->stream = rtsp;
    vlc_rand_bytes (&s->id, sizeof (s->id));
    s->trackc = 0;
    s->trackv = NULL;

    TAB_APPEND( rtsp->sessionc, rtsp->sessionv, s );

    return s;
}


/** rtsp must be locked */
static
rtsp_session_t *RtspClientGet( rtsp_stream_t *rtsp, const char *name )
{
    char *end;
    uint64_t id;
    int i;

    if( name == NULL )
        return NULL;

    errno = 0;
    id = strtoull( name, &end, 0x10 );
    if( errno || *end )
        return NULL;

    /* FIXME: use a hash/dictionary */
    for( i = 0; i < rtsp->sessionc; i++ )
    {
        if( rtsp->sessionv[i]->id == id )
            return rtsp->sessionv[i];
    }
    return NULL;
}


/** rtsp must be locked */
static
void RtspClientDel( rtsp_stream_t *rtsp, rtsp_session_t *session )
{
    int i;
    TAB_REMOVE( rtsp->sessionc, rtsp->sessionv, session );

    for( i = 0; i < session->trackc; i++ )
        RtspTrackClose( &session->trackv[i] );

    free( session->trackv );
    free( session );
}


/** rtsp must be locked */
static void RtspClientAlive( rtsp_session_t *session )
{
    if (session->stream->timeout <= 0)
        return;

    session->last_seen = mdate();
    RtspUpdateTimer(session->stream);
}

static int dup_socket(int oldfd)
{
    int newfd;
#if !defined(WIN32) || defined(UNDER_CE)
    newfd = vlc_dup(oldfd);
#else
    WSAPROTOCOL_INFO info;
    WSADuplicateSocket (oldfd, GetCurrentProcessId (), &info);
    newfd = WSASocket (info.iAddressFamily, info.iSocketType,
                       info.iProtocol, &info, 0, 0);
#endif
    return newfd;
}

/* Attach a starting VoD RTP id to its RTSP track, and let it
 * initialize with the parameters of the SETUP request */
int RtspTrackAttach( rtsp_stream_t *rtsp, const char *name,
                     rtsp_stream_id_t *id, sout_stream_id_t *sout_id,
                     uint32_t *ssrc, uint16_t *seq_init )
{
    int val = VLC_EGENERIC;
    rtsp_session_t *session;

    vlc_mutex_lock(&rtsp->lock);
    session = RtspClientGet(rtsp, name);

    if (session == NULL)
        goto out;

    rtsp_strack_t *tr = NULL;
    for (int i = 0; i < session->trackc; i++)
    {
        if (session->trackv[i].id == id)
        {
            tr = session->trackv + i;
            break;
        }
    }

    if (tr != NULL)
    {
        tr->sout_id = sout_id;
        tr->rtp_fd = dup_socket(tr->setup_fd);
    }
    else
    {
        /* The track was not SETUP. We still create one because we'll
         * need the sout_id if we set it up later. */
        rtsp_strack_t track = { .id = id, .sout_id = sout_id,
                                .setup_fd = -1, .rtp_fd = -1 };
        vlc_rand_bytes (&track.seq_init, sizeof (track.seq_init));
        vlc_rand_bytes (&track.ssrc, sizeof (track.ssrc));

        INSERT_ELEM(session->trackv, session->trackc, session->trackc, track);
    }

    *ssrc = ntohl(tr->ssrc);
    *seq_init = tr->seq_init;

    if (tr->rtp_fd != -1)
    {
        uint16_t seq;
        rtp_add_sink(tr->sout_id, tr->rtp_fd, false, &seq);
        /* To avoid race conditions, sout_id->i_seq_sent_next must
         * be set here and now. Make sure the caller did its job
         * properly when passing seq_init. */
        assert(tr->seq_init == seq);
    }

    val = VLC_SUCCESS;
out:
    vlc_mutex_unlock(&rtsp->lock);
    return val;
}


/* Remove references to the RTP id when it is stopped */
void RtspTrackDetach( rtsp_stream_t *rtsp, const char *name,
                      sout_stream_id_t *sout_id )
{
    rtsp_session_t *session;

    vlc_mutex_lock(&rtsp->lock);
    session = RtspClientGet(rtsp, name);<commit_msg>rtsp: fix crash with VoD when all tracks are not set up<commit_after>/*****************************************************************************
 * rtsp.c: RTSP support for RTP stream output module
 *****************************************************************************
 * Copyright (C) 2003-2004, 2010 the VideoLAN team
 * Copyright © 2007 <NAME>
 *
 * $Id$
 *
 * Authors: <NAME> <<EMAIL>>
 *          <NAME>
 *
 * 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
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

/*****************************************************************************
 * Preamble
 *****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include <vlc_common.h>
#include <vlc_sout.h>

#include <vlc_httpd.h>
#include <vlc_url.h>
#include <vlc_charset.h>
#include <vlc_fs.h>
#include <vlc_network.h>
#include <vlc_rand.h>
#include <assert.h>
#include <errno.h>
#include <stdlib.h>

#ifndef WIN32
# include <locale.h>
#endif
#ifdef HAVE_XLOCALE_H
# include <xlocale.h>
#endif

#include "rtp.h"

typedef struct rtsp_session_t rtsp_session_t;

struct rtsp_stream_t
{
    vlc_mutex_t     lock;
    vlc_object_t   *owner;
    vod_media_t    *vod_media;
    httpd_host_t   *host;
    httpd_url_t    *url;
    char           *psz_path;
    unsigned        track_id;
    unsigned        port;

    int             sessionc;
    rtsp_session_t **sessionv;

    int             timeout;
    vlc_timer_t     timer;
};


static int  RtspCallback( httpd_callback_sys_t *p_args,
                          httpd_client_t *cl, httpd_message_t *answer,
                          const httpd_message_t *query );
static int  RtspCallbackId( httpd_callback_sys_t *p_args,
                            httpd_client_t *cl, httpd_message_t *answer,
                            const httpd_message_t *query );
static void RtspClientDel( rtsp_stream_t *rtsp, rtsp_session_t *session );

static void RtspTimeOut( void *data );

rtsp_stream_t *RtspSetup( vlc_object_t *owner, vod_media_t *media,
                          const vlc_url_t *url )
{
    rtsp_stream_t *rtsp = malloc( sizeof( *rtsp ) );

    if( rtsp == NULL || ( url->i_port > 99999 ) )
    {
        free( rtsp );
        return NULL;
    }

    rtsp->owner = owner;
    rtsp->vod_media = media;
    rtsp->sessionc = 0;
    rtsp->sessionv = NULL;
    rtsp->host = NULL;
    rtsp->url = NULL;
    rtsp->psz_path = NULL;
    rtsp->track_id = 0;
    vlc_mutex_init( &rtsp->lock );

    rtsp->timeout = var_InheritInteger(owner, "rtsp-timeout");
    if (rtsp->timeout > 0)
    {
        if (vlc_timer_create(&rtsp->timer, RtspTimeOut, rtsp))
            goto error;
    }

    rtsp->port = (url->i_port > 0) ? url->i_port : 554;
    rtsp->psz_path = strdup( ( url->psz_path != NULL ) ? url->psz_path : "/" );
    if( rtsp->psz_path == NULL )
        goto error;

    msg_Dbg( owner, "RTSP stream: host %s port %d at %s",
             url->psz_host, rtsp->port, rtsp->psz_path );

    rtsp->host = httpd_HostNew( VLC_OBJECT(owner), url->psz_host,
                                rtsp->port );
    if( rtsp->host == NULL )
        goto error;

    rtsp->url = httpd_UrlNewUnique( rtsp->host, rtsp->psz_path,
                                    NULL, NULL, NULL );
    if( rtsp->url == NULL )
        goto error;

    httpd_UrlCatch( rtsp->url, HTTPD_MSG_DESCRIBE, RtspCallback, (void*)rtsp );
    httpd_UrlCatch( rtsp->url, HTTPD_MSG_SETUP,    RtspCallback, (void*)rtsp );
    httpd_UrlCatch( rtsp->url, HTTPD_MSG_PLAY,     RtspCallback, (void*)rtsp );
    httpd_UrlCatch( rtsp->url, HTTPD_MSG_PAUSE,    RtspCallback, (void*)rtsp );
    httpd_UrlCatch( rtsp->url, HTTPD_MSG_GETPARAMETER, RtspCallback,
                    (void*)rtsp );
    httpd_UrlCatch( rtsp->url, HTTPD_MSG_TEARDOWN, RtspCallback, (void*)rtsp );
    return rtsp;

error:
    RtspUnsetup( rtsp );
    return NULL;
}


void RtspUnsetup( rtsp_stream_t *rtsp )
{
    if( rtsp->url )
        httpd_UrlDelete( rtsp->url );

    if( rtsp->host )
        httpd_HostDelete( rtsp->host );

    while( rtsp->sessionc > 0 )
        RtspClientDel( rtsp, rtsp->sessionv[0] );

    if (rtsp->timeout > 0)
        vlc_timer_destroy(rtsp->timer);

    free( rtsp->psz_path );
    vlc_mutex_destroy( &rtsp->lock );

    free( rtsp );
}


struct rtsp_stream_id_t
{
    rtsp_stream_t    *stream;
    sout_stream_id_t *sout_id;
    httpd_url_t      *url;
    unsigned          track_id;
    uint32_t          ssrc;
    unsigned          clock_rate; /* needed to compute rtptime in RTP-Info */
    int               mcast_fd;
};


typedef struct rtsp_strack_t rtsp_strack_t;

/* For unicast streaming */
struct rtsp_session_t
{
    rtsp_stream_t *stream;
    uint64_t       id;
    mtime_t        last_seen; /* for timeouts */

    /* output (id-access) */
    int            trackc;
    rtsp_strack_t *trackv;
};


/* Unicast session track */
struct rtsp_strack_t
{
    rtsp_stream_id_t  *id;
    sout_stream_id_t  *sout_id;
    int          setup_fd;  /* socket created by the SETUP request */
    int          rtp_fd;    /* socket used by the RTP output, when playing */
    uint32_t     ssrc;
    uint16_t     seq_init;
};

static void RtspTrackClose( rtsp_strack_t *tr );

#define TRACK_PATH_SIZE (sizeof("/trackID=999") - 1)

char *RtspAppendTrackPath( rtsp_stream_id_t *id, const char *base )
{
    const char *sep = strlen( base ) > 0 && base[strlen( base ) - 1] == '/' ?
                      "" : "/";
    char *url;

    if( asprintf( &url, "%s%strackID=%u", base, sep, id->track_id ) == -1 )
        url = NULL;
    return url;
}


rtsp_stream_id_t *RtspAddId( rtsp_stream_t *rtsp, sout_stream_id_t *sid,
                             uint32_t ssrc, unsigned clock_rate,
                             int mcast_fd)
{
    if (rtsp->track_id > 999)
    {
        msg_Err(rtsp->owner, "RTSP: too many IDs!");
        return NULL;
    }

    char *urlbuf;
    rtsp_stream_id_t *id = malloc( sizeof( *id ) );
    httpd_url_t *url;

    if( id == NULL )
        return NULL;

    id->stream = rtsp;
    id->sout_id = sid;
    id->track_id = rtsp->track_id;
    id->ssrc = ssrc;
    id->clock_rate = clock_rate;
    id->mcast_fd = mcast_fd;

    urlbuf = RtspAppendTrackPath( id, rtsp->psz_path );
    if( urlbuf == NULL )
    {
        free( id );
        return NULL;
    }

    msg_Dbg( rtsp->owner, "RTSP: adding %s", urlbuf );
    url = id->url = httpd_UrlNewUnique( rtsp->host, urlbuf, NULL, NULL, NULL );
    free( urlbuf );

    if( url == NULL )
    {
        free( id );
        return NULL;
    }

    httpd_UrlCatch( url, HTTPD_MSG_DESCRIBE, RtspCallbackId, (void *)id );
    httpd_UrlCatch( url, HTTPD_MSG_SETUP,    RtspCallbackId, (void *)id );
    httpd_UrlCatch( url, HTTPD_MSG_PLAY,     RtspCallbackId, (void *)id );
    httpd_UrlCatch( url, HTTPD_MSG_PAUSE,    RtspCallbackId, (void *)id );
    httpd_UrlCatch( url, HTTPD_MSG_GETPARAMETER, RtspCallbackId, (void *)id );
    httpd_UrlCatch( url, HTTPD_MSG_TEARDOWN, RtspCallbackId, (void *)id );

    rtsp->track_id++;

    return id;
}


void RtspDelId( rtsp_stream_t *rtsp, rtsp_stream_id_t *id )
{
    httpd_UrlDelete( id->url );

    vlc_mutex_lock( &rtsp->lock );
    for( int i = 0; i < rtsp->sessionc; i++ )
    {
        rtsp_session_t *ses = rtsp->sessionv[i];

        for( int j = 0; j < ses->trackc; j++ )
        {
            if( ses->trackv[j].id == id )
            {
                rtsp_strack_t *tr = ses->trackv + j;
                RtspTrackClose( tr );
                REMOVE_ELEM( ses->trackv, ses->trackc, j );
            }
        }
    }

    vlc_mutex_unlock( &rtsp->lock );
    free( id );
}


/** rtsp must be locked */
static void RtspUpdateTimer( rtsp_stream_t *rtsp )
{
    if (rtsp->timeout <= 0)
        return;

    mtime_t timeout = 0;
    for (int i = 0; i < rtsp->sessionc; i++)
    {
        if (timeout == 0 || rtsp->sessionv[i]->last_seen < timeout)
            timeout = rtsp->sessionv[i]->last_seen;
    }
    if (timeout != 0)
        timeout += rtsp->timeout * CLOCK_FREQ;
    vlc_timer_schedule(rtsp->timer, true, timeout, 0);
}


static void RtspTimeOut( void *data )
{
    rtsp_stream_t *rtsp = data;

    vlc_mutex_lock(&rtsp->lock);
    mtime_t now = mdate();
    for (int i = rtsp->sessionc - 1; i >= 0; i--)
    {
        if (rtsp->sessionv[i]->last_seen + rtsp->timeout * CLOCK_FREQ < now)
        {
            if (rtsp->vod_media != NULL)
            {
                char psz_sesbuf[17];
                snprintf( psz_sesbuf, sizeof( psz_sesbuf ), "%"PRIx64,
                          rtsp->sessionv[i]->id );
                vod_stop(rtsp->vod_media, psz_sesbuf);
            }
            RtspClientDel(rtsp, rtsp->sessionv[i]);
        }
    }
    RtspUpdateTimer(rtsp);
    vlc_mutex_unlock(&rtsp->lock);
}


/** rtsp must be locked */
static
rtsp_session_t *RtspClientNew( rtsp_stream_t *rtsp )
{
    rtsp_session_t *s = malloc( sizeof( *s ) );
    if( s == NULL )
        return NULL;

    s->stream = rtsp;
    vlc_rand_bytes (&s->id, sizeof (s->id));
    s->trackc = 0;
    s->trackv = NULL;

    TAB_APPEND( rtsp->sessionc, rtsp->sessionv, s );

    return s;
}


/** rtsp must be locked */
static
rtsp_session_t *RtspClientGet( rtsp_stream_t *rtsp, const char *name )
{
    char *end;
    uint64_t id;
    int i;

    if( name == NULL )
        return NULL;

    errno = 0;
    id = strtoull( name, &end, 0x10 );
    if( errno || *end )
        return NULL;

    /* FIXME: use a hash/dictionary */
    for( i = 0; i < rtsp->sessionc; i++ )
    {
        if( rtsp->sessionv[i]->id == id )
            return rtsp->sessionv[i];
    }
    return NULL;
}


/** rtsp must be locked */
static
void RtspClientDel( rtsp_stream_t *rtsp, rtsp_session_t *session )
{
    int i;
    TAB_REMOVE( rtsp->sessionc, rtsp->sessionv, session );

    for( i = 0; i < session->trackc; i++ )
        RtspTrackClose( &session->trackv[i] );

    free( session->trackv );
    free( session );
}


/** rtsp must be locked */
static void RtspClientAlive( rtsp_session_t *session )
{
    if (session->stream->timeout <= 0)
        return;

    session->last_seen = mdate();
    RtspUpdateTimer(session->stream);
}

static int dup_socket(int oldfd)
{
    int newfd;
#if !defined(WIN32) || defined(UNDER_CE)
    newfd = vlc_dup(oldfd);
#else
    WSAPROTOCOL_INFO info;
    WSADuplicateSocket (oldfd, GetCurrentProcessId (), &info);
    newfd = WSASocket (info.iAddressFamily, info.iSocketType,
                       info.iProtocol, &info, 0, 0);
#endif
    return newfd;
}

/* Attach a starting VoD RTP id to its RTSP track, and let it
 * initialize with the parameters of the SETUP request */
int RtspTrackAttach( rtsp_stream_t *rtsp, const char *name,
                     rtsp_stream_id_t *id, sout_stream_id_t *sout_id,
                     uint32_t *ssrc, uint16_t *seq_init )
{
    int val = VLC_EGENERIC;
    rtsp_session_t *session;

    vlc_mutex_lock(&rtsp->lock);
    session = RtspClientGet(rtsp, name);

    if (session == NULL)
        goto out;

    rtsp_strack_t *tr = NULL;
    for (int i = 0; i < session->trackc; i++)
    {
        if (session->trackv[i].id == id)
        {
            tr = session->trackv + i;
            break;
        }
    }

    if (tr != NULL)
    {
        tr->sout_id = sout_id;
        tr->rtp_fd = dup_socket(tr->setup_fd);
    }
    else
    {
        /* The track was not SETUP. We still create one because we'll
         * need the sout_id if we set it up later. */
        rtsp_strack_t track = { .id = id, .sout_id = sout_id,
                                .setup_fd = -1, .rtp_fd = -1 };
        vlc_rand_bytes (&track.seq_init, sizeof (track.seq_init));
        vlc_rand_bytes (&track.ssrc, sizeof (track.ssrc));

        INSERT_ELEM(session->trackv, session->trackc, session->trackc, track);
        tr = session->trackv + session->trackc - 1;
    }

    *ssrc = ntohl(tr->ssrc);
    *seq_init = tr->seq_init;

    if (tr->rtp_fd != -1)
    {
        uint16_t seq;
        rtp_add_sink(tr->sout_id, tr->rtp_fd, false, &seq);
        /* To avoid race conditions, sout_id->i_seq_sent_next must
         * be set here and now. Make sure the caller did its job
         * properly when passing seq_init. */
        assert(tr->seq_init == seq);
    }

    val = VLC_SUCCESS;
out:
    vlc_mutex_unlock(&rtsp->lock);
    return val;
}


/* Remove references to the RTP id when it is stopped */
void RtspTrackDetach( rtsp_stream_t *rtsp, const char *name,
                      sout_stream_id_t *sout_id )
{
    rtsp_session_t *session;

    vlc_mutex_lock(&rtsp->lock);
    session = RtspClientGet(rtsp, name);
{'fraction_non_alphanumeric': 0.14840285606914694, 'fraction_numerical': 0.007779030439684329, 'mean_word_length': 2.392529321774605, 'pattern_counts': {'":': 0, '<': 59, '<?xml version=': 0, '>': 317, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1328084', 'n_tokens_mistral': 9760, 'n_tokens_neox': 9444, 'n_words': 2254}