libavformat/rtpdec_xiph.c
887af2aa
 /*
96070b8b
  * Xiph RTP Protocols
339f5f39
  * Copyright (c) 2009 Colin McQuillian
887af2aa
  * Copyright (c) 2010 Josh Allmann
  *
  * This file is part of FFmpeg.
  *
  * FFmpeg 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.
  *
  * FFmpeg 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
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with FFmpeg; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 /**
ba87f080
  * @file
96070b8b
  * @brief Xiph / RTP Code
339f5f39
  * @author Colin McQuillan <m.niloc@gmail.com>
887af2aa
  * @author Josh Allmann <joshua.allmann@gmail.com>
  */
 
7abd35a1
 #include "libavutil/attributes.h"
6b72615c
 #include "libavutil/avassert.h"
887af2aa
 #include "libavutil/avstring.h"
 #include "libavutil/base64.h"
 #include "libavcodec/bytestream.h"
 
199fb402
 #include "avio_internal.h"
a807c682
 #include "internal.h"
887af2aa
 #include "rtpdec.h"
965a3ddb
 #include "rtpdec_formats.h"
887af2aa
 
 /**
96070b8b
  * RTP/Xiph specific private data.
887af2aa
  */
 struct PayloadContext {
     unsigned ident;             ///< 24-bit stream configuration identifier
     uint32_t timestamp;
471fe57e
     AVIOContext* fragment;    ///< buffer for split payloads
504de2ec
     uint8_t *split_buf;
     int split_pos, split_buf_len, split_buf_size;
     int split_pkts;
887af2aa
 };
 
d594dbec
 static void xiph_close_context(PayloadContext * data)
887af2aa
 {
199fb402
     ffio_free_dyn_buf(&data->fragment);
ba8d2c90
     av_freep(&data->split_buf);
887af2aa
 }
 
c6f1dc8e
 
90c784cc
 static int xiph_handle_packet(AVFormatContext *ctx, PayloadContext *data,
                               AVStream *st, AVPacket *pkt, uint32_t *timestamp,
                               const uint8_t *buf, int len, uint16_t seq,
                               int flags)
887af2aa
 {
 
     int ident, fragmented, tdt, num_pkts, pkt_len;
 
504de2ec
     if (!buf) {
         if (!data->split_buf || data->split_pos + 2 > data->split_buf_len ||
             data->split_pkts <= 0) {
             av_log(ctx, AV_LOG_ERROR, "No more data to return\n");
             return AVERROR_INVALIDDATA;
         }
         pkt_len = AV_RB16(data->split_buf + data->split_pos);
         data->split_pos += 2;
a23379a0
         if (pkt_len > data->split_buf_len - data->split_pos) {
504de2ec
             av_log(ctx, AV_LOG_ERROR, "Not enough data to return\n");
             return AVERROR_INVALIDDATA;
         }
         if (av_new_packet(pkt, pkt_len)) {
             av_log(ctx, AV_LOG_ERROR, "Out of memory.\n");
             return AVERROR(ENOMEM);
         }
         pkt->stream_index = st->index;
         memcpy(pkt->data, data->split_buf + data->split_pos, pkt_len);
         data->split_pos += pkt_len;
         data->split_pkts--;
         return data->split_pkts > 0;
     }
 
aa516993
     if (len < 6 || len > INT_MAX/2) {
887af2aa
         av_log(ctx, AV_LOG_ERROR, "Invalid %d byte packet\n", len);
         return AVERROR_INVALIDDATA;
     }
 
96070b8b
     // read xiph rtp headers
887af2aa
     ident       = AV_RB24(buf);
     fragmented  = buf[3] >> 6;
     tdt         = (buf[3] >> 4) & 3;
737b3972
     num_pkts    = buf[3] & 0xf;
887af2aa
     pkt_len     = AV_RB16(buf + 4);
 
     if (pkt_len > len - 6) {
         av_log(ctx, AV_LOG_ERROR,
                "Invalid packet length %d in %d byte packet\n", pkt_len,
                len);
         return AVERROR_INVALIDDATA;
     }
 
     if (ident != data->ident) {
         av_log(ctx, AV_LOG_ERROR,
96070b8b
                "Unimplemented Xiph SDP configuration change detected\n");
887af2aa
         return AVERROR_PATCHWELCOME;
     }
 
     if (tdt) {
         av_log(ctx, AV_LOG_ERROR,
96070b8b
                "Unimplemented RTP Xiph packet settings (%d,%d,%d)\n",
887af2aa
                fragmented, tdt, num_pkts);
         return AVERROR_PATCHWELCOME;
     }
 
     buf += 6; // move past header bits
     len -= 6;
 
     if (fragmented == 0) {
504de2ec
         if (av_new_packet(pkt, pkt_len)) {
887af2aa
             av_log(ctx, AV_LOG_ERROR, "Out of memory.\n");
2874c81c
             return AVERROR(ENOMEM);
887af2aa
         }
         pkt->stream_index = st->index;
504de2ec
         memcpy(pkt->data, buf, pkt_len);
         buf += pkt_len;
         len -= pkt_len;
         num_pkts--;
 
         if (num_pkts > 0) {
             if (len > data->split_buf_size || !data->split_buf) {
                 av_freep(&data->split_buf);
                 data->split_buf_size = 2 * len;
                 data->split_buf = av_malloc(data->split_buf_size);
                 if (!data->split_buf) {
                     av_log(ctx, AV_LOG_ERROR, "Out of memory.\n");
                     av_free_packet(pkt);
                     return AVERROR(ENOMEM);
                 }
             }
             memcpy(data->split_buf, buf, len);
             data->split_buf_len = len;
             data->split_pos = 0;
             data->split_pkts = num_pkts;
             return 1;
887af2aa
         }
 
         return 0;
 
     } else if (fragmented == 1) {
96070b8b
         // start of xiph data fragment
887af2aa
         int res;
 
         // end packet has been lost somewhere, so drop buffered data
199fb402
         ffio_free_dyn_buf(&data->fragment);
887af2aa
 
b92c5452
         if((res = avio_open_dyn_buf(&data->fragment)) < 0)
887af2aa
             return res;
 
e9eb8d0b
         avio_write(data->fragment, buf, pkt_len);
887af2aa
         data->timestamp = *timestamp;
 
     } else {
6b72615c
         av_assert1(fragmented < 4);
887af2aa
         if (data->timestamp != *timestamp) {
             // skip if fragmented timestamp is incorrect;
             // a start packet has been lost somewhere
199fb402
             ffio_free_dyn_buf(&data->fragment);
887af2aa
             av_log(ctx, AV_LOG_ERROR, "RTP timestamps don't match!\n");
             return AVERROR_INVALIDDATA;
         }
adc03a34
         if (!data->fragment) {
             av_log(ctx, AV_LOG_WARNING,
                    "Received packet without a start fragment; dropping.\n");
             return AVERROR(EAGAIN);
         }
887af2aa
 
         // copy data to fragment buffer
e9eb8d0b
         avio_write(data->fragment, buf, pkt_len);
887af2aa
 
         if (fragmented == 3) {
96070b8b
             // end of xiph data packet
179a5c37
             int ret = ff_rtp_finalize_packet(pkt, &data->fragment, st->index);
             if (ret < 0) {
887af2aa
                 av_log(ctx, AV_LOG_ERROR,
                        "Error occurred when getting fragment buffer.");
179a5c37
                 return ret;
887af2aa
             }
 
             return 0;
         }
     }
 
    return AVERROR(EAGAIN);
 }
 
 /**
  * Length encoding described in RFC5215 section 3.1.1.
  */
 static int get_base128(const uint8_t ** buf, const uint8_t * buf_end)
 {
     int n = 0;
     for (; *buf < buf_end; ++*buf) {
         n <<= 7;
         n += **buf & 0x7f;
         if (!(**buf & 0x80)) {
             ++*buf;
             return n;
         }
     }
     return 0;
 }
 
 /**
  * Based off parse_packed_headers in Vorbis RTP
  */
0a7005be
 static int
887af2aa
 parse_packed_headers(const uint8_t * packed_headers,
                      const uint8_t * packed_headers_end,
96070b8b
                      AVCodecContext * codec, PayloadContext * xiph_data)
887af2aa
 {
 
     unsigned num_packed, num_headers, length, length1, length2, extradata_alloc;
     uint8_t *ptr;
 
     if (packed_headers_end - packed_headers < 9) {
         av_log(codec, AV_LOG_ERROR,
ced0d6c1
                "Invalid %"PTRDIFF_SPECIFIER" byte packed header.",
887af2aa
                packed_headers_end - packed_headers);
         return AVERROR_INVALIDDATA;
     }
 
     num_packed         = bytestream_get_be32(&packed_headers);
96070b8b
     xiph_data->ident   = bytestream_get_be24(&packed_headers);
887af2aa
     length             = bytestream_get_be16(&packed_headers);
     num_headers        = get_base128(&packed_headers, packed_headers_end);
     length1            = get_base128(&packed_headers, packed_headers_end);
     length2            = get_base128(&packed_headers, packed_headers_end);
 
     if (num_packed != 1 || num_headers > 3) {
         av_log(codec, AV_LOG_ERROR,
                "Unimplemented number of headers: %d packed headers, %d headers\n",
                num_packed, num_headers);
         return AVERROR_PATCHWELCOME;
     }
 
     if (packed_headers_end - packed_headers != length ||
         length1 > length || length2 > length - length1) {
         av_log(codec, AV_LOG_ERROR,
ced0d6c1
                "Bad packed header lengths (%d,%d,%"PTRDIFF_SPECIFIER",%d)\n", length1,
887af2aa
                length2, packed_headers_end - packed_headers, length);
         return AVERROR_INVALIDDATA;
     }
 
     /* allocate extra space:
      * -- length/255 +2 for xiphlacing
      * -- one for the '2' marker
059a9348
      * -- AV_INPUT_BUFFER_PADDING_SIZE required */
     extradata_alloc = length + length/255 + 3 + AV_INPUT_BUFFER_PADDING_SIZE;
887af2aa
 
a807c682
     if (ff_alloc_extradata(codec, extradata_alloc)) {
887af2aa
         av_log(codec, AV_LOG_ERROR, "Out of memory\n");
2874c81c
         return AVERROR(ENOMEM);
887af2aa
     }
a807c682
     ptr = codec->extradata;
887af2aa
     *ptr++ = 2;
     ptr += av_xiphlacing(ptr, length1);
     ptr += av_xiphlacing(ptr, length2);
     memcpy(ptr, packed_headers, length);
     ptr += length;
     codec->extradata_size = ptr - codec->extradata;
     // clear out remaining parts of the buffer
     memset(ptr, 0, extradata_alloc - codec->extradata_size);
 
     return 0;
 }
 
0307cc22
 static int xiph_parse_fmtp_pair(AVFormatContext *s,
                                 AVStream* stream,
96070b8b
                                 PayloadContext *xiph_data,
ec96a89c
                                 const char *attr, const char *value)
887af2aa
 {
af1308f0
     AVCodecContext *codec = stream->codec;
887af2aa
     int result = 0;
 
     if (!strcmp(attr, "sampling")) {
42c63263
         if (!strcmp(value, "YCbCr-4:2:0")) {
716d413c
             codec->pix_fmt = AV_PIX_FMT_YUV420P;
42c63263
         } else if (!strcmp(value, "YCbCr-4:4:2")) {
716d413c
             codec->pix_fmt = AV_PIX_FMT_YUV422P;
42c63263
         } else if (!strcmp(value, "YCbCr-4:4:4")) {
716d413c
             codec->pix_fmt = AV_PIX_FMT_YUV444P;
42c63263
         } else {
0307cc22
             av_log(s, AV_LOG_ERROR,
42c63263
                    "Unsupported pixel format %s\n", attr);
             return AVERROR_INVALIDDATA;
         }
887af2aa
     } else if (!strcmp(attr, "width")) {
         /* This is an integer between 1 and 1048561
          * and MUST be in multiples of 16. */
         codec->width = atoi(value);
         return 0;
     } else if (!strcmp(attr, "height")) {
         /* This is an integer between 1 and 1048561
          * and MUST be in multiples of 16. */
         codec->height = atoi(value);
         return 0;
     } else if (!strcmp(attr, "delivery-method")) {
         /* Possible values are: inline, in_band, out_band/specific_name. */
         return AVERROR_PATCHWELCOME;
     } else if (!strcmp(attr, "configuration-uri")) {
         /* NOTE: configuration-uri is supported only under 2 conditions:
          *--after the delivery-method tag
          * --with a delivery-method value of out_band */
         return AVERROR_PATCHWELCOME;
     } else if (!strcmp(attr, "configuration")) {
         /* NOTE: configuration is supported only AFTER the delivery-method tag
          * The configuration value is a base64 encoded packed header */
         uint8_t *decoded_packet = NULL;
         int packet_size;
         size_t decoded_alloc = strlen(value) / 4 * 3 + 4;
 
         if (decoded_alloc <= INT_MAX) {
             decoded_packet = av_malloc(decoded_alloc);
             if (decoded_packet) {
                 packet_size =
                     av_base64_decode(decoded_packet, value, decoded_alloc);
 
                 result = parse_packed_headers
                     (decoded_packet, decoded_packet + packet_size, codec,
96070b8b
                     xiph_data);
887af2aa
             } else {
0307cc22
                 av_log(s, AV_LOG_ERROR,
887af2aa
                        "Out of memory while decoding SDP configuration.\n");
2874c81c
                 result = AVERROR(ENOMEM);
887af2aa
             }
         } else {
0307cc22
             av_log(s, AV_LOG_ERROR, "Packet too large\n");
887af2aa
             result = AVERROR_INVALIDDATA;
         }
         av_free(decoded_packet);
     }
     return result;
 }
 
96070b8b
 static int xiph_parse_sdp_line(AVFormatContext *s, int st_index,
2ce7f4d4
                                PayloadContext *data, const char *line)
887af2aa
 {
     const char *p;
 
45600148
     if (st_index < 0)
         return 0;
 
887af2aa
     if (av_strstart(line, "fmtp:", &p)) {
0307cc22
         return ff_parse_fmtp(s, s->streams[st_index], data, p,
af1308f0
                              xiph_parse_fmtp_pair);
887af2aa
     }
 
     return 0;
 }
 
 RTPDynamicProtocolHandler ff_theora_dynamic_handler = {
     .enc_name         = "theora",
72415b2a
     .codec_type       = AVMEDIA_TYPE_VIDEO,
36ef5369
     .codec_id         = AV_CODEC_ID_THEORA,
5d8cae45
     .priv_data_size   = sizeof(PayloadContext),
96070b8b
     .parse_sdp_a_line = xiph_parse_sdp_line,
d594dbec
     .close            = xiph_close_context,
3cd5828f
     .parse_packet     = xiph_handle_packet,
887af2aa
 };
339f5f39
 
 RTPDynamicProtocolHandler ff_vorbis_dynamic_handler = {
     .enc_name         = "vorbis",
4bebf2cf
     .codec_type       = AVMEDIA_TYPE_AUDIO,
36ef5369
     .codec_id         = AV_CODEC_ID_VORBIS,
2b982e92
     .need_parsing     = AVSTREAM_PARSE_HEADERS,
5d8cae45
     .priv_data_size   = sizeof(PayloadContext),
339f5f39
     .parse_sdp_a_line = xiph_parse_sdp_line,
d594dbec
     .close            = xiph_close_context,
3cd5828f
     .parse_packet     = xiph_handle_packet,
339f5f39
 };