summaryrefslogtreecommitdiffstats
path: root/src/modules/rtp/rtp-native.c
blob: 01e668cc65cfaa6d5f0c9bbce360b2083b57bf40 (plain)
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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
131
132
133
134
135
136
137
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
/***
  This file is part of PulseAudio.

  Copyright 2006 Lennart Poettering

  PulseAudio 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.

  PulseAudio 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 Lesser General Public License
  along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
***/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/ioctl.h>

#ifdef HAVE_SYS_FILIO_H
#include <sys/filio.h>
#endif

#ifdef HAVE_SYS_UIO_H
#include <sys/uio.h>
#endif

#include <pulsecore/core-error.h>
#include <pulsecore/log.h>
#include <pulsecore/macro.h>
#include <pulsecore/core-util.h>
#include <pulsecore/arpa-inet.h>
#include <pulsecore/poll.h>

#include "rtp.h"

typedef struct pa_rtp_context {
    int fd;
    uint16_t sequence;
    uint32_t timestamp;
    uint32_t ssrc;
    uint8_t payload;
    size_t frame_size;
    size_t mtu;

    uint8_t *recv_buf;
    size_t recv_buf_size;
    pa_memchunk memchunk;
} pa_rtp_context;

pa_rtp_context* pa_rtp_context_new_send(int fd, uint8_t payload, size_t mtu, const pa_sample_spec *ss) {
    pa_rtp_context *c;

    pa_assert(fd >= 0);

    pa_log_info("Initialising native RTP backend for send");

    c = pa_xnew0(pa_rtp_context, 1);

    c->fd = fd;
    c->sequence = (uint16_t) (rand()*rand());
    c->timestamp = 0;
    c->ssrc = (uint32_t) (rand()*rand());
    c->payload = (uint8_t) (payload & 127U);
    c->frame_size = pa_frame_size(ss);
    c->mtu = mtu;

    c->recv_buf = NULL;
    c->recv_buf_size = 0;
    pa_memchunk_reset(&c->memchunk);

    return c;
}

#define MAX_IOVECS 16

int pa_rtp_send(pa_rtp_context *c, pa_memblockq *q) {
    struct iovec iov[MAX_IOVECS];
    pa_memblock* mb[MAX_IOVECS];
    int iov_idx = 1;
    size_t n = 0;

    pa_assert(c);
    pa_assert(q);

    if (pa_memblockq_get_length(q) < c->mtu)
        return 0;

    for (;;) {
        int r;
        pa_memchunk chunk;

        pa_memchunk_reset(&chunk);

        if ((r = pa_memblockq_peek(q, &chunk)) >= 0) {

            size_t k = n + chunk.length > c->mtu ? c->mtu - n : chunk.length;

            pa_assert(chunk.memblock);

            iov[iov_idx].iov_base = pa_memblock_acquire_chunk(&chunk);
            iov[iov_idx].iov_len = k;
            mb[iov_idx] = chunk.memblock;
            iov_idx ++;

            n += k;
            pa_memblockq_drop(q, k);
        }

        pa_assert(n % c->frame_size == 0);

        if (r < 0 || n >= c->mtu || iov_idx >= MAX_IOVECS) {
            uint32_t header[3];
            struct msghdr m;
            ssize_t k;
            int i;

            if (n > 0) {
                header[0] = htonl(((uint32_t) 2 << 30) | ((uint32_t) c->payload << 16) | ((uint32_t) c->sequence));
                header[1] = htonl(c->timestamp);
                header[2] = htonl(c->ssrc);

                iov[0].iov_base = (void*)header;
                iov[0].iov_len = sizeof(header);

                m.msg_name = NULL;
                m.msg_namelen = 0;
                m.msg_iov = iov;
                m.msg_iovlen = (size_t) iov_idx;
                m.msg_control = NULL;
                m.msg_controllen = 0;
                m.msg_flags = 0;

                k = sendmsg(c->fd, &m, MSG_DONTWAIT);

                for (i = 1; i < iov_idx; i++) {
                    pa_memblock_release(mb[i]);
                    pa_memblock_unref(mb[i]);
                }

                c->sequence++;
            } else
                k = 0;

            c->timestamp += (unsigned) (n/c->frame_size);

            if (k < 0) {
                if (errno != EAGAIN && errno != EINTR) /* If the queue is full, just ignore it */
                    pa_log("sendmsg() failed: %s", pa_cstrerror(errno));
                return -1;
            }

            if (r < 0 || pa_memblockq_get_length(q) < c->mtu)
                break;

            n = 0;
            iov_idx = 1;
        }
    }

    return 0;
}

pa_rtp_context* pa_rtp_context_new_recv(int fd, uint8_t payload, const pa_sample_spec *ss) {
    pa_rtp_context *c;

    pa_log_info("Initialising native RTP backend for receive");

    c = pa_xnew0(pa_rtp_context, 1);

    c->fd = fd;
    c->payload = payload;
    c->frame_size = pa_frame_size(ss);

    c->recv_buf_size = 2000;
    c->recv_buf = pa_xmalloc(c->recv_buf_size);
    pa_memchunk_reset(&c->memchunk);

    return c;
}

int pa_rtp_recv(pa_rtp_context *c, pa_memchunk *chunk, pa_mempool *pool, uint32_t *rtp_tstamp, struct timeval *tstamp) {
    int size;
    size_t audio_length;
    size_t metadata_length;
    struct msghdr m;
    struct cmsghdr *cm;
    struct iovec iov;
    uint32_t header;
    uint32_t ssrc;
    uint8_t payload;
    unsigned cc;
    ssize_t r;
    uint8_t aux[1024];
    bool found_tstamp = false;

    pa_assert(c);
    pa_assert(chunk);

    pa_memchunk_reset(chunk);

    if (ioctl(c->fd, FIONREAD, &size) < 0) {
        pa_log_warn("FIONREAD failed: %s", pa_cstrerror(errno));
        goto fail;
    }

    if (size <= 0) {
        /* size can be 0 due to any of the following reasons:
         *
         * 1. Somebody sent us a perfectly valid zero-length UDP packet.
         * 2. Somebody sent us a UDP packet with a bad CRC.
         *
         * It is unknown whether size can actually be less than zero.
         *
         * In the first case, the packet has to be read out, otherwise the
         * kernel will tell us again and again about it, thus preventing
         * reception of any further packets. So let's just read it out
         * now and discard it later, when comparing the number of bytes
         * received (0) with the number of bytes wanted (1, see below).
         *
         * In the second case, recvmsg() will fail, thus allowing us to
         * return the error.
         *
         * Just to avoid passing zero-sized memchunks and NULL pointers to
         * recvmsg(), let's force allocation of at least one byte by setting
         * size to 1.
         */
        size = 1;
    }

    if (c->recv_buf_size < (size_t) size) {
        do
            c->recv_buf_size *= 2;
        while (c->recv_buf_size < (size_t) size);

        c->recv_buf = pa_xrealloc(c->recv_buf, c->recv_buf_size);
    }

    pa_assert(c->recv_buf_size >= (size_t) size);

    iov.iov_base = c->recv_buf;
    iov.iov_len = (size_t) size;

    m.msg_name = NULL;
    m.msg_namelen = 0;
    m.msg_iov = &iov;
    m.msg_iovlen = 1;
    m.msg_control = aux;
    m.msg_controllen = sizeof(aux);
    m.msg_flags = 0;

    r = recvmsg(c->fd, &m, 0);

    if (r != size) {
        if (r < 0 && errno != EAGAIN && errno != EINTR)
            pa_log_warn("recvmsg() failed: %s", r < 0 ? pa_cstrerror(errno) : "size mismatch");

        goto fail;
    }

    if (size < 12) {
        pa_log_warn("RTP packet too short.");
        goto fail;
    }

    memcpy(&header, iov.iov_base, sizeof(uint32_t));
    memcpy(rtp_tstamp, (uint8_t*) iov.iov_base + 4, sizeof(uint32_t));
    memcpy(&ssrc, (uint8_t*) iov.iov_base + 8, sizeof(uint32_t));

    header = ntohl(header);
    *rtp_tstamp = ntohl(*rtp_tstamp);
    ssrc = ntohl(c->ssrc);

    if ((header >> 30) != 2) {
        pa_log_warn("Unsupported RTP version.");
        goto fail;
    }

    if ((header >> 29) & 1) {
        pa_log_warn("RTP padding not supported.");
        goto fail;
    }

    if ((header >> 28) & 1) {
        pa_log_warn("RTP header extensions not supported.");
        goto fail;
    }

    if (ssrc != c->ssrc) {
        pa_log_debug("Got unexpected SSRC");
        goto fail;
    }

    cc = (header >> 24) & 0xF;
    payload = (uint8_t) ((header >> 16) & 127U);
    c->sequence = (uint16_t) (header & 0xFFFFU);

    metadata_length = 12 + cc * 4;

    if (payload != c->payload) {
        pa_log_debug("Got unexpected payload: %u", payload);
        goto fail;
    }

    if (metadata_length > (unsigned) size) {
        pa_log_warn("RTP packet too short. (CSRC)");
        goto fail;
    }

    audio_length = size - metadata_length;

    if (audio_length % c->frame_size != 0) {
        pa_log_warn("Bad RTP packet size.");
        goto fail;
    }

    if (c->memchunk.length < (unsigned) audio_length) {
        size_t l;

        if (c->memchunk.memblock)
            pa_memblock_unref(c->memchunk.memblock);

        l = PA_MAX((size_t) audio_length, pa_mempool_block_size_max(pool));

        c->memchunk.memblock = pa_memblock_new(pool, l);
        c->memchunk.index = 0;
        c->memchunk.length = pa_memblock_get_length(c->memchunk.memblock);
    }

    memcpy(pa_memblock_acquire_chunk(&c->memchunk), c->recv_buf + metadata_length, audio_length);
    pa_memblock_release(c->memchunk.memblock);

    chunk->memblock = pa_memblock_ref(c->memchunk.memblock);
    chunk->index = c->memchunk.index;
    chunk->length = audio_length;

    c->memchunk.index += audio_length;
    c->memchunk.length -= audio_length;

    if (c->memchunk.length <= 0) {
        pa_memblock_unref(c->memchunk.memblock);
        pa_memchunk_reset(&c->memchunk);
    }

    for (cm = CMSG_FIRSTHDR(&m); cm; cm = CMSG_NXTHDR(&m, cm))
        if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SCM_TIMESTAMP) {
            memcpy(tstamp, CMSG_DATA(cm), sizeof(struct timeval));
            found_tstamp = true;
            break;
        }

    if (!found_tstamp) {
        pa_log_warn("Couldn't find SCM_TIMESTAMP data in auxiliary recvmsg() data!");
        pa_zero(*tstamp);
    }

    return 0;

fail:
    if (chunk->memblock)
        pa_memblock_unref(chunk->memblock);

    return -1;
}

void pa_rtp_context_free(pa_rtp_context *c) {
    pa_assert(c);

    pa_assert_se(pa_close(c->fd) == 0);

    if (c->memchunk.memblock)
        pa_memblock_unref(c->memchunk.memblock);

    pa_xfree(c->recv_buf);
    pa_xfree(c);
}

size_t pa_rtp_context_get_frame_size(pa_rtp_context *c) {
    return c->frame_size;
}

pa_rtpoll_item* pa_rtp_context_get_rtpoll_item(pa_rtp_context *c, pa_rtpoll *rtpoll) {
    pa_rtpoll_item *item;
    struct pollfd *p;

    item = pa_rtpoll_item_new(rtpoll, PA_RTPOLL_LATE, 1);

    p = pa_rtpoll_item_get_pollfd(item, NULL);
    p->fd = c->fd;
    p->events = POLLIN;
    p->revents = 0;

    return item;
}