Bind the broadcast Stop action to its registered publisher

This commit is contained in:
omar committed 2026-11-27 09:05:09 +03:00
1 parent 8004c01526
commit 039af3f3b7
6 files changed
+111 -18

No files matched your search

+2
View File
@@ -2,6 +2,8 @@
## Unreleased ## Unreleased
- Stop on an active broadcast tile now targets the registered stream and its publisher. Closing the capture no longer looks up a replacement publisher to stop after the wait.
- Active publications now have an Edit broadcast action for the title, video bitrate, viewer limit and admission policy. It edits the registered stream without selecting or restarting the capture source. - Active publications now have an Edit broadcast action for the title, video bitrate, viewer limit and admission policy. It edits the registered stream without selecting or restarting the capture source.
- A running publisher reports changed stream settings only after the server acknowledges the update. Tighter admission rules apply immediately; looser rules wait for acknowledgement. A late reply cannot replace the state of a disconnected publication. - A running publisher reports changed stream settings only after the server acknowledges the update. Tighter admission rules apply immediately; looser rules wait for acknowledgement. A late reply cannot replace the state of a disconnected publication.
+2
View File
@@ -2,6 +2,8 @@
## Current Windows account-free checkpoint (2026-11-26) ## Current Windows account-free checkpoint (2026-11-26)
**Stopping an active broadcast:** In the three-client Windows beta14 test, the publisher invoked Stop from the Slint tile for the registered stream while the admitted viewer was receiving video. The source rejected another frame, the publisher had no pending or admitted viewers, and the admitted viewer ended with no frame left to present. The refused viewer stayed declined. Fresh discovery from both viewers did not bring the stream back. This covers `command:stream_stop` for a generated source, not physical capture or an official client.
**Viewer admission and video on beta14:** In `approved_beta14_viewer_receives_generated_video` three muted native tabs connected to private beta14. From its Slint tile, the publisher admitted the first viewer to a closed publication. That viewer answered and decoded three red frames. The second viewer requested the same stream and received a refusal, sent no answer, and was not admitted. Only after the refusal did the source switch to green; the first viewer decoded three green frames without rejoining. Its departure emptied the publisher's viewer list. This covers Windows `command:stream_respond` with generated 64×48 video on the same host, not physical capture, audio delivery, or an official client. **Viewer admission and video on beta14:** In `approved_beta14_viewer_receives_generated_video` three muted native tabs connected to private beta14. From its Slint tile, the publisher admitted the first viewer to a closed publication. That viewer answered and decoded three red frames. The second viewer requested the same stream and received a refusal, sent no answer, and was not admitted. Only after the refusal did the source switch to green; the first viewer decoded three green frames without rejoining. Its departure emptied the publisher's viewer list. This covers Windows `command:stream_respond` with generated 64×48 video on the same host, not physical capture, audio delivery, or an official client.
**Viewer admission refusal on beta14:** In `duplex_qa --stream-lifecycle` the publisher received the observer's join request for its registered stream. The server acknowledged the negative response with an empty offer; the observer received the decline message for the same stream. A fresh targeted listing still returned the original publication, and its subsequent metadata update and stop were observed. Both disconnects were confirmed. No viewer was admitted and no media was sent in this run. **Viewer admission refusal on beta14:** In `duplex_qa --stream-lifecycle` the publisher received the observer's join request for its registered stream. The server acknowledged the negative response with an empty offer; the observer received the decline message for the same stream. A fresh targeted listing still returned the original publication, and its subsequent metadata update and stop were observed. Both disconnects were confirmed. No viewer was admitted and no media was sent in this run.
+2
View File
@@ -4,6 +4,8 @@
## Возврат к разработке на ПК, 2026-11-26 ## Возврат к разработке на ПК, 2026-11-26
Windows, база `8004c01`: закрыт `command:stream_stop`. На beta14 Stop из карточки Slint завершил выбранную публикацию во время передачи видео. Источник отклонил следующий кадр, просмотр завершился без оставшегося кадра, повторный поиск с обеих вкладок не обнаружил поток. Физический захват не использовался; стенд остановлен.
Windows, база `f7601e7`: закрыт `command:stream_respond`. На beta14 издатель разрешил просмотр первому зрителю и отказал второму. После отказа первый зритель получил три новых зелёных кадра без переподключения. Первоначальный запуск остановился на `ConnectFailedBanned` до проверки допуска; отдельный запуск с интервалом между подключениями прошёл на том же стенде без изменения серверных ограничений. Стенд остановлен. Windows, база `f7601e7`: закрыт `command:stream_respond`. На beta14 издатель разрешил просмотр первому зрителю и отказал второму. После отказа первый зритель получил три новых зелёных кадра без переподключения. Первоначальный запуск остановился на `ConnectFailedBanned` до проверки допуска; отдельный запуск с интервалом между подключениями прошёл на том же стенде без изменения серверных ограничений. Стенд остановлен.
Windows, база `402d8ff`: прошли два изолированных теста Slint на закрытом beta14. В `approved_beta14_viewer_receives_generated_video` зритель дождался допуска, издатель разрешил просмотр из карточки Slint, после ответа WebRTC зритель получил три красных кадра. Выход зрителя очистил список допущенных. Использован сгенерированный источник; звук, третья вкладка зрителя и официальный клиент не проверялись. Windows, база `402d8ff`: прошли два изолированных теста Slint на закрытом beta14. В `approved_beta14_viewer_receives_generated_video` зритель дождался допуска, издатель разрешил просмотр из карточки Slint, после ответа WebRTC зритель получил три красных кадра. Выход зрителя очистил список допущенных. Использован сгенерированный источник; звук, третья вкладка зрителя и официальный клиент не проверялись.
@@ -39,10 +39,39 @@ pub(super) async fn handle(ctx:Arc<RuntimeServices>,target:Target,operation:Oper
Operation::CapturePreview=>preview(ctx,target,values).await, Operation::CapturePreview=>preview(ctx,target,values).await,
Operation::CaptureStart=>start(ctx,target,values).await, Operation::CaptureStart=>start(ctx,target,values).await,
Operation::CaptureStop=>{ Operation::CaptureStop=>{
let flow=ctx.stream_workflows.lock().await.captures.remove(&session_id(&key)); let (flow,publisher)={
let mut state=ctx.stream_workflows.lock().await;
ctx.require_key(&key,true)?;
let publisher=match ctx.streams.publisher(&key){
Ok(publisher)=>publisher,
Err(error)if error.code=="target_changed"&&matches!(&target.entity,Entity::CaptureSource(_))=>None,
Err(error)=>return Err(stream_error(error)),
};
match &target.entity{
Entity::Stream{id,owner_uid}=>{
let publisher=publisher.as_ref().ok_or_else(changed)?;
let snapshot=publisher.snapshot();
if publisher.key!=key||id.is_empty()||snapshot.state!=PublisherState::Live||snapshot.stream_id.as_deref()!=Some(id.as_str()){
return Err(changed())
}
let connections=ctx.connected.connections.snapshot();
let connection=connections.get(&key.connection_id).filter(|connection|connection.key==key&&connection.is_connected()).ok_or_else(changed)?;
let uid=projection::own_roster_uid(connection,publisher.own_client_id).or_else(||connection.identity_id.as_deref()).filter(|uid|!uid.is_empty());
if uid!=Some(owner_uid.as_str()){return Err(changed())}
},
Entity::CaptureSource(_)=>{
// A preview or registration cancel cannot stop a registered publication.
if publisher.as_ref().is_some_and(|publisher|publisher.snapshot().state==PublisherState::Live){return Err(changed())}
},
_=>return Err(bad("Choose an active capture or publication")),
}
let flow=state.captures.remove(&session_id(&key));
if let Some(flow)=&flow{flow.active.store(false,Ordering::Release);}
(flow,publisher)
};
// Revoke OS capture before awaiting unregister acknowledgement. // Revoke OS capture before awaiting unregister acknowledgement.
if let Some(flow)=flow{blocking(move||{flow.close();Ok(())}).await?;} if let Some(flow)=flow{blocking(move||{flow.close();Ok(())}).await?;}
if let Some(publisher)=ctx.streams.publisher(&key).map_err(stream_error)?{publisher.stop("user_stop").await;} if let Some(publisher)=publisher{publisher.stop("user_stop").await;}
ctx.changed().await?;Ok(WorkflowResult::effect(UiEffect::StreamClose{target})) ctx.changed().await?;Ok(WorkflowResult::effect(UiEffect::StreamClose{target}))
}, },
_=>Err(bad("Invalid capture operation")), _=>Err(bad("Invalid capture operation")),
@@ -1,4 +1,5 @@
use super::*; use super::*;
use crate::app::connections::ConnectionSnapshot;
use crate::media::stream::publisher::PublisherSnapshot; use crate::media::stream::publisher::PublisherSnapshot;
pub(super) async fn project(ctx:&RuntimeServices)->Result<Vec<StreamPresentation>>{ pub(super) async fn project(ctx:&RuntimeServices)->Result<Vec<StreamPresentation>>{
@@ -52,17 +53,22 @@ pub(super) async fn project(ctx:&RuntimeServices)->Result<Vec<StreamPresentation
if let Some(publisher)=ctx.streams.publisher(key).map_err(stream_error)?{ if let Some(publisher)=ctx.streams.publisher(key).map_err(stream_error)?{
let snapshot=publisher.snapshot(); let snapshot=publisher.snapshot();
if matches!(snapshot.state,PublisherState::Starting|PublisherState::Live){ if matches!(snapshot.state,PublisherState::Starting|PublisherState::Live){
let target=Target{session:Some(key.clone()),entity:Entity::CaptureSource("capture-preview".into()),name:snapshot.options.name.clone(),own_channel_id:channel}; let preview=Target{session:Some(key.clone()),entity:Entity::CaptureSource("capture-preview".into()),name:snapshot.options.name.clone(),own_channel_id:channel};
let mut actions=vec![action(&target,Operation::CaptureStop,&catalog),action(&target,Operation::StreamStats,&catalog)]; let mut actions=Vec::new();
if snapshot.state==PublisherState::Live { let target=if snapshot.state==PublisherState::Live {
let owner=connection.server.as_deref().and_then(|server|server["clients"].as_array()) let roster_uid=own_roster_uid(connection,publisher.own_client_id);
.and_then(|clients|clients.iter().find(|client|client["id"].as_u64()==Some(u64::from(publisher.own_client_id)))) // The authenticated connection UID is available even if the roster omits self.
.and_then(|client|client["uid"].as_str()).filter(|uid|!uid.is_empty()); if let Some((id,uid))=snapshot.stream_id.as_ref().zip(roster_uid.or_else(||connection.identity_id.as_deref()).filter(|uid|!uid.is_empty())){
if let (Some(id),Some(uid))=(snapshot.stream_id.as_ref(),owner){ let publication=Target{entity:Entity::Stream{id:id.clone(),owner_uid:uid.to_owned()},..preview.clone()};
let edit=Target{entity:Entity::Stream{id:id.clone(),owner_uid:uid.to_owned()},..target.clone()}; if roster_uid.is_some(){actions.push(action(&publication,Operation::StreamEdit,&catalog));}
actions.insert(0,action(&edit,Operation::StreamEdit,&catalog)); actions.push(action(&publication,Operation::CaptureStop,&catalog));
} publication
} }else{preview.clone()}
}else{
actions.push(action(&preview,Operation::CaptureStop,&catalog));
preview.clone()
};
actions.push(action(&preview,Operation::StreamStats,&catalog));
for viewer in &snapshot.pending{let target=admission_target(&target,&snapshot,viewer);actions.push(action(&target,Operation::StreamAdmit,&catalog));actions.push(action(&target,Operation::StreamReject,&catalog));} for viewer in &snapshot.pending{let target=admission_target(&target,&snapshot,viewer);actions.push(action(&target,Operation::StreamAdmit,&catalog));actions.push(action(&target,Operation::StreamReject,&catalog));}
for viewer in &snapshot.viewers{actions.push(action(&admission_target(&target,&snapshot,viewer),Operation::StreamRemoveViewer,&catalog));} for viewer in &snapshot.viewers{actions.push(action(&admission_target(&target,&snapshot,viewer),Operation::StreamRemoveViewer,&catalog));}
result.push(StreamPresentation{id:tile_id(key,"capture-preview"),title:target.name.clone(),status:format!("{:?}; viewers={}; pending={}; {}",snapshot.state,snapshot.viewers.len(),snapshot.pending.len(),snapshot.detail),volume:0.0,actions,target}); result.push(StreamPresentation{id:tile_id(key,"capture-preview"),title:target.name.clone(),status:format!("{:?}; viewers={}; pending={}; {}",snapshot.state,snapshot.viewers.len(),snapshot.pending.len(),snapshot.detail),volume:0.0,actions,target});
@@ -84,6 +90,10 @@ pub(super) async fn project(ctx:&RuntimeServices)->Result<Vec<StreamPresentation
} }
Ok(result) Ok(result)
} }
pub(super) fn own_roster_uid(connection:&ConnectionSnapshot,client_id:u16)->Option<&str>{
connection.server.as_deref()?.get("clients")?.as_array()?.iter()
.find(|client|client["id"].as_u64()==Some(u64::from(client_id)))?["uid"].as_str().filter(|uid|!uid.is_empty())
}
fn admission_target(target:&Target,snapshot:&PublisherSnapshot,viewer:&crate::media::stream::publisher::PublisherViewer)->Target{Target{entity:Entity::StreamViewer{stream_id:snapshot.stream_id.clone().unwrap_or_default(),client_id:viewer.client_id,uid:viewer.identity.uid.clone()},name:viewer.identity.nickname.clone(),..target.clone()}} fn admission_target(target:&Target,snapshot:&PublisherSnapshot,viewer:&crate::media::stream::publisher::PublisherViewer)->Target{Target{entity:Entity::StreamViewer{stream_id:snapshot.stream_id.clone().unwrap_or_default(),client_id:viewer.client_id,uid:viewer.identity.uid.clone()},name:viewer.identity.nickname.clone(),..target.clone()}}
pub(super) fn admission_entries(target:&Target,snapshot:&PublisherSnapshot,catalog:&Catalog)->Vec<Entry>{ pub(super) fn admission_entries(target:&Target,snapshot:&PublisherSnapshot,catalog:&Catalog)->Vec<Entry>{
snapshot.pending.iter().chain(&snapshot.viewers).map(|viewer|{ snapshot.pending.iter().chain(&snapshot.viewers).map(|viewer|{
+53 -5
View File
@@ -98,7 +98,7 @@ fn run_publisher_fixture(check_admission:bool) {
until("observer discovers updated publisher metadata",||owner.streams.offers(&tabs[1],channel).is_ok_and(|offers|offers.iter().any(|offer|matches!(offer, until("observer discovers updated publisher metadata",||owner.streams.offers(&tabs[1],channel).is_ok_and(|offers|offers.iter().any(|offer|matches!(offer,
ChannelOffer::Stream{stream:info,..} if info.id==stream&&info.client_id==clients[0]&&info.name==renamed&&info.fields.get("bitrate").and_then(|v|v.as_str())==Some("2700")&&info.fields.get("viewer_limit").and_then(|v|v.as_str())==Some("4"))))).await?; ChannelOffer::Stream{stream:info,..} if info.id==stream&&info.client_id==clients[0]&&info.name==renamed&&info.fields.get("bitrate").and_then(|v|v.as_str())==Some("2700")&&info.fields.get("viewer_limit").and_then(|v|v.as_str())==Some("4"))))).await?;
if check_admission { if check_admission {
use crate::media::stream::{frames::VideoFrames,viewer::ViewerState}; use crate::{app::runtime::stream_actions::tile_id, media::stream::{frames::VideoFrames,publisher::PublisherState,viewer::ViewerState}};
use libwebrtc::video_frame::{I420Buffer,VideoFrame,VideoRotation}; use libwebrtc::video_frame::{I420Buffer,VideoFrame,VideoRotation};
let surface=Arc::new(std::sync::Mutex::new(None::<Arc<VideoFrames>>)); let surface=Arc::new(std::sync::Mutex::new(None::<Arc<VideoFrames>>));
let viewer={let output=surface.clone();let key=tabs[1].clone();let audio=owner.audio.clone();let hub=owner.streams.clone();let stream=stream.clone(); let viewer={let output=surface.clone();let key=tabs[1].clone();let audio=owner.audio.clone();let hub=owner.streams.clone();let stream=stream.clone();
@@ -149,11 +149,59 @@ fn run_publisher_fixture(check_admission:bool) {
}} }}
green>=3 green>=3
}).await?; }).await?;
viewer.stop().await; let capture_id=tile_id(&tabs[0],"capture-preview");
until("publisher releases the departing viewer",||publisher.snapshot().viewers.is_empty()).await?; let label=runtime.snapshot().catalog.text(forms::label_key(Operation::CaptureStop));
println!("beta14: publisher admitted the pending viewer; {red} red frames decoded; viewer left"); let stop=shell.get_streams().iter().find(|tile|tile.id.as_str()==capture_id)
.and_then(|tile|tile.actions.iter().find(|action|action.label==label.as_str()&&action.enabled))
.ok_or("missing Stop action on the live publication tile")?;
let frames=surface.lock().unwrap().clone().ok_or("no admitted viewer video surface")?;
assert_eq!(viewer.stream_id,stream);
let watching=viewer.snapshot();
assert!(!watching.state.terminal());
// Leave one more real frame in flight when the Slint action revokes the source.
green_frame.timestamp_us=start.elapsed().as_micros().max(1) as i64;
source.capture_video(&green_frame).unwrap();
shell.invoke_invoke(stop.id);
until("admitted viewer receives the server's stop",||viewer.snapshot().state.terminal()).await
.map_err(|e|format!("{e}: {:?}; {:?}",viewer.snapshot(),publisher.snapshot()))?;
let assert_stopped=||{
let publication=publisher.snapshot();
assert_eq!(publication.state,PublisherState::Stopped,"{publication:?}");
assert_eq!(publication.detail,"user_stop");
assert_eq!(publication.stream_id.as_deref(),Some(stream.as_str()));
assert!(publication.pending.is_empty()&&publication.viewers.is_empty(),"{publication:?}");
let admitted=viewer.snapshot();
assert_eq!(admitted.state,ViewerState::Ended,"{admitted:?}");
assert_eq!(admitted.detail,"stream_stopped");
assert_eq!(admitted.answers_sent,watching.answers_sent);
assert_eq!(admitted.offers_applied,watching.offers_applied);
let refused=rejected.snapshot();
assert_eq!(refused.state,ViewerState::Declined,"{refused:?}");
assert_eq!(refused.answers_sent,0);
assert!(surface.lock().unwrap().as_ref().is_some_and(|current|Arc::ptr_eq(current,&frames)));
assert!(frames.take_pixels(64,48).unwrap().is_none(),"a decoded frame survived the server stop");
};
assert_stopped();
green_frame.timestamp_us=start.elapsed().as_micros().max(1) as i64;
assert_eq!(source.capture_video(&green_frame).unwrap_err().code,"stream_closed");
let publication_gone=||!shell.get_streams().iter().any(|tile|tile.id.as_str()==capture_id)
&& tabs[1..].iter().all(|key|owner.streams.offers(key,channel).is_ok_and(|offers|
!offers.iter().any(|offer|matches!(offer,ChannelOffer::Stream{stream:info,..} if info.id==stream))));
until("the exact registered stream disappears for both viewers",publication_gone).await?;
// Give late network/media work a chance to run, including fresh server discovery.
for key in &tabs[1..]{owner.streams.probe(key,clients[0]).await.map_err(|e|e.to_string())?;}
let settled=std::time::Instant::now()+std::time::Duration::from_millis(300);
until("stopped publication stays closed after discovery",||{
assert_stopped();
assert!(publication_gone(),"stopped publication reappeared");
std::time::Instant::now()>=settled
}).await?;
println!("beta14: admitted viewer decoded {red} red and {green} green frames; Slint Stop ended stream {stream}");
}else{
publisher.stop("test complete").await;
} }
publisher.stop("test complete").await;
for key in &tabs{owner.request(key,Command::Disconnect{message:None}).await.map_err(|e|e.message)?;} for key in &tabs{owner.request(key,Command::Disconnect{message:None}).await.map_err(|e|e.message)?;}
until("all stream fixture tabs disconnected",||!runtime.snapshot().connections.any_active()).await until("all stream fixture tabs disconnected",||!runtime.snapshot().connections.any_active()).await
}).unwrap(); }).unwrap();