Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/guide/video/camera-capture.md
Original file line number Diff line number Diff line change
Expand Up @@ -362,7 +362,7 @@ Rules that keep this correct:
- The pixels of a captured frame may be shared with the source. Write changes into a new buffer, as above, instead of into the captured one.
- `onFrameCaptured()` runs on the capture thread and holds up capturing while it runs. An exception it throws goes to that thread's uncaught exception handler, and the frame is dropped.

`setVideoProcessor(null)` removes the processor. A `CustomVideoSource` does not take a processor: change the frames before pushing them.
`setVideoProcessor(null)` removes the processor. Neither that nor `dispose()` waits for a frame the processor is delivering at that moment, which may still reach the tracks; what it delivers later is dropped. A `CustomVideoSource` does not take a processor: change the frames before pushing them.

## Best Practices

Expand Down
5 changes: 3 additions & 2 deletions docs/guide/video/desktop-capture.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,11 @@ import dev.onvoid.webrtc.media.video.VideoDesktopSource;
VideoDesktopSource videoSource = new VideoDesktopSource();

// Configure the desktop video source
// Set frame rate (e.g., 30 fps)
// Set frame rate (e.g., 30 fps), from 1 to VideoDesktopSource.MAX_FRAME_RATE
videoSource.setFrameRate(30);

// Set maximum frame size (e.g., 1920x1080)
// Set maximum frame size (e.g., 1920x1080). Frames are scaled down to fit
// both limits and keep their aspect ratio.
videoSource.setMaxFrameSize(1920, 1080);

// Select a specific source to capture
Expand Down
4 changes: 2 additions & 2 deletions webrtc-jni/src/main/cpp/include/JNI_VideoDesktopSource.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@

#include "media/video/VideoProcessorHost.h"

#include <atomic>

namespace jni
{
class VideoTrackDesktopSource : public webrtc::AdaptedVideoTrackSource, public webrtc::DesktopCapturer::Callback, public VideoProcessorHost
Expand Down Expand Up @@ -59,7 +61,7 @@ namespace jni

private:
uint16_t frameRate;
bool isCapturing;
std::atomic<bool> isCapturing;
bool focusSelectedSource;

webrtc::DesktopSize maxFrameSize;
Expand Down
23 changes: 18 additions & 5 deletions webrtc-jni/src/main/cpp/src/JNI_VideoDesktopSource.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
#include "rtc_base/logging.h"
#include "rtc_base/ref_counted_object.h"

#include <thread>

JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoDesktopSource_setSourceId
(JNIEnv * env, jobject caller, jlong sourceId, jboolean isWindow)
{
Expand All @@ -37,7 +39,7 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoDesktopSource_set
});
}

JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoDesktopSource_setFrameRate
JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoDesktopSource_setFrameRateInternal
(JNIEnv * env, jobject caller, jint frameRate)
{
jni::CallFromJava(env, [&]() {
Expand Down Expand Up @@ -106,11 +108,22 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoDesktopSource_dis
videoSource->SetVideoProcessor(env, nullptr);
SetHandle<std::nullptr_t>(env, caller, "processorHostHandle", nullptr);

jni::ReleaseHandle(env, videoSource, [videoSource](bool) {
webrtc::RefCountReleaseStatus status = videoSource->Release();
jni::ReleaseHandle(env, videoSource, [videoSource](bool deferred) {
auto release = [videoSource]() {
webrtc::RefCountReleaseStatus status = videoSource->Release();

if (status != webrtc::RefCountReleaseStatus::kDroppedLastRef) {
RTC_LOG(LS_WARNING) << "Native object was not deleted. A reference is still around somewhere.";
}
};

if (status != webrtc::RefCountReleaseStatus::kDroppedLastRef) {
RTC_LOG(LS_WARNING) << "Native object was not deleted. A reference is still around somewhere.";
// The last call may be a processed frame on the capture thread,
// which the destructor of the source stops and cannot join itself.
if (deferred) {
std::thread(release).detach();
}
else {
release();
}
});
});
Expand Down
21 changes: 17 additions & 4 deletions webrtc-jni/src/main/cpp/src/JNI_VideoDeviceSource.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@
#include "JavaString.h"
#include "JavaUtils.h"

#include <thread>

JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoDeviceSource_setVideoCaptureDevice
(JNIEnv * env, jobject caller, jobject device)
{
Expand Down Expand Up @@ -148,11 +150,22 @@ JNIEXPORT void JNICALL Java_dev_onvoid_webrtc_media_video_VideoDeviceSource_disp
videoSource->SetVideoProcessor(env, nullptr);
SetHandle<std::nullptr_t>(env, caller, "processorHostHandle", nullptr);

jni::ReleaseHandle(env, videoSource, [videoSource](bool) {
webrtc::RefCountReleaseStatus status = videoSource->Release();
jni::ReleaseHandle(env, videoSource, [videoSource](bool deferred) {
auto release = [videoSource]() {
webrtc::RefCountReleaseStatus status = videoSource->Release();

if (status != webrtc::RefCountReleaseStatus::kDroppedLastRef) {
RTC_LOG(LS_WARNING) << "Native object was not deleted. A reference is still around somewhere.";
}
};

if (status != webrtc::RefCountReleaseStatus::kDroppedLastRef) {
RTC_LOG(LS_WARNING) << "Native object was not deleted. A reference is still around somewhere.";
// The last call may be a processed frame on the capture thread,
// which the destructor of the source stops and cannot join itself.
if (deferred) {
std::thread(release).detach();
}
else {
release();
}
});
});
Expand Down
25 changes: 11 additions & 14 deletions webrtc-jni/src/main/cpp/src/media/video/VideoTrackDesktopSource.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@
#include "modules/desktop_capture/desktop_and_cursor_composer.h"
#include "modules/desktop_capture/mouse_cursor_monitor.h"

#include <algorithm>
#include <cmath>

namespace jni
{
VideoTrackDesktopSource::VideoTrackDesktopSource() :
Expand Down Expand Up @@ -207,20 +210,14 @@ namespace jni

if (conversionResult >= 0) {
if (!maxFrameSize.is_empty()) {
// Adapt frame size to contraints.
int max_width = maxFrameSize.width();
int max_height = maxFrameSize.height();

if (adapted_width > max_width) {
double scale = max_width / (double)adapted_width;
adapted_width = max_width;
adapted_height = (int)(adapted_height * scale);
}
else if (adapted_height > max_height) {
double scale = max_height / (double)adapted_height;
adapted_width = (int)(adapted_width * scale);
adapted_height = max_height;
}
// One factor for both limits: the frame fits both and keeps its
// aspect ratio. A very narrow limit must not round a side to 0.
const double scale = std::min({ 1.0,
maxFrameSize.width() / static_cast<double>(adapted_width),
maxFrameSize.height() / static_cast<double>(adapted_height) });

adapted_width = std::max(1, static_cast<int>(std::lround(adapted_width * scale)));
adapted_height = std::max(1, static_cast<int>(std::lround(adapted_height * scale)));
}

if (adapted_width != width || adapted_height != height) {
Expand Down
12 changes: 8 additions & 4 deletions webrtc/src/main/java/dev/onvoid/webrtc/client/ScreenOptions.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import static java.util.Objects.requireNonNull;

import dev.onvoid.webrtc.media.video.VideoDesktopSource;
import dev.onvoid.webrtc.media.video.desktop.DesktopSource;

/**
Expand Down Expand Up @@ -87,21 +88,24 @@ private Builder(DesktopSource source, boolean window) {
}

/**
* @param frameRate the frames per second to capture.
* @param frameRate the frames per second to capture, 1 to {@value
* VideoDesktopSource#MAX_FRAME_RATE}.
*
* @return this builder.
*/
public Builder frameRate(int frameRate) {
if (frameRate <= 0) {
throw new IllegalArgumentException("The frame rate must be positive, got " + frameRate);
if (frameRate < 1 || frameRate > VideoDesktopSource.MAX_FRAME_RATE) {
throw new IllegalArgumentException("The frame rate must be between 1 and "
+ VideoDesktopSource.MAX_FRAME_RATE + ", got " + frameRate);
}

this.frameRate = frameRate;
return this;
}

/**
* Scales captured frames down to fit, keeping their aspect ratio.
* Scales captured frames down to fit both limits, keeping their aspect
* ratio.
*
* @param width the largest width, in pixels.
* @param height the largest height, in pixels.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,17 @@
* The sink a {@link VideoProcessor} delivers processed frames to. It passes
* them on to its source until it is detached, when the processor is replaced
* or the source is disposed, and drops them afterwards.
* <p>
* A delivery holds no lock: a callback further down may call into the source
* while another thread, holding the monitor of the source, detaches this sink.
* The native call keeps the native source alive by itself and drops the frame
* of a disposed source. So {@link #detach()} does not wait for a delivery that
* is running, which may still reach the tracks, and every delivery that starts
* after it returned is dropped.
*/
final class ProcessedFrameSink implements VideoTrackSink {

private VideoTrackSource source;
private volatile VideoTrackSource source;


ProcessedFrameSink(VideoTrackSource source) {
Expand All @@ -36,16 +43,14 @@ public void onVideoFrame(VideoFrame frame) {
throw new NullPointerException("VideoFrame must not be null");
}

// Holding the lock while delivering keeps the source from being
// disposed during the native call.
synchronized (this) {
if (source != null) {
source.deliverProcessedFrame(frame);
}
VideoTrackSource target = source;

if (target != null) {
target.deliverProcessedFrame(frame);
}
}

synchronized void detach() {
void detach() {
source = null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,13 @@

public class VideoDesktopSource extends VideoTrackSource {

/**
* The highest frame rate. The capture thread paces itself in whole
* milliseconds, so anything higher would make it spin without a pause.
*/
public static final int MAX_FRAME_RATE = 1000;


public VideoDesktopSource() {
super();

Expand All @@ -26,8 +33,29 @@ public VideoDesktopSource() {

public native void setSourceId(long sourceId, boolean isWindow);

public native void setFrameRate(int frameRate);
/**
* Sets the frames per second to capture, read when the capture starts.
*
* @param frameRate The frame rate, 1 to {@value #MAX_FRAME_RATE}.
*
* @throws IllegalArgumentException If the frame rate is out of range.
*/
public void setFrameRate(int frameRate) {
if (frameRate < 1 || frameRate > MAX_FRAME_RATE) {
throw new IllegalArgumentException(
"The frame rate must be between 1 and " + MAX_FRAME_RATE + ", got " + frameRate);
}

setFrameRateInternal(frameRate);
}

/**
* Scales captured frames down to fit both limits, keeping their aspect
* ratio.
*
* @param width The largest width, in pixels.
* @param height The largest height, in pixels.
*/
public native void setMaxFrameSize(int width, int height);

public native void start();
Expand All @@ -41,6 +69,8 @@ public void dispose() {

private native void initialize();

private native void setFrameRateInternal(int frameRate);

private native void disposeInternal();

}
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ public interface VideoProcessor {
* Gives the processor the sink to deliver processed frames to. Called by
* {@link VideoTrackSource#setVideoProcessor} before the first frame
* arrives. The sink does nothing once the processor is replaced or the
* source is disposed.
* source is disposed. A frame being delivered at that moment may still
* reach the tracks, as neither waits for the sink.
*
* @param sink The sink that passes frames on to the source's tracks.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ protected VideoTrackSource() {
* they reach its tracks, replacing any processor set before. {@code null}
* removes the processor, so frames go to the tracks unchanged.
* <p>
* This does not wait for a frame the previous processor is delivering at
* that moment, which may still reach the tracks. What it delivers later
* is dropped.
* <p>
* Camera and desktop sources support a processor. A {@link
* CustomVideoSource} does not: process the frames before pushing them.
*
Expand All @@ -66,7 +70,8 @@ public synchronized void setVideoProcessor(VideoProcessor processor) {

setVideoProcessorNative(processor);

// Frames the previous processor delivers from now on are dropped.
// Frames the previous processor delivers from now on are dropped, a
// delivery already running may finish.
if (processorSink != null) {
processorSink.detach();
}
Expand All @@ -76,9 +81,10 @@ public synchronized void setVideoProcessor(VideoProcessor processor) {

/**
* Detaches the sink of the current processor, so that it drops frames
* delivered while and after this source is disposed. Called by the
* sources that support a processor before they dispose of their native
* source, which removes the processor.
* delivered from now on. A delivery already running either finishes
* before the native source is disposed or is dropped by the native call.
* Called by the sources that support a processor before they dispose of
* their native source, which removes the processor.
*/
synchronized void detachVideoProcessor() {
if (processorSink != null) {
Expand Down
12 changes: 12 additions & 0 deletions webrtc/src/test/java/dev/onvoid/webrtc/client/MediaTests.java
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
import dev.onvoid.webrtc.media.video.CustomVideoSource;
import dev.onvoid.webrtc.media.video.NativeI420Buffer;
import dev.onvoid.webrtc.media.video.VideoFrame;
import dev.onvoid.webrtc.media.video.desktop.DesktopSource;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
Expand Down Expand Up @@ -303,6 +304,17 @@ void fullQueueDropsOldest() throws Exception {
}
}

@Test
void screenFrameRateOutOfRangeRejected() {
ScreenOptions.Builder options = ScreenOptions.screen(new DesktopSource("screen", 0));

assertThrows(IllegalArgumentException.class, () -> options.frameRate(0));
assertThrows(IllegalArgumentException.class, () -> options.frameRate(1001));
assertThrows(IllegalArgumentException.class, () -> options.frameRate(65536));

assertEquals(1000, options.frameRate(1000).build().frameRate);
}

@Test
void queueLimitBelowChunkRejected() {
CustomAudio voice = rtc.media().customAudio("voice");
Expand Down
Loading
Loading