1# This Source Code Form is subject to the terms of the Mozilla Public
2# License, v. 2.0. If a copy of the MPL was not distributed with this
3# file, You can obtain one at https://mozilla.org/MPL/2.0/.
4#
5# This file incorporates work covered by the following copyright and
6# permission notice:
7#
8# Copyright (c) Jeremy Lainé.
9# All rights reserved.
10#
11# Redistribution and use in source and binary forms, with or without
12# modification, are permitted provided that the following conditions are met:
13#
14# * Redistributions of source code must retain the above copyright notice,
15# this list of conditions and the following disclaimer.
16# * Redistributions in binary form must reproduce the above copyright notice,
17# this list of conditions and the following disclaimer in the documentation
18# and/or other materials provided with the distribution.
19# * Neither the name of aiortc nor the names of its contributors may
20# be used to endorse or promote products derived from this software without
21# specific prior written permission.
22#
23# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
24# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
25# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
26# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
27# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
29# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
30# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
32# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33
34import fractions
35import uuid
36from abc import ABCMeta, abstractmethod
37from typing import Any
38
39from pyee.asyncio import AsyncIOEventEmitter
40
41VIDEO_CLOCK_RATE = 90000
42VIDEO_TIME_BASE = fractions.Fraction(1, VIDEO_CLOCK_RATE)
43
44
45def convert_timebase(
46 pts: int, from_base: fractions.Fraction, to_base: fractions.Fraction
47) -> int:
48 if from_base != to_base:
49 pts = int(pts * from_base / to_base)
50 return pts
51
52
53class MediaStreamError(Exception):
54 pass
55
56
57class MediaStreamTrack(AsyncIOEventEmitter, metaclass=ABCMeta):
58 """
59 A single media track within a stream.
60 """
61
62 kind = "unknown"
63
64 def __init__(self) -> None:
65 super().__init__()
66 self.__ended = False
67 self._id = str(uuid.uuid4())
68
69 @property
70 def id(self) -> str:
71 """
72 An automatically generated globally unique ID.
73 """
74 return self._id
75
76 @property
77 def readyState(self) -> str:
78 return "ended" if self.__ended else "live"
79
80 @abstractmethod
81 async def recv(self) -> Any:
82 """Receive the next media sample. Selkies' tracks serve a pre-encoded
83 `EncodedPacket` from pixelflux/pcmflux."""
84
85 def stop(self) -> None:
86 if not self.__ended:
87 self.__ended = True
88 self.emit("ended")
89
90 # no more events will be emitted, so remove all event listeners
91 # to facilitate garbage collection.
92 self.remove_all_listeners()
93
94
95class AudioStreamTrack(MediaStreamTrack):
96 """Base audio track. Selkies' `AudioMedia` overrides `recv` to serve
97 pre-encoded packets from pcmflux; the base itself produces nothing."""
98
99 kind = "audio"
100
101 async def recv(self) -> Any:
102 raise NotImplementedError("recv() must be implemented by a subclass")
103
104
105class VideoStreamTrack(MediaStreamTrack):
106 """Base video track. Selkies' `VideoMedia` overrides `recv` to serve
107 pre-encoded packets from pixelflux; the base itself produces nothing."""
108
109 kind = "video"
110
111 async def recv(self) -> Any:
112 raise NotImplementedError("recv() must be implemented by a subclass")