react-native-webrtc 155.0.0 → 155.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,6 @@
1
1
  # WebRTC
2
2
  -keep class org.webrtc.** { *; }
3
+ -keep class org.jni_zero.** { *; }
4
+ -keep class J.N { *; }
5
+ -dontwarn org.jni_zero.**
6
+ -dontwarn org.webrtc.**
@@ -8,6 +8,8 @@ import android.media.projection.MediaProjectionConfig;
8
8
  import android.util.DisplayMetrics;
9
9
  import android.util.Log;
10
10
  import android.os.Build;
11
+ import android.os.Handler;
12
+ import android.os.Looper;
11
13
 
12
14
  import androidx.core.util.Consumer;
13
15
 
@@ -34,7 +36,9 @@ import java.util.List;
34
36
  import java.util.Map;
35
37
  import java.util.Objects;
36
38
  import java.util.UUID;
39
+ import java.util.concurrent.CompletableFuture;
37
40
  import java.util.concurrent.TimeUnit;
41
+ import java.util.concurrent.TimeoutException;
38
42
  import java.util.stream.Collectors;
39
43
 
40
44
  /**
@@ -92,8 +96,14 @@ class GetUserMediaImpl {
92
96
 
93
97
  mediaProjectionPermissionResultData = data;
94
98
 
95
- MediaProjectionService.launch(activity)
96
- .orTimeout(10, TimeUnit.SECONDS)
99
+ CompletableFuture<Void> launchFuture = MediaProjectionService.launch(activity);
100
+
101
+ // CompletableFuture.orTimeout() requires API 31; this is a no-op if already completed.
102
+ new Handler(Looper.getMainLooper()).postDelayed(
103
+ () -> launchFuture.completeExceptionally(new TimeoutException()),
104
+ TimeUnit.SECONDS.toMillis(10));
105
+
106
+ launchFuture
97
107
  .whenCompleteAsync((value, error) -> {
98
108
  if (error != null) {
99
109
  Log.e(TAG, "Failed to start MediaProjection service", error);
@@ -500,8 +510,8 @@ class GetUserMediaImpl {
500
510
  TrackPrivate track = tracks.get(trackId);
501
511
 
502
512
  if (track != null && track.videoCaptureController instanceof CameraCaptureController) {
503
- VideoSource videoSource = (VideoSource) track.mediaSource;
504
513
  SurfaceTextureHelper surfaceTextureHelper = track.surfaceTextureHelper;
514
+ VideoEffectProcessor videoEffectProcessor = null;
505
515
 
506
516
  if (names != null) {
507
517
  List<VideoFrameProcessor> processors =
@@ -519,12 +529,10 @@ class GetUserMediaImpl {
519
529
  .filter(Objects::nonNull)
520
530
  .collect(Collectors.toList());
521
531
 
522
- VideoEffectProcessor videoEffectProcessor = new VideoEffectProcessor(processors, surfaceTextureHelper);
523
- videoSource.setVideoProcessor(videoEffectProcessor);
524
-
525
- } else {
526
- videoSource.setVideoProcessor(null);
532
+ videoEffectProcessor = new VideoEffectProcessor(processors, surfaceTextureHelper);
527
533
  }
534
+
535
+ track.setVideoEffectProcessor(videoEffectProcessor);
528
536
  }
529
537
  }
530
538
 
@@ -548,6 +556,11 @@ class GetUserMediaImpl {
548
556
 
549
557
  private final SurfaceTextureHelper surfaceTextureHelper;
550
558
 
559
+ /**
560
+ * The processor chain that the video source uses, if any. Used only on the executor thread.
561
+ */
562
+ private VideoEffectProcessor videoEffectProcessor;
563
+
551
564
  /**
552
565
  * Whether this object has been disposed or not.
553
566
  */
@@ -572,6 +585,22 @@ class GetUserMediaImpl {
572
585
  this.disposed = false;
573
586
  }
574
587
 
588
+ /**
589
+ * Sets the processor chain of the video source and releases the previous one.
590
+ */
591
+ public void setVideoEffectProcessor(VideoEffectProcessor newVideoEffectProcessor) {
592
+ // setVideoProcessor() holds the lock that frame delivery takes, so the previous chain
593
+ // gets no more frames after it returns.
594
+ ((VideoSource) mediaSource).setVideoProcessor(newVideoEffectProcessor);
595
+
596
+ VideoEffectProcessor previousVideoEffectProcessor = videoEffectProcessor;
597
+ videoEffectProcessor = newVideoEffectProcessor;
598
+
599
+ if (previousVideoEffectProcessor != null) {
600
+ previousVideoEffectProcessor.release();
601
+ }
602
+ }
603
+
575
604
  public void dispose() {
576
605
  if (!disposed) {
577
606
  if (videoCaptureController != null) {
@@ -580,6 +609,10 @@ class GetUserMediaImpl {
580
609
  }
581
610
  }
582
611
 
612
+ if (videoEffectProcessor != null) {
613
+ setVideoEffectProcessor(null);
614
+ }
615
+
583
616
  /*
584
617
  * As per webrtc library documentation - The caller still has ownership of {@code
585
618
  * surfaceTextureHelper} and is responsible for making sure surfaceTextureHelper.dispose() is
@@ -359,7 +359,6 @@ class PeerConnectionObserver implements PeerConnection.Observer {
359
359
  final String reactTag = UUID.randomUUID().toString();
360
360
  DataChannelWrapper dcw = new DataChannelWrapper(webRTCModule, id, reactTag, dataChannel);
361
361
  dataChannels.put(reactTag, dcw);
362
- dataChannel.registerObserver(dcw);
363
362
 
364
363
  WritableMap info = Arguments.createMap();
365
364
  info.putInt("peerConnectionId", id);
@@ -381,6 +380,9 @@ class PeerConnectionObserver implements PeerConnection.Observer {
381
380
  params.putMap("dataChannel", info);
382
381
 
383
382
  webRTCModule.sendEvent("peerConnectionDidOpenDataChannel", params);
383
+
384
+ // Ensure buffered messages reach JavaScript after the DataChannel is created.
385
+ dataChannel.registerObserver(dcw);
384
386
  });
385
387
  }
386
388
 
@@ -24,6 +24,8 @@ import org.webrtc.RendererCommon;
24
24
  import org.webrtc.RendererCommon.RendererEvents;
25
25
  import org.webrtc.RendererCommon.ScalingType;
26
26
  import org.webrtc.SurfaceViewRenderer;
27
+ import org.webrtc.VideoFrame;
28
+ import org.webrtc.VideoSink;
27
29
  import org.webrtc.VideoTrack;
28
30
 
29
31
  import java.lang.reflect.InvocationTargetException;
@@ -139,8 +141,43 @@ public class WebRTCView extends ViewGroup {
139
141
  private String streamURL;
140
142
 
141
143
  /**
142
- * The {@link View} and {@link VideoSink} implementation which
143
- * actually renders {@link #videoTrack} on behalf of this instance.
144
+ * The URL most recently passed to {@link #setStreamURL(String)}. The track
145
+ * lookup is asynchronous, so a callback for an older URL must be ignored.
146
+ */
147
+ private String requestedStreamURL;
148
+
149
+ /**
150
+ * The sink currently added to {@link #videoTrack}. It forwards frames to
151
+ * {@link #surfaceViewRenderer} only while it is open, and it is closed on
152
+ * the UI thread as soon as the track is let go, so frames of a previous
153
+ * track are never drawn even if the asynchronous removeSink runs late.
154
+ */
155
+ private TrackSink trackSink;
156
+
157
+ private final class TrackSink implements VideoSink {
158
+ final VideoTrack track;
159
+ private boolean open = true;
160
+
161
+ TrackSink(VideoTrack track) {
162
+ this.track = track;
163
+ }
164
+
165
+ @Override
166
+ public synchronized void onFrame(VideoFrame frame) {
167
+ if (open) {
168
+ surfaceViewRenderer.onFrame(frame);
169
+ }
170
+ }
171
+
172
+ synchronized void close() {
173
+ open = false;
174
+ }
175
+ }
176
+
177
+ /**
178
+ * The {@link View} which actually renders {@link #videoTrack} on behalf of
179
+ * this instance. It is not added to the track directly: frames reach it
180
+ * through the {@link TrackSink} in {@link #trackSink}.
144
181
  */
145
182
  private final SurfaceViewRenderer surfaceViewRenderer;
146
183
 
@@ -375,14 +412,22 @@ public class WebRTCView extends ViewGroup {
375
412
  */
376
413
  private void removeRendererFromVideoTrack() {
377
414
  if (rendererAttached) {
378
- if (videoTrack != null) {
415
+ // Capture the sink now: by the time the executor runs, the
416
+ // videoTrack field may already be null or the next track.
417
+ final TrackSink sink = trackSink;
418
+ trackSink = null;
419
+ if (sink != null) {
420
+ sink.close();
379
421
  ThreadUtils.runOnExecutor(() -> {
380
422
  try {
381
- videoTrack.removeSink(surfaceViewRenderer);
382
- } catch (Throwable tr) {
423
+ sink.track.removeSink(sink);
424
+ } catch (IllegalStateException e) {
383
425
  // XXX If WebRTCModule#mediaStreamTrackRelease has already been
384
- // invoked on videoTrack, then it is no longer safe to call removeSink
385
- // on the instance, it will throw IllegalStateException.
426
+ // invoked on the track this sink was added to, then the track is
427
+ // disposed and removeSink throws IllegalStateException. That is
428
+ // expected and there is nothing left to remove.
429
+ } catch (Throwable tr) {
430
+ Log.w(TAG, "Failed to remove renderer", tr);
386
431
  }
387
432
  });
388
433
  }
@@ -477,23 +522,30 @@ public class WebRTCView extends ViewGroup {
477
522
  * this {@code WebRTCView} or {@code null}.
478
523
  */
479
524
  void setStreamURL(String streamURL) {
480
- Log.d(TAG, "Set stream URL " + streamURL + " current: " + this.streamURL);
481
- if (Objects.equals(streamURL, this.streamURL)) {
525
+ Log.d(TAG,
526
+ "Set stream URL " + streamURL + " requested: " + this.requestedStreamURL
527
+ + " applied: " + this.streamURL);
528
+ // Compare with the last requested URL, not the applied one, which is
529
+ // only updated once the asynchronous lookup below completes.
530
+ if (Objects.equals(streamURL, this.requestedStreamURL)) {
482
531
  return;
483
532
  }
484
-
485
- // The value of this.streamURL is really changing. Before
486
- // realizing/applying the change, let go of the old videoTrack. Of
487
- // course, that is only necessary if the value of videoTrack will
488
- // really change. Please note though that letting go of the old
489
- // videoTrack before assigning to this.streamURL is vital;
490
- // otherwise, removeRendererFromVideoTrack will fail to remove the
491
- // old videoTrack from the associated videoRenderer, two
492
- // VideoTracks (the old and the new) may start rendering and, most
493
- // importantly the videoRender may eventually crash when the old
494
- // videoTrack is disposed.
533
+ this.requestedStreamURL = streamURL;
534
+
535
+ // The value of this.streamURL is really changing. Look up the new
536
+ // videoTrack asynchronously and, once the lookup completes, let go of
537
+ // the old videoTrack (only if the track really changes) and render
538
+ // the new one. removeRendererFromVideoTrack removes exactly the
539
+ // TrackSink that was added to the old videoTrack and closes it right
540
+ // away, so the old track's frames are not drawn after the switch even
541
+ // if the asynchronous removeSink runs late.
495
542
  getVideoTrackForStreamURL(streamURL, videoTrack -> {
496
543
  Log.d(TAG, "Got video track for stream URL " + streamURL + " -> " + videoTrack);
544
+ if (!Objects.equals(streamURL, this.requestedStreamURL)) {
545
+ // A newer setStreamURL call superseded this one.
546
+ Log.d(TAG, "Ignoring stale track lookup for " + streamURL + ", requested: " + requestedStreamURL);
547
+ return;
548
+ }
497
549
  if (this.videoTrack != videoTrack) {
498
550
  setVideoTrack(null);
499
551
  }
@@ -584,15 +636,20 @@ public class WebRTCView extends ViewGroup {
584
636
  return;
585
637
  }
586
638
 
639
+ // Add a sink for exactly this track; the videoTrack field may
640
+ // already hold another track when the executor runs.
641
+ final TrackSink sink = new TrackSink(videoTrack);
642
+ trackSink = sink;
587
643
  ThreadUtils.runOnExecutor(() -> {
588
644
  try {
589
- videoTrack.addSink(surfaceViewRenderer);
590
- } catch (Throwable tr) {
645
+ sink.track.addSink(sink);
646
+ } catch (IllegalStateException e) {
591
647
  // XXX If WebRTCModule#mediaStreamTrackRelease has already been
592
- // invoked on videoTrack, then it is no longer safe to call addSink
593
- // on the instance, it will throw IllegalStateException.
594
-
595
- Log.e(TAG, "Failed to add renderer", tr);
648
+ // invoked on the track this sink is for, then the track is
649
+ // disposed and addSink throws IllegalStateException. That is
650
+ // expected: the track is gone, so there is nothing to render.
651
+ } catch (Throwable tr) {
652
+ Log.w(TAG, "Failed to add renderer", tr);
596
653
  }
597
654
  });
598
655
 
@@ -1,6 +1,9 @@
1
1
  package com.oney.WebRTCModule.videoEffects;
2
2
 
3
+ import android.util.Log;
4
+
3
5
  import org.webrtc.SurfaceTextureHelper;
6
+ import org.webrtc.ThreadUtils;
4
7
  import org.webrtc.VideoFrame;
5
8
  import org.webrtc.VideoProcessor;
6
9
  import org.webrtc.VideoSink;
@@ -12,6 +15,8 @@ import java.util.List;
12
15
  * them, and pass them on to another object.
13
16
  */
14
17
  public class VideoEffectProcessor implements VideoProcessor {
18
+ private static final String TAG = VideoEffectProcessor.class.getSimpleName();
19
+
15
20
  private VideoSink mSink;
16
21
  final private SurfaceTextureHelper textureHelper;
17
22
  final private List<VideoFrameProcessor> videoFrameProcessors;
@@ -56,4 +61,20 @@ public class VideoEffectProcessor implements VideoProcessor {
56
61
  mSink.onFrame(outputFrame);
57
62
  outputFrame.release();
58
63
  }
64
+
65
+ /**
66
+ * Releases the frame processors on the capture thread, where their GL context is current.
67
+ * Call it only after the video source stops sending frames here.
68
+ */
69
+ public void release() {
70
+ ThreadUtils.invokeAtFrontUninterruptibly(textureHelper.getHandler(), () -> {
71
+ for (VideoFrameProcessor processor : this.videoFrameProcessors) {
72
+ try {
73
+ processor.release();
74
+ } catch (Throwable t) {
75
+ Log.e(TAG, "Failed to release video frame processor " + processor.getClass().getName(), t);
76
+ }
77
+ }
78
+ });
79
+ }
59
80
  }
@@ -16,4 +16,10 @@ public interface VideoFrameProcessor {
16
16
  * @return processed videoframe which will rendered
17
17
  */
18
18
  public VideoFrame process(VideoFrame frame, SurfaceTextureHelper textureHelper);
19
+
20
+ /**
21
+ * Called once after the last process() call, on the same thread, when the effects of the track
22
+ * change or the track is disposed. Frames already returned can still be in use downstream.
23
+ */
24
+ default void release() {}
19
25
  }
@@ -5,8 +5,8 @@ package com.oney.WebRTCModule.videoEffects;
5
5
  */
6
6
  public interface VideoFrameProcessorFactoryInterface {
7
7
  /**
8
- * Dynamically allocates a VideoFrameProcessor instance and returns a pointer to it.
9
- * The caller takes ownership of the object.
8
+ * Returns a new VideoFrameProcessor on each call, not a shared one.
9
+ * The caller takes ownership and calls release() on it when the chain is replaced.
10
10
  */
11
11
  public VideoFrameProcessor build();
12
12
  }
@@ -25,4 +25,7 @@
25
25
  + (NSDictionary *_Nonnull)streamToJSONWithPeerConnectionId:(NSNumber *_Nonnull)id
26
26
  stream:(RTCMediaStream *_Nonnull)stream
27
27
  streamReactTag:(NSString *_Nonnull)streamReactTag;
28
+ + (NSNumber *_Nullable)parseDegradationPreference:(NSString *_Nonnull)name;
29
+ + (NSString *_Nullable)serializeDegradationPreference:(NSNumber *_Nonnull)value;
30
+
28
31
  @end
@@ -75,6 +75,29 @@
75
75
  return receiverDictionary;
76
76
  }
77
77
 
78
+ /**
79
+ * The names RTCRtpSendParameters exchanges with JS, indexed by RTCDegradationPreference.
80
+ *
81
+ * JS sends and expects a name such as MAINTAIN_FRAMERATE, while the native property is an
82
+ * NSNumber wrapping the enum, so both directions need a conversion.
83
+ */
84
+ + (NSArray<NSString *> *_Nonnull)degradationPreferenceNames {
85
+ return @[ @"DISABLED", @"MAINTAIN_FRAMERATE", @"MAINTAIN_RESOLUTION", @"BALANCED" ];
86
+ }
87
+
88
+ + (NSNumber *_Nullable)parseDegradationPreference:(NSString *_Nonnull)name {
89
+ NSUInteger index = [[self degradationPreferenceNames] indexOfObject:[name uppercaseString]];
90
+
91
+ return index == NSNotFound ? nil : @(index);
92
+ }
93
+
94
+ + (NSString *_Nullable)serializeDegradationPreference:(NSNumber *_Nonnull)value {
95
+ NSArray<NSString *> *names = [self degradationPreferenceNames];
96
+ NSInteger index = value.integerValue;
97
+
98
+ return (index >= 0 && index < (NSInteger)names.count) ? names[index] : nil;
99
+ }
100
+
78
101
  + (NSDictionary *)parametersToJSON:(RTCRtpParameters *)params {
79
102
  NSMutableDictionary *paramsDictionary = [NSMutableDictionary new];
80
103
 
@@ -145,8 +168,12 @@
145
168
  paramsDictionary[@"encodings"] = encodings;
146
169
  paramsDictionary[@"codecs"] = codecs;
147
170
 
148
- if (params.degradationPreference) {
149
- paramsDictionary[@"degradationPreference"] = params.degradationPreference;
171
+ if (params.degradationPreference != nil) {
172
+ NSString *name = [SerializeUtils serializeDegradationPreference:params.degradationPreference];
173
+
174
+ if (name != nil) {
175
+ paramsDictionary[@"degradationPreference"] = name;
176
+ }
150
177
  }
151
178
 
152
179
  return paramsDictionary;
@@ -51,23 +51,6 @@
51
51
  return;
52
52
  }
53
53
 
54
- // Enable Center Stage when the device supports it; cooperative with Control Center.
55
- if (@available(iOS 16.0, *)) {
56
- BOOL centerStageSupported = NO;
57
- for (AVCaptureDeviceFormat *fmt in [RTCCameraVideoCapturer supportedFormatsForDevice:self.device]) {
58
- if (fmt.isCenterStageSupported) {
59
- centerStageSupported = YES;
60
- break;
61
- }
62
- }
63
- if (centerStageSupported) {
64
- AVCaptureDevice.centerStageControlMode = AVCaptureCenterStageControlModeCooperative;
65
- AVCaptureDevice.centerStageEnabled = YES;
66
- } else if (AVCaptureDevice.isCenterStageEnabled) {
67
- AVCaptureDevice.centerStageEnabled = NO;
68
- }
69
- }
70
-
71
54
  AVCaptureDeviceFormat *format = [self selectFormatForDevice:self.device
72
55
  withTargetWidth:self.width
73
56
  withTargetHeight:self.height];
@@ -79,17 +62,6 @@
79
62
 
80
63
  self.selectedFormat = format;
81
64
 
82
- // Clamp fps to the range Center Stage allows for this format.
83
- int fps = self.frameRate;
84
- if (@available(iOS 16.0, *)) {
85
- if (AVCaptureDevice.isCenterStageEnabled) {
86
- AVFrameRateRange *csRange = format.videoFrameRateRangeForCenterStage;
87
- if (csRange) {
88
- fps = MAX((int)csRange.minFrameRate, MIN(fps, (int)csRange.maxFrameRate));
89
- }
90
- }
91
- }
92
-
93
65
  AVCaptureSession *session = self.capturer.captureSession;
94
66
  if (@available(iOS 16.0, *)) {
95
67
  BOOL enable = self.enableMultitaskingCameraAccess;
@@ -111,7 +83,7 @@
111
83
  __weak VideoCaptureController *weakSelf = self;
112
84
  [self.capturer startCaptureWithDevice:self.device
113
85
  format:format
114
- fps:fps
86
+ fps:self.frameRate
115
87
  completionHandler:^(NSError *err) {
116
88
  if (err) {
117
89
  RCTLogError(@"[VideoCaptureController] Error starting capture: %@", err);
@@ -298,18 +270,7 @@
298
270
  AVCaptureDeviceFormat *selectedFormat = nil;
299
271
  int currentDiff = INT_MAX;
300
272
 
301
- BOOL centerStageEnabled = NO;
302
- if (@available(iOS 16.0, *)) {
303
- centerStageEnabled = AVCaptureDevice.isCenterStageEnabled;
304
- }
305
-
306
273
  for (AVCaptureDeviceFormat *format in formats) {
307
- // Center Stage only permits supported formats.
308
- if (@available(iOS 16.0, *)) {
309
- if (centerStageEnabled && !format.isCenterStageSupported) {
310
- continue;
311
- }
312
- }
313
274
  CMVideoDimensions dimension = CMVideoFormatDescriptionGetDimensions(format.formatDescription);
314
275
  FourCharCode pixelFormat = CMFormatDescriptionGetMediaSubType(format.formatDescription);
315
276
  int diff = abs(targetWidth - dimension.width) + abs(targetHeight - dimension.height);
@@ -245,8 +245,11 @@ RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(transceiverSetCodecPreferences : (nonnull
245
245
  encoding.scaleResolutionDownBy = encodingUpdate[@"scaleResolutionDownBy"];
246
246
  }
247
247
 
248
- if ([options objectForKey:@"degradationPreference"]) {
249
- params.degradationPreference = [options objectForKey:@"degradationPreference"];
248
+ id degradationPreference = [options objectForKey:@"degradationPreference"];
249
+ if ([degradationPreference isKindOfClass:[NSString class]]) {
250
+ params.degradationPreference = [SerializeUtils parseDegradationPreference:degradationPreference];
251
+ } else if ([degradationPreference isKindOfClass:[NSNumber class]]) {
252
+ params.degradationPreference = degradationPreference;
250
253
  }
251
254
 
252
255
  return params;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-webrtc",
3
- "version": "155.0.0",
3
+ "version": "155.0.2",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/react-native-webrtc/react-native-webrtc.git"