how do i know which track is which async def on_e...
# ask-ai
c
how do i know which track is which async def on_enter(self): room = get_job_context().room # Find the first video track (if any) from the remote participant remote_participant = list(room.remote_participants.values())[0] video_tracks = [ publication.track for publication in list(remote_participant.track_publications.values()) if publication.track and publication.track.kind == rtc.TrackKind.KIND_VIDEO ] logger.info(f"Found video tracks: {video_tracks}") if video_tracks: self._create_video_stream(video_tracks[0])
t
Thanks for reaching out, dexter. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'm glad you're exploring how to differentiate video tracks from remote participants in LiveKit using Python! Here are some friendly tips to help you along: • Using the
kind
Property:
The
kind
attribute of
RemoteTrackPublication
tells you whether a track is audio or video. For example:
Copy code
if publication.kind == rtc.TrackKind.VIDEO:
    print(f"Video track: {publication.sid}, name: {publication.name}")
• Iterating Over Track Publications: You can look through the
track_publications
dictionary of a remote participant and pick out the video tracks by checking the `kind`:
Copy code
for publication in participant.track_publications.values():
    if publication.kind == rtc.TrackKind.VIDEO:
        print(f"Found video track: {publication.name} (SID: {publication.sid})")
• Waiting for Specific Track Types: Another handy approach is to use utility functions like
wait_for_track_publication
that let you wait for a particular track type, such as video, to be published. These methods should make it easier for you to identify and work with video tracks in sessions with multiple participants. If you have any questions or need more help, feel free to ask—I’m here to support you! Sources: livekit-rtc/livekit/rtc/participant.py | livekit-agents/livekit/agents/utils/participant.py | Recording participants | LiveKit docs
c
trying to figure out which is the uesrs webcam and which is screenshare
t
I'm glad you're looking to differentiate between a user's webcam and screen share tracks in LiveKit using Python! A handy way to do this is by using the
source
property of the
TrackPublication
object. This property tells you exactly where the track is coming from, and it can have these values: • `SOURCE_CAMERA`: This means it's a webcam track. • `SOURCE_SCREENSHARE`: This indicates a screen share track. • `SOURCE_SCREENSHARE_AUDIO`: This points to screen share audio. Here's a simple example to help you check the source:
Copy code
if track_publication.source == proto_track.TrackSource.SOURCE_CAMERA:
    print("This is a webcam track")
elif track_publication.source == proto_track.TrackSource.SOURCE_SCREENSHARE:
    print("This is a screen share track")
elif track_publication.source == proto_track.TrackSource.SOURCE_SCREENSHARE_AUDIO:
    print("This is a screen share audio track")
This approach works smoothly for both local and remote track publications, so you can confidently identify where each track is coming from. If you have any more questions or need further clarification, feel free to ask—I'm here to help! Sources: livekit-rtc/livekit/rtc/_proto/ffi_pb2.pyi
c
Found video tracks: [rtc.RemoteVideoTrack(sid=TR_VCG8hVowZETZp8, name=), rtc.RemoteVideoTrack(sid=TR_VS745Wbxkv6asF, name=)] {"pid": 78027, "job_id": "AJ_WjBe3dBbJ272"} I see this async def on_enter(self): room = get_job_context().room # Find the first video track (if any) from the remote participant remote_participant = list(room.remote_participants.values())[0] logger.info(f"Remote participant found: {remote_participant}") video_tracks = [ publication.track for publication in list(remote_participant.track_publications.values()) if publication.track and publication.track.kind == rtc.TrackKind.KIND_VIDEO ] logger.info(f"Found video tracks: {video_tracks}") if video_tracks: self._create_video_stream(video_tracks[0]) # Watch for new video tracks not yet published @room.on("track_subscribed") def on_track_subscribed( track: rtc.Track, publication: rtc.RemoteTrackPublication, participant: rtc.RemoteParticipant, ): if track.kind == rtc.TrackKind.KIND_VIDEO: self._create_video_stream(track)
t
I'm glad you're looking into how to tell if a video track comes from a webcam or a screen share, even when the track name might be empty. A helpful way to do this is by using the
source
property of the
TrackPublication
object. This property tells you where the track originated and can have these values: • `SOURCE_CAMERA`: This means the track is from a webcam. • `SOURCE_SCREENSHARE`: This means the track is from a screen share. Here's a simple example to check the source:
Copy code
if publication.kind == rtc.TrackKind.KIND_VIDEO:
    if publication.source == rtc.TrackSource.SOURCE_CAMERA:
        print("This is a webcam track")
    elif publication.source == rtc.TrackSource.SOURCE_SCREENSHARE:
        print("This is a screen share track")
This approach is quite reliable because the
source
field is set by LiveKit at the protocol level, so it works whether or not the track name is present. I hope this helps you confidently identify your video tracks! Sources: livekit-protocol/src/livekit.rs | livekit-android-sdk/src/main/java/io/livekit/android/room/track/Track.kt | src/room/track/options.ts | Recording participants | LiveKit docs | livekit-rtc/livekit/rtc/track.py
c
Copy code
class Assistant(Agent):
    def __init__(self) -> None:
        self._latest_frame = None
        self._video_stream = None
        self._tasks = []
        super().__init__(instructions="You are a helpful voice AI assistant.")
    
    async def on_enter(self):
        room = get_job_context().room

        # Find the first video track (if any) from the remote participant
        remote_participant = list(room.remote_participants.values())[0]
        video_tracks = [publication.track for publication in list(remote_participant.track_publications.values()) if publication.track.kind == rtc.TrackKind.KIND_VIDEO]
        if video_tracks:
            self._create_video_stream(video_tracks[0])
        
        # Watch for new video tracks not yet published
        @room.on("track_subscribed")
        def on_track_subscribed(track: rtc.Track, publication: rtc.RemoteTrackPublication, participant: rtc.RemoteParticipant):
            if track.kind == rtc.TrackKind.KIND_VIDEO:
                self._create_video_stream(track)
                        
    async def on_user_turn_completed(self, turn_ctx: ChatContext, new_message: ChatMessage) -> None:
        # Add the latest video frame, if any, to the new message
        if self._latest_frame:
            new_message.content.append(ImageContent(image=self._latest_frame))
            self._latest_frame = None
    
    # Helper method to buffer the latest video frame from the user's track
    def _create_video_stream(self, track: rtc.Track):
        # Close any existing stream (we only want one at a time)
        if self._video_stream is not None:
            self._video_stream.close()

        # Create a new stream to receive frames    
        self._video_stream = rtc.VideoStream(track)
        async def read_stream():
            async for event in self._video_stream:
                # Store the latest frame for use later
                self._latest_frame = event.frame
        
        # Store the async task
        task = asyncio.create_task(read_stream())
        task.add_done_callback(lambda t: self._tasks.remove(t))
        self._tasks.append(task)
In your example, how would you handle two video streams? for example I want the ability to screenshot the webcam and or the screenshare
t
To help you manage multiple video streams, like your webcam and screen share, and also enable screenshot functionality for each, you can work with separate
VideoStream
instances for every track. Here’s a friendly way to approach this: • Track Subscription: You can use the
track_subscribed
event to detect and distinguish between different tracks. For example:
Copy code
@room.on("track_subscribed")
def on_track_subscribed(track: rtc.Track, publication: rtc.RemoteTrackPublication, participant: rtc.RemoteParticipant):
    if track.kind == rtc.TrackKind.KIND_VIDEO:
        if publication.source == rtc.TrackSource.SOURCE_CAMERA:
            self._create_video_stream(track, "webcam")
        elif publication.source == rtc.TrackSource.SOURCE_SCREENSHARE:
            self._create_video_stream(track, "screenshare")
• Managing Streams: It’s helpful to keep separate streams for your webcam and screen share by passing an identifier like "webcam" or "screenshare" to your
_create_video_stream
method. • Screenshot Functionality: To take screenshots, you can store the latest frame from each stream in different variables (such as
self._latest_webcam_frame
and
self._latest_screenshare_frame
) and then use those frames whenever you want to capture a screenshot. If you’d like, I’m here to walk you through more details or provide additional examples to make this even clearer. Just let me know! Sources: examples/room_example.py | Vision | LiveKit Docs