-
Notifications
You must be signed in to change notification settings - Fork 198
/
Copy pathWebRTC.cs
1831 lines (1669 loc) · 71 KB
/
WebRTC.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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering;
namespace Unity.WebRTC
{
/// <summary>
///
/// </summary>
public enum RTCErrorDetailType
{
/// <summary>
///
/// </summary>
DataChannelFailure,
/// <summary>
///
/// </summary>
DtlsFailure,
/// <summary>
///
/// </summary>
FingerprintFailure,
/// <summary>
///
/// </summary>
IdpBadScriptFailure,
/// <summary>
///
/// </summary>
IdpExecutionFailure,
/// <summary>
///
/// </summary>
IdpLoadFailure,
/// <summary>
///
/// </summary>
IdpNeedLogin,
/// <summary>
///
/// </summary>
IdpTimeout,
/// <summary>
///
/// </summary>
IdpTlsFailure,
/// <summary>
///
/// </summary>
IdpTokenExpired,
/// <summary>
///
/// </summary>
IdpTokenInvalid,
/// <summary>
///
/// </summary>
SctpFailure,
/// <summary>
///
/// </summary>
SdpSyntaxError,
/// <summary>
///
/// </summary>
HardwareEncoderNotAvailable,
/// <summary>
///
/// </summary>
HardwareEncoderError
}
/// <summary>
///
/// </summary>
public struct RTCError
{
/// <summary>
///
/// </summary>
public RTCErrorType errorType;
/// <summary>
///
/// </summary>
public string message;
}
/// <summary>
///
/// </summary>
/// <seealso cref="RTCPeerConnection.ConnectionState"/>
public enum RTCPeerConnectionState : int
{
/// <summary>
///
/// </summary>
New = 0,
/// <summary>
///
/// </summary>
Connecting = 1,
/// <summary>
///
/// </summary>
Connected = 2,
/// <summary>
///
/// </summary>
Disconnected = 3,
/// <summary>
///
/// </summary>
Failed = 4,
/// <summary>
///
/// </summary>
Closed = 5
}
/// <summary>
///
/// </summary>
/// <seealso cref="RTCPeerConnection.IceConnectionState"/>
public enum RTCIceConnectionState : int
{
/// <summary>
///
/// </summary>
New = 0,
/// <summary>
///
/// </summary>
Checking = 1,
/// <summary>
///
/// </summary>
Connected = 2,
/// <summary>
///
/// </summary>
Completed = 3,
/// <summary>
///
/// </summary>
Failed = 4,
/// <summary>
///
/// </summary>
Disconnected = 5,
/// <summary>
///
/// </summary>
Closed = 6,
/// <summary>
///
/// </summary>
Max = 7
}
/// <summary>
///
/// </summary>
/// <seealso cref="RTCPeerConnection.GatheringState"/>
public enum RTCIceGatheringState : int
{
/// <summary>
///
/// </summary>
New = 0,
/// <summary>
///
/// </summary>
Gathering = 1,
/// <summary>
///
/// </summary>
Complete = 2
}
/// <summary>
///
/// </summary>
/// <seealso cref="RTCPeerConnection.SignalingState"/>
public enum RTCSignalingState : int
{
/// <summary>
///
/// </summary>
Stable = 0,
/// <summary>
///
/// </summary>
HaveLocalOffer = 1,
/// <summary>
///
/// </summary>
HaveLocalPrAnswer = 2,
/// <summary>
///
/// </summary>
HaveRemoteOffer = 3,
/// <summary>
///
/// </summary>
HaveRemotePrAnswer = 4,
/// <summary>
///
/// </summary>
Closed = 5,
}
/// <summary>
///
/// </summary>
public enum RTCErrorType
{
/// <summary>
///
/// </summary>
None,
/// <summary>
///
/// </summary>
UnsupportedOperation,
/// <summary>
///
/// </summary>
UnsupportedParameter,
/// <summary>
///
/// </summary>
InvalidParameter,
/// <summary>
///
/// </summary>
InvalidRange,
/// <summary>
///
/// </summary>
SyntaxError,
/// <summary>
///
/// </summary>
InvalidState,
/// <summary>
///
/// </summary>
InvalidModification,
/// <summary>
///
/// </summary>
NetworkError,
/// <summary>
///
/// </summary>
ResourceExhausted,
/// <summary>
///
/// </summary>
InternalError,
/// <summary>
///
/// </summary>
OperationErrorWithData
}
/// <summary>
///
/// </summary>
public enum RTCPeerConnectionEventType
{
/// <summary>
///
/// </summary>
ConnectionStateChange,
/// <summary>
///
/// </summary>
DataChannel,
/// <summary>
///
/// </summary>
IceCandidate,
/// <summary>
///
/// </summary>
IceConnectionStateChange,
/// <summary>
///
/// </summary>
Track
}
/// <summary>
///
/// </summary>
public enum RTCSdpType
{
/// <summary>
///
/// </summary>
Offer,
/// <summary>
///
/// </summary>
Pranswer,
/// <summary>
///
/// </summary>
Answer,
/// <summary>
///
/// </summary>
Rollback
}
/// <summary>
/// Please check the <see cref="RTCConfiguration.bundlePolicy"/> in the <see cref="RTCConfiguration"/> class.
/// </summary>
/// <seealso cref="RTCConfiguration.bundlePolicy"/>
public enum RTCBundlePolicy : int
{
/// <summary>
///
/// </summary>
BundlePolicyBalanced = 0,
/// <summary>
///
/// </summary>
BundlePolicyMaxBundle = 1,
/// <summary>
///
/// </summary>
BundlePolicyMaxCompat = 2
}
/// <summary>
/// Please check the <see cref="RTCDataChannel.ReadyState"/> in the <see cref="RTCDataChannel"/> class.
/// </summary>
/// <seealso cref="RTCDataChannel.ReadyState"/>
public enum RTCDataChannelState
{
/// <summary>
///
/// </summary>
Connecting,
/// <summary>
///
/// </summary>
Open,
/// <summary>
///
/// </summary>
Closing,
/// <summary>
///
/// </summary>
Closed
}
/// <summary>
/// The RTCSessionDescription interface represents the setup of one side of a connection or a proposed connection.
/// It contains a description type that identifies the negotiation stage it pertains to, along with the session's SDP (Session Description Protocol)
/// details.
/// </summary>
/// <remarks>
/// Establishing a connection between two parties involves swapping RTCSessionDescription objects,
/// with each one proposing a set of connection setup options that the sender can accommodate.
/// The connection setup is finalized when both parties agree on a particular configuration.
/// </remarks>
/// <example>
/// <code lang="cs"><![CDATA[
/// using System.Collections;
/// using System.Collections.Generic;
/// using System.Linq;
/// using UnityEngine;
/// using Unity.WebRTC;
///
/// class MediaStreamer : MonoBehaviour
/// {
/// private RTCPeerConnection _pc1;
/// private List<RTCRtpSender> pc1Senders;
/// private MediaStream videoStream;
/// private MediaStreamTrack track;
/// private DelegateOnNegotiationNeeded pc1OnNegotiationNeeded;
/// private bool videoUpdateStarted;
///
/// private void Start()
/// {
/// pc1Senders = new List<RTCRtpSender>();
/// pc1OnNegotiationNeeded = () => { StartCoroutine(PcOnNegotiationNeeded(_pc1)); };
/// Call();
/// }
///
/// IEnumerator PcOnNegotiationNeeded(RTCPeerConnection pc)
/// {
/// var op = pc.CreateOffer();
/// yield return op;
/// if (!op.IsError)
/// {
/// yield return StartCoroutine(OnCreateOfferSuccess(pc, op.Desc));
/// }
/// }
///
/// private void Call()
/// {
/// RTCConfiguration configuration = default;
/// configuration.iceServers = new[] { new RTCIceServer { urls = new[] { "stun:stun.l.google.com:19302" } } };
/// _pc1 = new RTCPeerConnection(ref configuration);
/// _pc1.OnNegotiationNeeded = pc1OnNegotiationNeeded;
///
/// videoStream = Camera.main.CaptureStream(1280, 720);
/// track = videoStream.GetTracks().First();
///
/// pc1Senders.Add(_pc1.AddTrack(track));
/// if (!videoUpdateStarted)
/// {
/// StartCoroutine(WebRTC.Update());
/// videoUpdateStarted = true;
/// }
/// }
///
/// private IEnumerator OnCreateOfferSuccess(RTCPeerConnection pc, RTCSessionDescription desc)
/// {
/// Debug.Log($"Offer created. SDP is: \n{desc.sdp}");
/// var op = pc.SetLocalDescription(ref desc);
/// yield return op;
/// }
/// }
///
/// ]]></code>
/// </example>
/// <seealso cref="RTCPeerConnection"/>
/// <seealso cref="RTCRtpSender"/>
public struct RTCSessionDescription
{
/// <summary>
/// An enum that specifies the type of the session description. Refer to <see cref="RTCSdpType"/>.
/// </summary>
public RTCSdpType type;
/// <summary>
/// A string that holds the session's SDP information.
/// </summary>
[MarshalAs(UnmanagedType.LPStr)]
public string sdp;
}
/// <summary>
///
/// </summary>
public struct RTCOfferAnswerOptions
{
/// <summary>
///
/// </summary>
public static RTCOfferAnswerOptions Default =
new RTCOfferAnswerOptions { iceRestart = false, voiceActivityDetection = true };
/// <summary>
///
/// </summary>
[MarshalAs(UnmanagedType.U1)]
public bool iceRestart;
/// <summary>
///
/// </summary>
/// <remarks>
/// this property is not supported yet.
/// </remarks>
[MarshalAs(UnmanagedType.U1)]
public bool voiceActivityDetection;
}
/// <summary>
/// Please check the <see cref="RTCIceServer.credentialType"/> in the <see cref="RTCIceServer"/> struct.
/// </summary>
/// <seealso cref="RTCIceServer.credentialType"/>
public enum RTCIceCredentialType
{
/// <summary>
///
/// </summary>
Password,
/// <summary>
///
/// </summary>
OAuth
}
/// <summary>
/// Represents a configuration for an ICE server used within WebRTC connections.
/// </summary>
/// <remarks>
/// Represents a configuration for an ICE server used within WebRTC connections,
/// including authentication credentials and STUN/TURN server URLs.
/// </remarks>
/// <example>
/// <code lang="cs"><![CDATA[
/// RTCConfiguration configuration = default;
/// configuration.iceServers = new[] { new RTCIceServer { urls = new[] { "stun:stun.l.google.com:19302" } } };
/// ]]></code>
/// </example>
/// /// <seealso cref="RTCConfiguration"/>
[Serializable]
public struct RTCIceServer
{
/// <summary>
/// Specifies the credential for authenticating with the ICE server.
/// </summary>
[Tooltip("Optional: specifies the password to use when authenticating with the ICE server")]
public string credential;
/// <summary>
/// Specifies the type of credential used.
/// </summary>
[Tooltip("What type of credential the `password` value")]
public RTCIceCredentialType credentialType;
/// <summary>
/// An array containing the URLs of STUN or TURN servers to use for ICE negotiation.
/// </summary>
[Tooltip("Array to set URLs of your STUN/TURN servers")]
public string[] urls;
/// <summary>
/// Specifies the user name for authenticating with the ICE server.
/// </summary>
[Tooltip("Optional: specifies the username to use when authenticating with the ICE server")]
public string username;
}
/// <summary>
/// Please check the <see cref="RTCConfiguration.iceTransportPolicy"/> in the <see cref="RTCConfiguration"/> class.
/// </summary>
/// <seealso cref="RTCConfiguration.iceTransportPolicy"/>
public enum RTCIceTransportPolicy : int
{
/// <summary>
///
/// </summary>
Relay = 1,
/// <summary>
///
/// </summary>
All = 3
}
/// <summary>
/// Provides options to configure the new connection.
/// </summary>
/// <remarks>
/// `RTCConfiguration` struct provides options to configure the new connection.
/// </remarks>
/// <example>
/// <code lang="cs"><![CDATA[
/// RTCConfiguration configuration = peerConnection.GetConfiguration();
/// if(configuration.urls.length == 0)
/// {
/// configuration.urls = new[] {"stun:stun.l.google.com:19302"};
/// }
/// peerConnection.SetConfiguration(configuration);
/// ]]></code>
/// </example>
/// <seealso cref="RTCPeerConnection.GetConfiguration()"/>
/// <seealso cref="RTCPeerConnection.SetConfiguration(ref RTCConfiguration)"/>
[Serializable]
public struct RTCConfiguration
{
/// <summary>
/// List of RTCIceServer objects, each describing one server which may be used by the ICE agent.
/// </summary>
public RTCIceServer[] iceServers;
/// <summary>
/// Represents the current ICE transport policy.
/// </summary>
public RTCIceTransportPolicy? iceTransportPolicy;
/// <summary>
/// Specifies how to handle negotiation of candidates when the remote peer is not compatible with the SDP BUNDLE standard.
/// </summary>
public RTCBundlePolicy? bundlePolicy;
/// <summary>
/// Specifies the size of the prefetched ICE candidate pool.
/// </summary>
public int? iceCandidatePoolSize;
internal RTCConfiguration(ref RTCConfigurationInternal v)
{
iceServers = v.iceServers;
iceTransportPolicy = v.iceTransportPolicy.AsEnum<RTCIceTransportPolicy>();
bundlePolicy = v.bundlePolicy.AsEnum<RTCBundlePolicy>();
iceCandidatePoolSize = v.iceCandidatePoolSize;
}
internal RTCConfigurationInternal Cast()
{
RTCConfigurationInternal instance = new RTCConfigurationInternal
{
iceServers = this.iceServers,
iceTransportPolicy = OptionalInt.FromEnum(this.iceTransportPolicy),
bundlePolicy = OptionalInt.FromEnum(this.bundlePolicy),
iceCandidatePoolSize = this.iceCandidatePoolSize,
};
return instance;
}
}
[Serializable]
struct RTCConfigurationInternal
{
public RTCIceServer[] iceServers;
public OptionalInt iceTransportPolicy;
public OptionalInt bundlePolicy;
public OptionalInt iceCandidatePoolSize;
public OptionalBool enableDtlsSrtp;
}
/// <summary>
///
/// </summary>
public enum NativeLoggingSeverity
{
/// <summary>
///
/// </summary>
Verbose,
/// <summary>
///
/// </summary>
Info,
/// <summary>
///
/// </summary>
Warning,
/// <summary>
///
/// </summary>
Error,
/// <summary>
///
/// </summary>
None,
};
/// <summary>
/// Provides utilities and management functions for integrating WebRTC functionality.
/// </summary>
/// <remarks>
/// `WebRTC` class provides a set of static methods and properties to manage the WebRTC functionality.
/// </remarks>
/// <example>
/// <code lang="cs"><![CDATA[
/// StartCoroutine(WebRTC.Update());
/// ]]></code>
/// </example>
/// <seealso cref="WebRTCSettings"/>
public static class WebRTC
{
#if UNITY_IOS
internal const string Lib = "__Internal";
#else
internal const string Lib = "webrtc";
#endif
private static Context s_context = null;
private static SynchronizationContext s_syncContext;
private static ILogger s_logger;
[RuntimeInitializeOnLoadMethod]
static void RuntimeInitializeOnLoadMethod()
{
// Initialize a custom invokable synchronization context to wrap the main thread UnitySynchronizationContext
s_syncContext = new ExecutableUnitySynchronizationContext(SynchronizationContext.Current);
}
internal static void InitializeInternal(bool limitTextureSize = true, bool enableNativeLog = false,
NativeLoggingSeverity nativeLoggingSeverity = NativeLoggingSeverity.Info)
{
if (s_context != null)
throw new InvalidOperationException("Already initialized WebRTC.");
NativeMethods.RegisterDebugLog(DebugLog, enableNativeLog, nativeLoggingSeverity);
NativeMethods.StatsCollectorRegisterCallback(OnCollectStatsCallback);
NativeMethods.CreateSessionDescriptionObserverRegisterCallback(OnCreateSessionDescription);
NativeMethods.SetLocalDescriptionObserverRegisterCallback(OnSetLocalDescription);
NativeMethods.SetRemoteDescriptionObserverRegisterCallback(OnSetRemoteDescription);
NativeMethods.SetTransformedFrameRegisterCallback(OnSetTransformedFrame);
#if UNITY_IOS && !UNITY_EDITOR
NativeMethods.RegisterRenderingWebRTCPlugin();
#endif
s_context = Context.Create();
s_context.limitTextureSize = limitTextureSize;
NativeMethods.SetCurrentContext(s_context.self);
}
/// <summary>
/// Updates the texture data for all video tracks at the end of each frame.
/// </summary>
/// <remarks>
/// `Update` method updates the texture data for all video tracks at the end of each frame.
/// </remarks>
/// <returns>`IEnumerator` to facilitate coroutine execution.</returns>
/// <example>
/// <code lang="cs"><![CDATA[
/// StartCoroutine(WebRTC.Update());
/// ]]></code>
/// </example>
public static IEnumerator Update()
{
var instruction = new WaitForEndOfFrame();
while (true)
{
// Wait until all frame rendering is done
yield return instruction;
{
var tempTextureActive = RenderTexture.active;
RenderTexture.active = null;
var batch = Context.batch;
batch.ResizeCapacity(VideoStreamTrack.s_tracks.Count);
int trackIndex = 0;
foreach (var reference in VideoStreamTrack.s_tracks.Values)
{
if (!reference.TryGetTarget(out var track))
continue;
track.UpdateTexture();
if (track.DataPtr != IntPtr.Zero)
{
batch.data.tracks[trackIndex] = track.DataPtr;
trackIndex++;
}
}
batch.data.tracksCount = trackIndex;
if (trackIndex > 0)
batch.Submit();
RenderTexture.active = tempTextureActive;
}
}
}
/// <summary>
/// Executes any pending tasks generated asynchronously during the WebRTC runtime.
/// </summary>
/// <remarks>
/// `ExecutePendingTasks` method processes pending tasks generated during WebRTC operations until reaching the specified timeout.
/// </remarks>
/// <param name="millisecondTimeout">
/// The maximum time in milliseconds for which to process the task queue before task execution stops.
/// </param>
/// <returns>
/// `true` if all pending tasks were completed within <see cref="millisecondTimeout"/> milliseconds and `false` otherwise.
/// </returns>
/// <example>
/// <code lang="cs"><![CDATA[
/// WebRTC.ExecutePendingTasks(100);
/// ]]></code>
/// </example>
public static bool ExecutePendingTasks(int millisecondTimeout)
{
if (s_syncContext is ExecutableUnitySynchronizationContext executableContext)
{
return executableContext.ExecutePendingTasks(millisecondTimeout);
}
return false;
}
/// <summary>
/// Controls whether texture size constraints are applied during WebRTC streaming.
/// </summary>
public static bool enableLimitTextureSize
{
get { return s_context.limitTextureSize; }
set { s_context.limitTextureSize = value; }
}
/// <summary>
/// Logger used for capturing debug messages within the WebRTC package.
/// Defaults to Debug.unityLogger.
/// </summary>
/// <exception cref="ArgumentNullException">Throws if setting a null logger.</exception>
public static ILogger Logger
{
get
{
if (s_logger == null)
{
return Debug.unityLogger;
}
return s_logger;
}
set
{
s_logger = value ?? throw new ArgumentNullException(nameof(value));
}
}
/// <summary>
/// Configures native logging settings for WebRTC.
/// </summary>
/// <remarks>
/// `ConfigureNativeLogging` method is used to enable or disable native logging and set the native logging level.
/// </remarks>
/// <param name="enableNativeLogging">Enables or disable native logging.</param>
/// <param name="nativeLoggingSeverity">Sets the native logging level.</param>
/// <example>
/// <code lang="cs"><![CDATA[
/// WebRTC.ConfigureNativeLogging(true, NativeLoggingSeverity.Warning);
/// ]]></code>
/// </example>
public static void ConfigureNativeLogging(bool enableNativeLogging, NativeLoggingSeverity nativeLoggingSeverity)
{
if (enableNativeLogging)
{
NativeMethods.RegisterDebugLog(DebugLog, enableNativeLogging, nativeLoggingSeverity);
}
else
{
NativeMethods.RegisterDebugLog(null, false, nativeLoggingSeverity);
}
}
/// <summary>
/// Sets the graphics sync timeout.
/// Graphics sync timeout determines how long the graphics device will wait on the frame copy for encoding before timing out.
/// By default timeout is set to 60 milliseconds.
/// </summary>
/// <param name="nSecTimeout">The timeout value specified in nanoseconds.</param>
public static void SetGraphicsSyncTimeout(uint nSecTimeout)
{
NativeMethods.SetGraphicsSyncTimeout(nSecTimeout);
}
internal static void DisposeInternal()
{
if (s_context != null)
{
s_context.Dispose();
s_context = null;
}
NativeMethods.RegisterDebugLog(null, false, NativeLoggingSeverity.Info);
}
internal static RTCError ValidateTextureSize(int width, int height, RuntimePlatform platform)
{
if (!s_context.limitTextureSize)
{
return new RTCError { errorType = RTCErrorType.None };
}
const int maxPixelCount = 3840 * 2160;
// Using codec is determined when the Encoder initialization process.
// Therefore, it is not possible to limit the resolution before that. (supported resolutions depend on the codec and its profile.)
// For workaround, all 4k resolutions and above are considered as errors.
// (Because under 4k resolution is almost supported by the supported codecs.)
// todo: Resize the texture size when encoder initialization process, or fall back to another encoder.
if (width * height > maxPixelCount)
{
return new RTCError
{
errorType = RTCErrorType.InvalidRange,
message = $"Texture pixel count is invalid. " +
$"width:{width} x height:{height} is over 4k pixel count ({maxPixelCount})."
};
}
// Check NVCodec capabilities
// todo(kazuki):: The constant values should be replaced by values that are got from NvCodec API.
// Use "nvEncGetEncodeCaps" function which is provided by the NvCodec API.
if (NvEncSupportedPlatdorm(platform))
{
const int minWidth = 145;
const int maxWidth = 4096;
const int minHeight = 49;
const int maxHeight = 4096;
if (width < minWidth || maxWidth < width ||
height < minHeight || maxHeight < height)
{
return new RTCError
{
errorType = RTCErrorType.InvalidRange,
message = $"Texture size is invalid. " +
$"minWidth:{minWidth}, maxWidth:{maxWidth} " +
$"minHeight:{minHeight}, maxHeight:{maxHeight} " +
$"current size width:{width} height:{height}"
};
}
}
if (platform == RuntimePlatform.Android)
{
// Some android crash when smaller than this size
const int minimumTextureSize = 114;
if (width < minimumTextureSize || height < minimumTextureSize)
{
return new RTCError
{
errorType = RTCErrorType.InvalidRange,
message =
$"Texture size need {minimumTextureSize}, current size width:{width} height:{height}"
};
}
}
return new RTCError { errorType = RTCErrorType.None };
}
/// <summary>
/// Checks whether the specified graphics format is supported.
/// </summary>
/// <remarks>
/// `ValidateGraphicsFormat` method checks whether the provided `GraphicsFormat` is compatible with the current graphics device.
/// This method throws an `ArgumentException` if the format is not supported.
/// </remarks>
/// <param name="format">`GraphicsFormat` value to be validated.</param>
/// <example>
/// <code lang="cs"><![CDATA[
/// WebRTC.ValidateGraphicsFormat(format);
/// ]]></code>