Module: rtclite.std.ietf.rfc4566
# Copyright (c) 2007, Kundan Singh. All rights reserved. See LICENSE for details.
This file implements RFC4566 (SDP)
import socket, time, re # this module level property can be modified to '\n' to use only LF in generated SDP lineending = '\r\n' class attrs(object): '''A generic class that allows uniformly accessing the attribute and items, and returns None for invalid attribute instead of throwing an acception.''' def __init__(self, **kwargs): for n,v in kwargs.items(): self[n] = v # attribute access: use container if not found def __getattr__(self, name): return self.__getitem__(name) # container access: use key in __dict__ def __getitem__(self, name): return self.__dict__.get(name, None) def __setitem__(self, name, value): self.__dict__[name] = value def __contains__(self, name): return name in self.__dict__ #def __repr__(self): return repr(self.__dict__) def is_token(value): '''BNF includes token-char values !#$%&'*+-.0-9A-Z^_`a-z{|}~''' return value and not not re.match(r"[!#$%&'\*\+\-\.0-9A-Z^_`{\|}~a-z]+$", value)
From RFC4566 p.3
   When initiating multimedia teleconferences, voice-over-IP calls,
   streaming video, or other sessions, there is a requirement to convey
   media details, transport addresses, and other session description
   metadata to the participants.

   SDP provides a standard representation for such information,
   irrespective of how that information is transported.  SDP is purely a
   format for session description -- it does not incorporate a transport
   protocol, and it is intended to use different transport protocols as
   appropriate, including the Session Announcement Protocol [14],
   Session Initiation Protocol [15], Real Time Streaming Protocol [16],
   electronic mail using the MIME extensions, and the Hypertext
   Transport Protocol.

   SDP is intended to be general purpose so that it can be used in a
   wide range of network environments and applications.  However, it is
   not intended to support negotiation of session content or media
   encodings: this is viewed as outside the scope of session
   description.
class SDP(attrs): '''A SDP packet with dynamic properties. The header names can be accessed as attributes or items. Accessing an unavailable header gives None instead of exception. ''' # header names that can appear multiple times. _multiple = 'tramb' def __init__(self, value=None): if value: self._parse(value)
From RFC4566 p.11
5.2.  Origin ("o=")

      o=    
        

   The "o=" field gives the originator of the session (her username and
   the address of the user's host) plus a session identifier and version
   number:

    is the user's login on the originating host, or it is "-"
      if the originating host does not support the concept of user IDs.
      The  MUST NOT contain spaces.

    is a numeric string such that the tuple of ,
      , , , and  forms a
      globally unique identifier for the session.  The method of
       allocation is up to the creating tool, but it has been
      suggested that a Network Time Protocol (NTP) format timestamp be
      used to ensure uniqueness [13].

    is a version number for this session description.  Its
      usage is up to the creating tool, so long as  is
      increased when a modification is made to the session data.  Again,
      it is RECOMMENDED that an NTP format timestamp is used.

    is a text string giving the type of network.  Initially
      "IN" is defined to have the meaning "Internet", but other values
      MAY be registered in the future (see Section 8).

    is a text string giving the type of the address that
      follows.  Initially "IP4" and "IP6" are defined, but other values
      MAY be registered in the future (see Section 8).

    is the address of the machine from which the
      session was created.  For an address type of IP4, this is either
      the fully qualified domain name of the machine or the dotted-
      decimal representation of the IP version 4 address of the machine.
      For an address type of IP6, this is either the fully qualified
      domain name of the machine or the compressed textual
      representation of the IP version 6 address of the machine.  For
      both IP4 and IP6, the fully qualified domain name is the form that
      SHOULD be given unless this is unavailable, in which case the
      globally unique address MAY be substituted.  A local IP address
      MUST NOT be used in any context where the SDP description might
      leave the scope in which the address is meaningful (for example, a
      local address MUST NOT be included in an application-level
      referral that might leave the scope).

   In general, the "o=" field serves as a globally unique identifier for
   this version of this session description, and the subfields excepting
   the version taken together identify the session irrespective of any
   modifications.

   For privacy reasons, it is sometimes desirable to obfuscate the
   username and IP address of the session originator.  If this is a
   concern, an arbitrary  and private  MAY be
   chosen to populate the "o=" field, provided that these are selected
   in a manner that does not affect the global uniqueness of the field.
class originator(attrs): '''Represents a o= line with attributes username (str), sessionid (long), version (long), nettype (str), addrtype (str), address (str).''' def __init__(self, value=None): if value: self.username, self.sessionid, self.version, self.nettype, self.addrtype, self.address = value.split(' ') self.sessionid = int(self.sessionid) self.version = int(self.version) else: hostname = socket.gethostname() self.username, self.sessionid, self.version, self.nettype, self.addrtype, self.address = \ '-', int(time.time()), int(time.time()), 'IN', 'IP4', (hostname.find('.')>0 and hostname or socket.gethostbyname(hostname)) def __repr__(self): return ' '.join(map(lambda x: str(x), [self.username, self.sessionid, self.version, self.nettype, self.addrtype, self.address]))
From RFC4566 p.14
      c=  

   The "c=" field contains connection data.

   A session description MUST contain either at least one "c=" field in
   each media description or a single "c=" field at the session level.
   It MAY contain a single session-level "c=" field and additional "c="
   field(s) per media description, in which case the per-media values
   override the session-level settings for the respective media.

   The first sub-field ("") is the network type, which is a
   text string giving the type of network.  Initially, "IN" is defined
   to have the meaning "Internet", but other values MAY be registered in
   the future (see Section 8).

   The second sub-field ("") is the address type.  This allows
   SDP to be used for sessions that are not IP based.  This memo only
   defines IP4 and IP6, but other values MAY be registered in the future
   (see Section 8).

   The third sub-field ("") is the connection
   address.  OPTIONAL sub-fields MAY be added after the connection
   address depending on the value of the  field.

   When the  is IP4 and IP6, the connection address is defined
   as follows:

   o  If the session is multicast, the connection address will be an IP
      multicast group address.  If the session is not multicast, then
      the connection address contains the unicast IP address of the
      expected data source or data relay or data sink as determined by
      additional attribute fields.  It is not expected that unicast
      addresses will be given in a session description that is
      communicated by a multicast announcement, though this is not
      prohibited.

   o  Sessions using an IPv4 multicast connection address MUST also have
      a time to live (TTL) value present in addition to the multicast
      address.  The TTL and the address together define the scope with
      which multicast packets sent in this conference will be sent.  TTL
      values MUST be in the range 0-255.  Although the TTL MUST be
      specified, its use to scope multicast traffic is deprecated;
      applications SHOULD use an administratively scoped address
      instead.

   The TTL for the session is appended to the address using a slash as a
   separator.  An example is:

      c=IN IP4 224.2.36.42/127

   IPv6 multicast does not use TTL scoping, and hence the TTL value MUST
   NOT be present for IPv6 multicast.  It is expected that IPv6 scoped
   addresses will be used to limit the scope of conferences.

   Hierarchical or layered encoding schemes are data streams where the
   encoding from a single media source is split into a number of layers.
   The receiver can choose the desired quality (and hence bandwidth) by
   only subscribing to a subset of these layers.  Such layered encodings
   are normally transmitted in multiple multicast groups to allow
   multicast pruning.  This technique keeps unwanted traffic from sites
   only requiring certain levels of the hierarchy.  For applications
   requiring multiple multicast groups, we allow the following notation
   to be used for the connection address:

      [/]/

   If the number of addresses is not given, it is assumed to be one.
   Multicast addresses so assigned are contiguously allocated above the
   base address, so that, for example:

      c=IN IP4 224.2.1.1/127/3

   would state that addresses 224.2.1.1, 224.2.1.2, and 224.2.1.3 are to
   be used at a TTL of 127.  This is semantically identical to including
   multiple "c=" lines in a media description:

      c=IN IP4 224.2.1.1/127
      c=IN IP4 224.2.1.2/127
      c=IN IP4 224.2.1.3/127

   Similarly, an IPv6 example would be:

      c=IN IP6 FF15::101/3

   which is semantically equivalent to:

      c=IN IP6 FF15::101
      c=IN IP6 FF15::102
      c=IN IP6 FF15::103

   (remembering that the TTL field is not present in IPv6 multicast).

   Multiple addresses or "c=" lines MAY be specified on a per-media
   basis only if they provide multicast addresses for different layers
   in a hierarchical or layered encoding scheme.  They MUST NOT be
   specified for a session-level "c=" field.

   The slash notation for multiple addresses described above MUST NOT be
   used for IP unicast addresses.
class connection(attrs): '''Represents a c= line with attributes nettype (str), addrtype (str), address (str) and optionally ttl (int) and count (int).''' def __init__(self, value=None, **kwargs): if value: self.nettype, self.addrtype, rest = value.split(' ') rest = rest.split('/') if len(rest) == 1: self.address = rest[0] elif len(rest) == 2: self.address, self.ttl = rest[0], int(rest[1]) else: self.address, self.ttl, self.count = rest[0], int(rest[1]), int(rest[2]) elif 'address' in kwargs: self.address = kwargs.get('address') self.nettype = kwargs.get('nettype', 'IN') self.addrtype = kwargs.get('addrtype', 'IP4') if 'ttl' in kwargs: self.ttl = int(kwargs.get('ttl')) if 'count' in kwargs: self.count = int(kwargs.get('count')) def __repr__(self): return self.nettype + ' ' + self.addrtype + ' ' + self.address + ('/' + str(self.ttl) if self.ttl else '') + ('/' + str(self.count) if self.count else '')
From RFC4566 p.22
      m=    ...

   A session description may contain a number of media descriptions.
   Each media description starts with an "m=" field and is terminated by
   either the next "m=" field or by the end of the session description.
   A media field has several sub-fields:

    is the media type.  Currently defined media are "audio",
      "video", "text", "application", and "message", although this list
      may be extended in the future (see Section 8).

    is the transport port to which the media stream is sent.  The
      meaning of the transport port depends on the network being used as
      specified in the relevant "c=" field, and on the transport
      protocol defined in the  sub-field of the media field.
      Other ports used by the media application (such as the RTP Control
      Protocol (RTCP) port [19]) MAY be derived algorithmically from the
      base media port or MAY be specified in a separate attribute (for
      example, "a=rtcp:" as defined in [22]).

      If non-contiguous ports are used or if they don't follow the
      parity rule of even RTP ports and odd RTCP ports, the "a=rtcp:"
      attribute MUST be used.  Applications that are requested to send
      media to a  that is odd and where the "a=rtcp:" is present
      MUST NOT subtract 1 from the RTP port: that is, they MUST send the
      RTP to the port indicated in  and send the RTCP to the port
      indicated in the "a=rtcp" attribute.

      For applications where hierarchically encoded streams are being
      sent to a unicast address, it may be necessary to specify multiple
      transport ports.  This is done using a similar notation to that
      used for IP multicast addresses in the "c=" field:
         m= /   ...

      In such a case, the ports used depend on the transport protocol.
      For RTP, the default is that only the even-numbered ports are used
      for data with the corresponding one-higher odd ports used for the
      RTCP belonging to the RTP session, and the 
      denoting the number of RTP sessions.  For example:

         m=video 49170/2 RTP/AVP 31

      would specify that ports 49170 and 49171 form one RTP/RTCP pair
      and 49172 and 49173 form the second RTP/RTCP pair.  RTP/AVP is the
      transport protocol and 31 is the format (see below).  If non-
      contiguous ports are required, they must be signalled using a
      separate attribute (for example, "a=rtcp:" as defined in [22]).

      If multiple addresses are specified in the "c=" field and multiple
      ports are specified in the "m=" field, a one-to-one mapping from
      port to the corresponding address is implied.  For example:

         c=IN IP4 224.2.1.1/127/2
         m=video 49170/2 RTP/AVP 31

      would imply that address 224.2.1.1 is used with ports 49170 and
      49171, and address 224.2.1.2 is used with ports 49172 and 49173.

      The semantics of multiple "m=" lines using the same transport
      address are undefined.  This implies that, unlike limited past
      practice, there is no implicit grouping defined by such means and
      an explicit grouping framework (for example, [18]) should instead
      be used to express the intended semantics.

    is the transport protocol.  The meaning of the transport
      protocol is dependent on the address type field in the relevant
      "c=" field.  Thus a "c=" field of IP4 indicates that the transport
      protocol runs over IP4.  The following transport protocols are
      defined, but may be extended through registration of new protocols
      with IANA (see Section 8):

      *  udp: denotes an unspecified protocol running over UDP.

      *  RTP/AVP: denotes RTP [19] used under the RTP Profile for Audio
         and Video Conferences with Minimal Control [20] running over
         UDP.

      *  RTP/SAVP: denotes the Secure Real-time Transport Protocol [23]
         running over UDP.

      The main reason to specify the transport protocol in addition to
      the media format is that the same standard media formats may be
      carried over different transport protocols even when the network
      protocol is the same -- a historical example is vat Pulse Code
      Modulation (PCM) audio and RTP PCM audio; another might be TCP/RTP
      PCM audio.  In addition, relays and monitoring tools that are
      transport-protocol-specific but format-independent are possible.

    is a media format description.  The fourth and any subsequent
      sub-fields describe the format of the media.  The interpretation
      of the media format depends on the value of the  sub-field.

      If the  sub-field is "RTP/AVP" or "RTP/SAVP" the 
      sub-fields contain RTP payload type numbers.  When a list of
      payload type numbers is given, this implies that all of these
      payload formats MAY be used in the session, but the first of these
      formats SHOULD be used as the default format for the session.  For
      dynamic payload type assignments the "a=rtpmap:" attribute (see
      Section 6) SHOULD be used to map from an RTP payload type number
      to a media encoding name that identifies the payload format.  The
      "a=fmtp:"  attribute MAY be used to specify format parameters (see
      Section 6).

      If the  sub-field is "udp" the  sub-fields MUST
      reference a media type describing the format under the "audio",
      "video", "text", "application", or "message" top-level media
      types.  The media type registration SHOULD define the packet
      format for use with UDP transport.

      For media using other transport protocols, the  field is
      protocol specific.  Rules for interpretation of the  sub-
      field MUST be defined when registering new protocols (see Section
      8.2.2).
class media(attrs): '''Represents a m= line and all subsequent lines until next m= or end. It has attributes such as media (str), port (int), proto (str), fmt (list).''' def __init__(self, value=None, **kwargs): if value: self.media, self.port, self.proto, rest = value.split(' ', 3) self.port = int(self.port) self.fmt = [] for f in rest.split(' '): a = attrs() try: a.pt = int(f) # if payload type is numeric except: a.pt = f self.fmt.append(a) elif 'media' in kwargs: self.media = kwargs.get('media') self.port = int(kwargs.get('port', 0)) self.proto = kwargs.get('proto', 'RTP/AVP') self.fmt = kwargs.get('fmt', []) def __repr__(self): result = self.media + ' ' + str(self.port) + ' ' + self.proto + ' ' + ' '.join(map(lambda x: str(x.pt), self.fmt)) for k in filter(lambda x: x in self, 'icbka'): # order is important if k not in SDP._multiple: # single header result += '\r\n' + k + '=' + str(self[k]) else: for v in self[k]: result += '\r\n' + k + '=' + str(v) for f in self.fmt: if f.name: result += '\r\n' + 'a=rtpmap:' + str(f.pt) + ' ' + f.name + '/' + str(f.rate) + (f.params and ('/'+f.params) or '') return result def dup(self): # use this method instead of SDP.media(str(m)) to duplicate m. Otherwise, fmt will be incomplete result = SDP.media(media=self.media, port=self.port, proto=self.proto, fmt=map(lambda f: attrs(pt=f.pt, name=f.name, rate=f.rate, params=f.params), self.fmt)) for k in filter(lambda x: x in self, 'icbka'): result[k] = self[k][:] if isinstance(self[k], list) else self[k] return result
From RFC4566 p.8
   An SDP session description consists of a number of lines of text of
   the form:

      =

   where  MUST be exactly one case-significant character and
    is structured text whose format depends on .  In
   general,  is either a number of fields delimited by a single
   space character or a free format string, and is case-significant
   unless a specific field defines otherwise.  Whitespace MUST NOT be
   used on either side of the "=" sign.

   An SDP session description consists of a session-level section
   followed by zero or more media-level sections.  The session-level
   part starts with a "v=" line and continues to the first media-level
   section.  Each media-level section starts with an "m=" line and
   continues to the next media-level section or end of the whole session
   description.  In general, session-level values are the default for
   all media unless overridden by an equivalent media-level value.

   Some lines in each description are REQUIRED and some are OPTIONAL,
   but all MUST appear in exactly the order given here (the fixed order
   greatly enhances error detection and allows for a simple parser).
   OPTIONAL items are marked with a "*".








      Session description
         v=  (protocol version)
         o=  (originator and session identifier)
         s=  (session name)
         i=* (session information)
         u=* (URI of description)
         e=* (email address)
         p=* (phone number)
         c=* (connection information -- not required if included in
              all media)
         b=* (zero or more bandwidth information lines)
         One or more time descriptions ("t=" and "r=" lines; see below)
         z=* (time zone adjustments)
         k=* (encryption key)
         a=* (zero or more session attribute lines)
         Zero or more media descriptions

      Time description
         t=  (time the session is active)
         r=* (zero or more repeat times)

      Media description, if present
         m=  (media name and transport address)
         i=* (media title)
         c=* (connection information -- optional if included at
              session level)
         b=* (zero or more bandwidth information lines)
         k=* (encryption key)
         a=* (zero or more media attribute lines)

   The set of type letters is deliberately small and not intended to be
   extensible -- an SDP parser MUST completely ignore any session
   description that contains a type letter that it does not understand.
   The attribute mechanism ("a=" described below) is the primary means
   for extending SDP and tailoring it to particular applications or
   media.  Some attributes (the ones listed in Section 6 of this memo)
   have a defined meaning, but others may be added on an application-,
   media-, or session-specific basis.  An SDP parser MUST ignore any
   attribute it doesn't understand.

   An SDP session description may contain URIs that reference external
   content in the "u=", "k=", and "a=" lines.  These URIs may be
   dereferenced in some cases, making the session description non-self-
   contained.




   The connection ("c=") and attribute ("a=") information in the
   session-level section applies to all the media of that session unless
   overridden by connection information or an attribute of the same name
   in the media description.  For instance, in the example below, each
   media behaves as if it were given a "recvonly" attribute.
def _parse(self, text): g = True # whether we are in global line or per media line? for line in text.replace('\r\n', '\n').split('\n'): k, sep, v = line.partition('=') if k == 'o': v = SDP.originator(v) elif k == 'c': v = SDP.connection(v) elif k == 'm': v = SDP.media(v) if k == 'm': # new m= line if not self['m']: self['m'] = [] self['m'].append(v) obj = self['m'][-1] elif self['m']: # not in global obj = self['m'][-1]
From RFC4566 p.25
      a=rtpmap: / [/]

         This attribute maps from an RTP payload type number (as used in
         an "m=" line) to an encoding name denoting the payload format
         to be used.  It also provides information on the clock rate and
         encoding parameters.  It is a media-level attribute that is not
         dependent on charset.
         Although an RTP profile may make static assignments of payload
         type numbers to payload formats, it is more common for that
         assignment to be done dynamically using "a=rtpmap:" attributes.
         As an example of a static payload type, consider u-law PCM
         coded single-channel audio sampled at 8 kHz.  This is
         completely defined in the RTP Audio/Video profile as payload
         type 0, so there is no need for an "a=rtpmap:" attribute, and
         the media for such a stream sent to UDP port 49232 can be
         specified as:

            m=audio 49232 RTP/AVP 0

         An example of a dynamic payload type is 16-bit linear encoded
         stereo audio sampled at 16 kHz.  If we wish to use the dynamic
         RTP/AVP payload type 98 for this stream, additional information
         is required to decode it:

            m=audio 49232 RTP/AVP 98
            a=rtpmap:98 L16/16000/2

         Up to one rtpmap attribute can be defined for each media format
         specified.  Thus, we might have the following:

            m=audio 49230 RTP/AVP 96 97 98
            a=rtpmap:96 L8/8000
            a=rtpmap:97 L16/8000
            a=rtpmap:98 L16/11025/2

         RTP profiles that specify the use of dynamic payload types MUST
         define the set of valid encoding names and/or a means to
         register encoding names if that profile is to be used with SDP.
         The "RTP/AVP" and "RTP/SAVP" profiles use media subtypes for
         encoding names, under the top-level media type denoted in the
         "m=" line.  In the example above, the media types are
         "audio/l8" and "audio/l16".

         For audio streams,  indicates the number
         of audio channels.  This parameter is OPTIONAL and may be
         omitted if the number of channels is one, provided that no
         additional parameters are needed.

         For video streams, no encoding parameters are currently
         specified.

         Additional encoding parameters MAY be defined in the future,
         but codec-specific parameters SHOULD NOT be added.  Parameters
         added to an "a=rtpmap:" attribute SHOULD only be those required
         for a session directory to make the choice of appropriate media
         to participate in a session.  Codec-specific parameters should
         be added in other attributes (for example, "a=fmtp:").

         Note: RTP audio formats typically do not include information
         about the number of samples per packet.  If a non-default (as
         defined in the RTP Audio/Video Profile) packetisation is
         required, the "ptime" attribute is used as given above.
if k == 'a' and v.startswith('rtpmap:'): pt, rest = v[7:].split(' ', 1) name, sep, rest = rest.partition('/') rate, sep, params = rest.partition('/') for f in filter(lambda x: str(x.pt) == str(pt), obj.fmt): f.name = name; f.rate = int(rate); f.params = params or None else: obj[k] = (k in SDP._multiple and ((k in obj) and (obj[k]+[v]) or [v])) or v else: # global obj = self obj[k] = ((k in SDP._multiple) and ((k in obj) and (obj[k]+[v]) or [v])) or v def __repr__(self): global lineending result = '' for k in filter(lambda x: x in self, 'vosiuepcbtam'): # order is important if k not in SDP._multiple: # single header result += k + '=' + str(self[k]) + '\r\n' else: for v in self[k]: result += k + '=' + str(v) + '\r\n' if lineending != '\r\n': if lineending != '\n': raise RuntimeError('lineending must be either "\r\n" or "\n"'); result = re.sub(r'\r\n', lineending, result) return result #--------------------------- Testing --------------------------------------
From RFC4566 p.10
   An example SDP description is:

      v=0
      o=jdoe 2890844526 2890842807 IN IP4 10.47.16.5
      s=SDP Seminar
      i=A Seminar on the session description protocol
      u=http://www.example.com/seminars/sdp.pdf
      e=j.doe@example.com (Jane Doe)
      c=IN IP4 224.2.17.12/127
      t=2873397496 2873404696
      a=recvonly
      m=audio 49170 RTP/AVP 0
      m=video 51372 RTP/AVP 99
      a=rtpmap:99 h263-1998/90000
def testSDP(): s = '''v=0\r o=jdoe 2890844526 2890842807 IN IP4 10.47.16.5\r s=SDP Seminar\r i=A Seminar on the session description protocol\r u=http://www.example.com/seminars/sdp.pdf\r e=j.doe@example.com (Jane Doe)\r c=IN IP4 224.2.17.12/127\r t=2873397496 2873404696\r a=recvonly\r m=audio 49170 RTP/AVP 0\r m=video 51372 RTP/AVP 99\r a=rtpmap:99 h263-1998/90000\r ''' sdp = SDP(s) assert str(sdp) == s if __name__ == '__main__': import doctest doctest.testmod() testSDP()