1/*
2 * RTP packetization for H.263 video
3 * Copyright (c) 2009 Luca Abeni
4 * Copyright (c) 2009 Martin Storsjo
5 *
6 * This file is part of FFmpeg.
7 *
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23#include "avformat.h"
24#include "rtpenc.h"
25
26static const uint8_t *find_resync_marker_reverse(const uint8_t *restrict start,
27                                                 const uint8_t *restrict end)
28{
29    const uint8_t *p = end - 1;
30    start += 1; /* Make sure we never return the original start. */
31    for (; p > start; p -= 2) {
32        if (!*p) {
33            if      (!p[ 1] && p[2]) return p;
34            else if (!p[-1] && p[1]) return p - 1;
35        }
36    }
37    return end;
38}
39
40/**
41 * Packetize H.263 frames into RTP packets according to RFC 4629
42 */
43void ff_rtp_send_h263(AVFormatContext *s1, const uint8_t *buf1, int size)
44{
45    RTPMuxContext *s = s1->priv_data;
46    int len, max_packet_size;
47    uint8_t *q;
48
49    max_packet_size = s->max_payload_size;
50
51    while (size > 0) {
52        q = s->buf;
53        if (size >= 2 && (buf1[0] == 0) && (buf1[1] == 0)) {
54            *q++ = 0x04;
55            buf1 += 2;
56            size -= 2;
57        } else {
58            *q++ = 0;
59        }
60        *q++ = 0;
61
62        len = FFMIN(max_packet_size - 2, size);
63
64        /* Look for a better place to split the frame into packets. */
65        if (len < size) {
66            const uint8_t *end = find_resync_marker_reverse(buf1, buf1 + len);
67            len = end - buf1;
68        }
69
70        memcpy(q, buf1, len);
71        q += len;
72
73        /* 90 KHz time stamp */
74        s->timestamp = s->cur_timestamp;
75        ff_rtp_send_data(s1, s->buf, q - s->buf, (len == size));
76
77        buf1 += len;
78        size -= len;
79    }
80}
81