-
Notifications
You must be signed in to change notification settings - Fork 9
Add VP8 encoding through WEBRTC #47
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
walesch-yan
wants to merge
1
commit into
main
Choose a base branch
from
yw-vp8-output
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,11 +1,12 @@ | ||
| import os | ||
| import asyncio | ||
|
|
||
| from fastapi import FastAPI, WebSocket, Request, WebSocketDisconnect | ||
| from fastapi.responses import StreamingResponse, HTMLResponse | ||
| from fastapi.staticfiles import StaticFiles | ||
|
|
||
| from video_streamer.core.websockethandler import WebsocketHandler | ||
| from video_streamer.core.streamer import FFMPGStreamer, MJPEGStreamer | ||
| from video_streamer.core.streamer import FFMPGStreamer, MJPEGStreamer, VideoMediaStreamer | ||
| from fastapi.templating import Jinja2Templates | ||
|
|
||
| from contextlib import asynccontextmanager | ||
|
|
@@ -15,6 +16,10 @@ | |
| from typing import Optional | ||
| from types import FrameType | ||
|
|
||
| from aiortc import RTCPeerConnection, RTCRtpSender, RTCSessionDescription | ||
| from fastapi.middleware.cors import CORSMiddleware | ||
| from fastapi.responses import JSONResponse | ||
|
|
||
| # This function makes sure that the server is correctly shutted down | ||
| def handle_shutdown(signum: int, frame: Optional[FrameType]) -> None: | ||
| print(f"Received signal {signum}, shutting down streamer...") | ||
|
|
@@ -116,5 +121,72 @@ async def video_in(request: Request): | |
|
|
||
| return app | ||
|
|
||
| def create_vp8_app(config, host, port, debug): | ||
|
|
||
| video_capabilities = RTCRtpSender.getCapabilities("video") | ||
|
|
||
| vp8_codecs = [ | ||
| codec for codec in video_capabilities.codecs | ||
| if codec.mimeType == "video/VP8" | ||
| ] | ||
|
|
||
| @asynccontextmanager | ||
| async def lifespan(app: FastAPI): | ||
| app.state.streamer = VideoMediaStreamer(config, host, port, debug) | ||
| app.state.video_track = app.state.streamer.start() | ||
|
|
||
| app.state.pcs = set() | ||
|
|
||
| # Some signals are catched from uvicorn/fastapi, this makes sure that the server is correctly | ||
| # shutting down and the second part of the lifespan is called | ||
| signal.signal(signal.SIGTERM, handle_shutdown) | ||
| signal.signal(signal.SIGINT, handle_shutdown) | ||
| try: | ||
| yield | ||
| finally: | ||
| for pc in set(app.state.pcs): | ||
| try: | ||
| await asyncio.wait_for(pc.close(), timeout=2) | ||
| except asyncio.TimeoutError: | ||
| print("Timeout while closing peer connection, closing forcefully...") | ||
|
Comment on lines
+148
to
+151
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The pc connections here often might not close gracefully, if a user is still connected on its browser, when we stop the application, hence the forcefull shutdown after timeout is needed |
||
| app.state.pcs.clear() | ||
| app.state.streamer.stop() | ||
|
|
||
| app = FastAPI(lifespan=lifespan) | ||
| app.add_middleware(CORSMiddleware, allow_methods=["OPTIONS", "POST"], allow_origins=config.allowed_origins, allow_headers=["Content-Type"]) | ||
|
|
||
| @app.post("/offer") | ||
| async def offer(request: Request): | ||
| params = await request.json() | ||
| offer = RTCSessionDescription(sdp=params["sdp"], type=params["type"]) | ||
| pc = RTCPeerConnection() | ||
| request.app.state.pcs.add(pc) | ||
|
|
||
| track = request.app.state.video_track | ||
| pc.addTrack(track) | ||
|
|
||
| # set the preferred codec to VP8 | ||
| for transceiver in pc.getTransceivers(): | ||
| if transceiver.kind == "video": | ||
| transceiver.setCodecPreferences(vp8_codecs) | ||
|
|
||
| @pc.on("connectionstatechange") | ||
| async def on_state_change(): | ||
| if pc.connectionState in ("failed", "closed", "disconnected"): | ||
| await pc.close() | ||
| request.app.state.pcs.discard(pc) | ||
|
|
||
| await pc.setRemoteDescription(offer) | ||
| answer = await pc.createAnswer() | ||
| await pc.setLocalDescription(answer) | ||
|
|
||
| return JSONResponse( | ||
| content={ | ||
| "sdp": pc.localDescription.sdp, | ||
| "type": pc.localDescription.type, | ||
| } | ||
| ) | ||
|
|
||
| return app | ||
|
|
||
| available_applications = {"MPEG1": create_mpeg1_app, "MJPEG": create_mjpeg_app} | ||
| available_applications = {"MPEG1": create_mpeg1_app, "MJPEG": create_mjpeg_app, "VP8": create_vp8_app} | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I added this field, to make it possible, to correctly configure the CORS middleware of the application. It currently only works for the VP8 encoding, mainly because in that case we would need additional HTTP Methods, namely
POSTto create the WebRTC method, while MPEG1 and MJPEG only used one websocket connection