Commit a0058c20cb for ffmpeg
commit a0058c20cb5fe728cc6ce5d38991a0fd39ec62a6
Author: Jun Zhao <barryjzhao@tencent.com>
Date: Fri Dec 4 23:26:41 2026 +0800
avdevice/avfoundation: handle interrupted reads and device disconnects
Return EAGAIN on empty nonblocking reads and check the interrupt
callback while waiting for frames. Enable the Darwin timed-wait
declaration even with strict POSIX feature flags.
End capture when a selected device disconnects. Use any queued first
samples to configure their streams and keep them for packet delivery
before EOF. Honor disconnects and interrupts while waiting for initial
stream metadata.
Verified that one SIGINT exits with default fflags, +nobuffer, and
nobuffer against a synthetic AVFoundation input that stops sending frames.
Fixes #26556.
Signed-off-by: Jun Zhao <barryjzhao@tencent.com>
diff --git a/libavdevice/avfoundation.m b/libavdevice/avfoundation.m
index 7348edb085..ede28fa792 100644
--- a/libavdevice/avfoundation.m
+++ b/libavdevice/avfoundation.m
@@ -25,6 +25,10 @@
* @author Thilo Borgmann <thilo.borgmann@mail.de>
*/
+#ifndef _DARWIN_C_SOURCE
+#define _DARWIN_C_SOURCE 1
+#endif
+
#include "config.h"
#import <AVFoundation/AVFoundation.h>
@@ -96,17 +100,19 @@ static const struct AVFPixelFormatSpec avf_pixel_formats[] = {
{ AV_PIX_FMT_NONE, 0 }
};
+@class AVFDeviceObserver;
+
typedef struct
{
AVClass* class;
- int frames_captured;
- int audio_frames_captured;
pthread_mutex_t frame_lock;
pthread_cond_t frame_wait_cond;
int is_stopping;
+ int device_disconnected;
id avf_delegate;
id avf_audio_delegate;
+ AVFDeviceObserver *disconnect_observer;
AVRational framerate;
int width, height;
@@ -169,6 +175,67 @@ static void unlock_frames(AVFContext* ctx)
pthread_mutex_unlock(&ctx->frame_lock);
}
+@interface AVFDeviceObserver : NSObject
+{
+ AVFContext *_context;
+ id _observer;
+}
+
+- (id)initWithContext:(AVFContext *)context video:(AVCaptureDevice *)video
+ audio:(AVCaptureDevice *)audio;
+- (void)stopObserving;
+
+@end
+
+@implementation AVFDeviceObserver
+
+- (void)deviceDisconnected
+{
+ @synchronized (self) {
+ if (_context) {
+ lock_frames(_context);
+ _context->device_disconnected = 1;
+ unlock_frames(_context);
+ }
+ }
+}
+
+- (id)initWithContext:(AVFContext *)context video:(AVCaptureDevice *)video
+ audio:(AVCaptureDevice *)audio
+{
+ if (self = [super init]) {
+ NSString *video_id = [video uniqueID];
+ NSString *audio_id = [audio uniqueID];
+ _context = context;
+ _observer = [[[NSNotificationCenter defaultCenter]
+ addObserverForName:AVCaptureDeviceWasDisconnectedNotification
+ object:nil queue:nil usingBlock:^(NSNotification *notification) {
+ AVCaptureDevice *device = [notification object];
+ NSString *device_id = [device uniqueID];
+ if ([device_id isEqualToString:video_id] || [device_id isEqualToString:audio_id])
+ [self deviceDisconnected];
+ }] retain];
+
+ // The device may have disappeared before the observer was registered.
+ if ((video && ![video isConnected]) || (audio && ![audio isConnected]))
+ [self deviceDisconnected];
+ }
+ return self;
+}
+
+- (void)stopObserving
+{
+ // A notification already being delivered may outlive observer removal.
+ @synchronized (self) {
+ _context = NULL;
+ }
+ [[NSNotificationCenter defaultCenter] removeObserver:_observer];
+ [_observer release];
+ _observer = nil;
+}
+
+@end
+
/** FrameReceiver class - delegate for AVCaptureSession
*/
@interface AVFFrameReceiver : NSObject
@@ -253,11 +320,12 @@ static void unlock_frames(AVFContext* ctx)
{
lock_frames(_context);
- while ((_context->current_frame != nil) && !_context->is_stopping) {
+ while (_context->current_frame && !_context->is_stopping &&
+ !_context->device_disconnected) {
pthread_cond_wait(&_context->frame_wait_cond, &_context->frame_lock);
}
- if (_context->is_stopping) {
+ if (_context->is_stopping || _context->device_disconnected) {
unlock_frames(_context);
return;
}
@@ -265,8 +333,6 @@ static void unlock_frames(AVFContext* ctx)
_context->current_frame = (CMSampleBufferRef)CFRetain(videoFrame);
unlock_frames(_context);
-
- ++_context->frames_captured;
}
@end
@@ -302,11 +368,12 @@ static void unlock_frames(AVFContext* ctx)
{
lock_frames(_context);
- while ((_context->current_audio_frame != nil) && !_context->is_stopping) {
+ while (_context->current_audio_frame && !_context->is_stopping &&
+ !_context->device_disconnected) {
pthread_cond_wait(&_context->frame_wait_cond, &_context->frame_lock);
}
- if (_context->is_stopping) {
+ if (_context->is_stopping || _context->device_disconnected) {
unlock_frames(_context);
return;
}
@@ -314,14 +381,16 @@ static void unlock_frames(AVFContext* ctx)
_context->current_audio_frame = (CMSampleBufferRef)CFRetain(audioFrame);
unlock_frames(_context);
-
- ++_context->audio_frames_captured;
}
@end
static void destroy_context(AVFContext* ctx)
{
+ [ctx->disconnect_observer stopObserving];
+ [ctx->disconnect_observer release];
+ ctx->disconnect_observer = nil;
+
// Wake any capture callback blocked waiting for the consumer and make it
// bail out, so stopRunning() can drain the session without a deadlock.
lock_frames(ctx);
@@ -678,21 +747,45 @@ static int add_audio_device(AVFormatContext *s, AVCaptureDevice *audio_device)
return 0;
}
+static int wait_for_first_frame(AVFormatContext *s, const CMSampleBufferRef *frame)
+{
+ AVFContext *ctx = s->priv_data;
+ const AVIOInterruptCB *interrupt_cb = &s->interrupt_callback;
+
+ for (;;) {
+ int disconnected, have_frame;
+
+ lock_frames(ctx);
+ disconnected = ctx->device_disconnected;
+ have_frame = *frame != NULL;
+ pthread_mutex_unlock(&ctx->frame_lock);
+
+ if (have_frame)
+ return 0;
+ if (disconnected)
+ return AVERROR_EOF;
+ if (interrupt_cb->callback && interrupt_cb->callback(interrupt_cb->opaque))
+ return AVERROR_EXIT;
+ CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
+ }
+}
+
static int get_video_config(AVFormatContext *s)
{
AVFContext *ctx = (AVFContext*)s->priv_data;
CVImageBufferRef image_buffer;
CGSize image_buffer_size;
AVStream* stream = avformat_new_stream(s, NULL);
+ int ret;
if (!stream) {
- return 1;
+ return AVERROR(ENOMEM);
}
// Take stream info from the first frame.
- while (ctx->frames_captured < 1) {
- CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
- }
+ ret = wait_for_first_frame(s, &ctx->current_frame);
+ if (ret < 0)
+ return ret;
lock_frames(ctx);
@@ -716,8 +809,10 @@ static int get_video_config(AVFormatContext *s)
stream->codecpar->format = ctx->pixel_format;
}
- CFRelease(ctx->current_frame);
- ctx->current_frame = nil;
+ if (!ctx->device_disconnected) {
+ CFRelease(ctx->current_frame);
+ ctx->current_frame = nil;
+ }
unlock_frames(ctx);
@@ -729,15 +824,16 @@ static int get_audio_config(AVFormatContext *s)
AVFContext *ctx = (AVFContext*)s->priv_data;
CMFormatDescriptionRef format_desc;
AVStream* stream = avformat_new_stream(s, NULL);
+ int ret;
if (!stream) {
- return 1;
+ return AVERROR(ENOMEM);
}
// Take stream info from the first frame.
- while (ctx->audio_frames_captured < 1) {
- CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
- }
+ ret = wait_for_first_frame(s, &ctx->current_audio_frame);
+ if (ret < 0)
+ return ret;
lock_frames(ctx);
@@ -751,7 +847,7 @@ static int get_audio_config(AVFormatContext *s)
if (!basic_desc) {
unlock_frames(ctx);
av_log(s, AV_LOG_ERROR, "audio format not available\n");
- return 1;
+ return AVERROR(EIO);
}
stream->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
@@ -789,7 +885,7 @@ static int get_audio_config(AVFormatContext *s)
} else {
unlock_frames(ctx);
av_log(s, AV_LOG_ERROR, "audio format is not supported\n");
- return 1;
+ return AVERROR(EIO);
}
if (ctx->audio_non_interleaved) {
@@ -799,12 +895,14 @@ static int get_audio_config(AVFormatContext *s)
if (!ctx->audio_buffer) {
unlock_frames(ctx);
av_log(s, AV_LOG_ERROR, "error allocating audio buffer\n");
- return 1;
+ return AVERROR(ENOMEM);
}
}
- CFRelease(ctx->current_audio_frame);
- ctx->current_audio_frame = nil;
+ if (!ctx->device_disconnected) {
+ CFRelease(ctx->current_audio_frame);
+ ctx->current_audio_frame = nil;
+ }
unlock_frames(ctx);
@@ -1310,6 +1408,11 @@ static int avf_read_header(AVFormatContext *s)
if (audio_device && add_audio_device(s, audio_device)) {
}
+ if ((video_device && !ctx->video_is_screen) || audio_device)
+ ctx->disconnect_observer = [[AVFDeviceObserver alloc]
+ initWithContext:ctx video:ctx->video_is_screen ? nil : video_device
+ audio:audio_device];
+
[ctx->capture_session startRunning];
/* Unlock device configuration only after the session is started so it
@@ -1318,12 +1421,12 @@ static int avf_read_header(AVFormatContext *s)
[video_device unlockForConfiguration];
}
- if (video_device && get_video_config(s)) {
+ if (video_device && (ret = get_video_config(s)) < 0) {
goto fail;
}
// set audio stream
- if (audio_device && get_audio_config(s)) {
+ if (audio_device && (ret = get_audio_config(s)) < 0) {
goto fail;
}
@@ -1517,14 +1620,48 @@ static int avf_read_packet(AVFormatContext *s, AVPacket *pkt)
CFRelease(ctx->current_audio_frame);
ctx->current_audio_frame = nil;
} else {
+ const AVIOInterruptCB *interrupt_cb = &s->interrupt_callback;
+ int ret;
+
pkt->data = NULL;
- if (ctx->observed_quit) {
+ if (ctx->observed_quit || ctx->device_disconnected || ctx->is_stopping) {
unlock_frames(ctx);
return AVERROR_EOF;
}
- // No frame available yet: wait until a capture callback delivers
- // one (or until the device is being torn down).
- pthread_cond_wait(&ctx->frame_wait_cond, &ctx->frame_lock);
+
+ if (interrupt_cb->callback) {
+ // Do not hold the frame lock while calling application code.
+ pthread_mutex_unlock(&ctx->frame_lock);
+ ret = interrupt_cb->callback(interrupt_cb->opaque);
+ lock_frames(ctx);
+ if (ret) {
+ unlock_frames(ctx);
+ return AVERROR_EXIT;
+ }
+
+ // A frame or EOF may have arrived while the lock was released.
+ if (ctx->current_frame || ctx->current_audio_frame ||
+ ctx->observed_quit || ctx->device_disconnected || ctx->is_stopping)
+ continue;
+ }
+
+ if (s->flags & AVFMT_FLAG_NONBLOCK) {
+ unlock_frames(ctx);
+ return AVERROR(EAGAIN);
+ }
+
+ if (interrupt_cb->callback) {
+ // Check for cancellation even when the device stops sending frames.
+ const struct timespec timeout = { .tv_nsec = 100000000 };
+ ret = pthread_cond_timedwait_relative_np(&ctx->frame_wait_cond,
+ &ctx->frame_lock, &timeout);
+ } else {
+ ret = pthread_cond_wait(&ctx->frame_wait_cond, &ctx->frame_lock);
+ }
+ if (ret && ret != ETIMEDOUT) {
+ unlock_frames(ctx);
+ return AVERROR(ret);
+ }
}
} while (!pkt->data && !ctx->is_stopping);