-
Notifications
You must be signed in to change notification settings - Fork 0
/
media.py
95 lines (79 loc) · 2.61 KB
/
media.py
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
import av
import cv2
import asyncio
from datetime import datetime
from aiortc.contrib.media import (
MediaPlayer,
MediaRelay,
MediaRecorder,
MediaStreamError,
MediaRecorderContext,
)
class CountsPerSec:
"""
Class that tracks the number of occurrences ("counts") of an
arbitrary event and returns the frequency in occurrences
(counts) per second. The caller must increment the count.
"""
def __init__(self):
self._start_time = None
self._num_occurrences = 0
def start(self):
self._start_time = datetime.now()
return self
def increment(self):
self._num_occurrences += 1
def countsPerSec(self):
elapsed_time = (datetime.now() - self._start_time).total_seconds()
return self._num_occurrences / elapsed_time
class MyMediaShower:
"""
A media sink that writes audio and/or video to a file.
Examples:
.. code-block:: python
# Write to a video file.
player = MediaRecorder('/path/to/file.mp4')
# Write to a set of images.
player = MediaRecorder('/path/to/file-%3d.png')
:param file: The path to a file, or a file-like object.
:param format: The format to use, defaults to autodect.
:param options: Additional options to pass to FFmpeg.
"""
def __init__(self, format=None, options={}):
self.__tracks = {}
self.stopped = False
self.cps = CountsPerSec().start()
def addTrack(self, track):
"""
Add a track to be recorded.
:param track: A :class:`aiortc.MediaStreamTrack`.
"""
self.__tracks[track] = MediaRecorderContext(None)
async def start(self):
"""
Start recording.
"""
for track, context in self.__tracks.items():
if context.task is None:
context.task = asyncio.ensure_future(self.__run_track(track, context))
async def stop(self):
"""
Stop recording.
"""
if self.__container:
for track, context in self.__tracks.items():
if context.task is not None:
context.task.cancel()
context.task = None
self.__tracks = {}
async def __run_track(self, track, context):
while True:
try:
frame = await track.recv()
if frame:
# self.cps.increment()
cv2.imshow("Video", frame.to_ndarray(format="rgb24"))
if cv2.waitKey(1) == ord("q"):
self.stopped = True
except MediaStreamError:
return