-
Notifications
You must be signed in to change notification settings - Fork 1
/
Program.cs
391 lines (322 loc) · 14.3 KB
/
Program.cs
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
using System.Net;
using System.Net.Mime;
using System.Text.Json;
using System.Text.Json.Serialization;
using Antelcat.AspNetCore.ProtooSharp;
using Antelcat.MediasoupSharp;
using Antelcat.MediasoupSharp.Demo;
using Antelcat.MediasoupSharp.Demo.Extensions;
using Antelcat.MediasoupSharp.Demo.Lib;
using Antelcat.MediasoupSharp.Internals.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.Primitives;
using Room = Antelcat.MediasoupSharp.Demo.Lib.Room;
using Utils = Antelcat.AspNetCore.ProtooSharp.Utils;
Utils.RandomNumberGenerator = () => Guid.NewGuid().GetHashCode();
List<WorkerImpl<TWorkerAppData>> mediasoupWorkers = [];
Dictionary<string, Room> rooms = [];
var nextMediasoupWorkerIdx = 0;
WebSocketServer protooWebSocketServer;
AwaitQueue queue = new();
FileExtensionContentTypeProvider provider = new();
var builder = WebApplication.CreateBuilder(args);
builder.Logging.AddConsole();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
var loggerFactory = app.Services.GetRequiredService<ILoggerFactory>();
Logger.LoggerFactory = loggerFactory;
var logger = loggerFactory.CreateLogger<Program>();
var jsonSerializerOptions = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
foreach (var converter in Mediasoup.JsonConverters)
{
jsonSerializerOptions.Converters.Add(converter);
}
var options = MediasoupOptions<TWorkerAppData>.Default;
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseWebSockets();
await RunAsync();
await app.RunAsync();
return;
async Task RunAsync()
{
// Open the interactive server.
Interactive.InteractiveServer();
// Run a mediasoup Worker.
await RunMediasoupWorkersAsync();
// Run a protoo WebSocketServer.
RunProtooWebSocketServer();
// Create Express app.
CreateExpressApp();
}
async Task RunMediasoupWorkersAsync()
{
logger.LogInformation("running {Num} mediasoup Workers...", options.NumWorkers);
var useWebRtcServer = Environment.GetEnvironmentVariable("MEDIASOUP_USE_WEBRTC_SERVER") != "false";
Console.WriteLine(new AppSerialization().Serialize(options));
foreach (var task in Mediasoup.CreateWorkers(options.WorkerSettings.NotNull(), options.NumWorkers.NotNull()))
{
var worker = await task;
worker.On(static x => x.Died, async _ =>
{
logger.LogError("mediasoup Worker died, exiting in 2 seconds... [pid:{Pid}]", worker.Pid);
await Task.Delay(2000);
Environment.Exit(1);
});
mediasoupWorkers.Add(worker);
if (!useWebRtcServer) continue;
// Each mediasoup Worker will run its own WebRtcServer, so those cannot
// share the same listening ports. Hence, we increase the value in config.js
// for each Worker.
var webRtcServerOptions = options.WebRtcServerOptions! with { };
var portIncrement = mediasoupWorkers.Count - 1;
foreach (var listenInfo in webRtcServerOptions.ListenInfos)
{
listenInfo.Port += (ushort)portIncrement;
}
var webRtcServer = await worker.CreateWebRtcServerAsync<TWorkerAppData>(new()
{
ListenInfos = webRtcServerOptions.ListenInfos
});
worker.AppData["webRtcServer"] = webRtcServer;
}
}
void CreateExpressApp()
{
// For every API request, verify that the roomId in the path matches and
// existing room.
async ValueTask<object?> RoomFilter(EndpointFilterInvocationContext context, EndpointFilterDelegate @delegate)
{
if (!context.HttpContext.Request.RouteValues.TryGetValue("roomId", out var id) || id is not string roomId)
{
return await @delegate(context);
}
var source = new TaskCompletionSource<object?>();
queue.Push(async () =>
{
context.HttpContext.Items.Add("room", await GetOrCreateRoomAsync(roomId, 0));
source.SetResult(await @delegate(context));
}).Catch(exception => { source.SetException(exception ?? new NullReferenceException("No Exception")); });
return await source.Task;
}
// API GET resource that returns the mediasoup Router RTP capabilities of
// the room.
app.MapGet("/rooms/{roomId}", (HttpContext context) =>
{
var data = context.Room().RouterRtpCapabilities;
return data;
}).AddEndpointFilter(RoomFilter);
// POST API to create a Broadcaster.
app.MapPost("/rooms/{roomId}/broadcasters", async (HttpContext context, [FromBody] CreateBroadcasterRequest json) =>
{
var data = await context.Room().CreateBroadcasterAsync(json);
return data;
}).AddEndpointFilter(RoomFilter);
// DELETE API to delete a Broadcaster.
app.MapDelete("/rooms/{roomId}/broadcasters/{broadcasterId}",
async (HttpContext context, [FromRoute] string broadcasterId) =>
{
await context.Room().DeleteBroadcasterAsync(broadcasterId);
return "broadcaster deleted";
}).AddEndpointFilter(RoomFilter);
// POST API to create a mediasoup Transport associated to a Broadcaster.
// It can be a PlainTransport or a WebRtcTransport depending on the
// type parameters in the body. There are also additional parameters for
// PlainTransport.
app.MapPost("/rooms/{roomId}/broadcasters/{broadcasterId}/transports",
async (HttpContext context, [FromRoute] string broadcasterId, [FromBody] CreateBroadcastTransport json) =>
{
var data = await context.Room().CreateBroadcasterTransportAsync(json);
return data;
}).AddEndpointFilter(RoomFilter);
// POST API to connect a Transport belonging to a Broadcaster. Not needed
// for PlainTransport if it was created with comedia option set to true.
app.MapPost("/rooms/{roomId}/broadcasters/{broadcasterId}/transports/{transportId}/connect",
async (HttpContext context, [FromRoute] string broadcasterId, [FromRoute] string transportId,
[FromBody] ConnectBroadcasterTransportRequest json) =>
{
await context.Room().ConnectBroadcasterTransportAsync(broadcasterId, transportId, json.DtlsParameters);
return Results.Ok();
}).AddEndpointFilter(RoomFilter);
// POST API to create a mediasoup Producer associated to a Broadcaster.
// The exact Transport in which the Producer must be created is signaled in
// the URL path. Body parameters include kind and rtpParameters of the
// Producer.
app.MapPost("/rooms/{roomId}/broadcasters/{broadcasterId}/transports/{transportId}/producers",
async (HttpContext context, [FromRoute] string broadcasterId, [FromRoute] string transportId,
[FromBody] CreateBroadcasterProducerRequest json) =>
{
var (kind, rtpParameters) = json;
var data = await context.Room()
.CreateBroadcasterProducerAsync(broadcasterId, transportId, kind, rtpParameters);
return data;
}).AddEndpointFilter(RoomFilter);
// POST API to create a mediasoup Consumer associated to a Broadcaster.
// The exact Transport in which the Consumer must be created is signaled in
// the URL path. Query parameters must include the desired producerId to
// consume.
app.MapPost("/rooms/{roomId}/broadcasters/{broadcasterId}/transports/{transportId}/consume",
async (HttpContext context, [FromRoute] string broadcasterId, [FromRoute] string transportId,
[FromBody] ProducerRequest json) =>
{
var data = await context.Room().CreateBroadcasterConsumerAsync(broadcasterId, transportId, json.ProducerId);
return data;
}).AddEndpointFilter(RoomFilter);
// POST API to create a mediasoup DataConsumer associated to a Broadcaster.
// The exact Transport in which the DataConsumer must be created is signaled in
// the URL path. Query body must include the desired producerId to
// consume.
app.MapPost("/rooms/{roomId}/broadcasters/{broadcasterId}/transports/{transportId}/consume/data",
async (HttpContext context, [FromRoute] string broadcasterId, [FromRoute] string transportId,
[FromBody] DataProducerRequest json) =>
{
var data = await context.Room()
.CreateBroadcasterDataConsumerAsync(broadcasterId, transportId, json.DataProducerId);
return data;
}).AddEndpointFilter(RoomFilter);
// POST API to create a mediasoup DataProducer associated to a Broadcaster.
// The exact Transport in which the DataProducer must be created is signaled in
app.MapPost("/rooms/{roomId}/broadcasters/{broadcasterId}/transports/{transportId}/produce/data",
async (HttpContext context, [FromRoute] string broadcasterId, [FromRoute] string transportId,
[FromBody] ProduceDataRequest json) =>
{
var (_, sctpStreamParameters, label, protocol, appData) = json;
var data = await context.Room()
.CreateBroadcasterDataProducerAsync(broadcasterId,
transportId,
label,
protocol,
sctpStreamParameters,
appData);
return data;
}).AddEndpointFilter(RoomFilter);
// Error handler.
app.Use(async (context, func) =>
{
try
{
await func(context);
}
catch (Exception ex)
{
return;
}
});
app.Map("/", async (HttpContext context) =>
{
if (!context.WebSockets.IsWebSocketRequest)
{
return Results.File(Path.Combine(AppContext.BaseDirectory, "wwwroot", "index.html"),
MediaTypeNames.Text.Html);
}
await protooWebSocketServer.OnRequest(context);
return Results.Ok();
}).AddEndpointFilter(RoomFilter);
app.MapGet("/{**rest}", ([FromRoute] string rest) =>
{
var path = Path.Combine(AppContext.BaseDirectory, "wwwroot", WebUtility.HtmlDecode(rest));
return File.Exists(path)
? Results.File(path,
provider.TryGetContentType(rest, out var type) ? type : MediaTypeNames.Text.Plain)
: Results.NotFound("file not found");
});
}
//Create a protoo WebSocketServer to allow WebSocket connections from browsers.
void RunProtooWebSocketServer()
{
Serialization.GlobalSerialization = new AppSerialization();
logger.LogInformation("running protoo WebSocketServer...");
// Create the protoo WebSocket server.
protooWebSocketServer = new WebSocketServer(loggerFactory, new());
// Handle connections from clients.
protooWebSocketServer.ConnectionRequest += async (info, accept, reject) =>
{
// The client indicates the roomId and peerId in the URL query.
var u = info.Request;
var roomId = u.Query["roomId"].ToString();
var peerId = u.Query["peerId"].ToString();
if (string.IsNullOrWhiteSpace(roomId) || string.IsNullOrWhiteSpace(peerId))
{
await reject(400, "Connection request without roomId and/or peerId");
return;
}
var consumerReplicas = int.Parse(u.Query["consumerReplicas"] is var value
&& value != StringValues.Empty
&& value.ToString() is not "undefined"
? value.ToString()
: "0");
logger.LogInformation(
"protoo connection request [roomId:{RoomId}, peerId:{PeerId}, address:{Address}, origin:{Origin}]",
roomId, peerId, info.Request.HttpContext.Connection.RemoteIpAddress, info.Origin);
// Serialize this code into the queue to avoid that two peers connecting at
// the same time with the same roomId create two separate rooms with same
// roomId.
queue.Push(async () =>
{
var room = await GetOrCreateRoomAsync(roomId, consumerReplicas);
// Accept the protoo WebSocket connection.
var protooWebSocketTransport = await accept();
room.HandleProtooConnection(peerId, false, protooWebSocketTransport!);
})
.Catch(async exception =>
{
logger.LogError("room creation or room joining failed:{Ex}", exception);
await reject(500, exception!.Message);
});
};
}
//Get next mediasoup Worker.
WorkerImpl<TWorkerAppData> GetMediasoupWorker()
{
var worker = mediasoupWorkers[nextMediasoupWorkerIdx];
if (++nextMediasoupWorkerIdx == mediasoupWorkers.Count)
nextMediasoupWorkerIdx = 0;
return worker;
}
//Get a Room instance (or create one if it does not exist).
async Task<Room> GetOrCreateRoomAsync(string roomId, int consumerReplicas)
{
if (rooms.TryGetValue(roomId, out var room)) return room;
logger.LogInformation("creating a new Room [{RoomId}]", roomId);
var mediasoupWorker = GetMediasoupWorker();
room = await Room.CreateAsync(loggerFactory, options,
mediasoupWorker,
roomId,
consumerReplicas);
rooms.Add(roomId, room);
room.On("close", () => rooms.Remove(roomId));
return room;
}
file static class HttpContextExtension
{
public static Room Room(this HttpContext context) =>
context.Items["room"] as Room ?? throw new NullReferenceException("room");
}
file class AppSerialization : Serialization
{
private readonly JsonSerializerOptions options;
public AppSerialization()
{
options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
WriteIndented = true
};
foreach (var converter in Mediasoup.JsonConverters) options.Converters.Add(converter);
}
public override string Serialize<T>(T instance) => JsonSerializer.Serialize(instance, options);
public override T? Deserialize<T>(string json) where T : default => JsonSerializer.Deserialize<T>(json, options);
}