LocalParticipant.kt 29.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812
/*
 * Copyright 2023 LiveKit, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.livekit.android.room.participant

import android.Manifest
import android.content.Context
import android.content.Intent
import com.google.protobuf.ByteString
import dagger.assisted.Assisted
import dagger.assisted.AssistedFactory
import dagger.assisted.AssistedInject
import io.livekit.android.dagger.CapabilitiesGetter
import io.livekit.android.dagger.InjectionNames
import io.livekit.android.events.ParticipantEvent
import io.livekit.android.room.ConnectionState
import io.livekit.android.room.DefaultsManager
import io.livekit.android.room.RTCEngine
import io.livekit.android.room.track.*
import io.livekit.android.room.util.EncodingUtils
import io.livekit.android.util.LKLog
import io.livekit.android.webrtc.createStatsGetter
import kotlinx.coroutines.CoroutineDispatcher
import livekit.LivekitModels
import livekit.LivekitRtc
import org.webrtc.*
import org.webrtc.RtpCapabilities.CodecCapability
import javax.inject.Named
import kotlin.math.max

class LocalParticipant
@AssistedInject
internal constructor(
    @Assisted
    private val dynacast: Boolean,
    internal val engine: RTCEngine,
    private val peerConnectionFactory: PeerConnectionFactory,
    private val context: Context,
    private val eglBase: EglBase,
    private val screencastVideoTrackFactory: LocalScreencastVideoTrack.Factory,
    private val videoTrackFactory: LocalVideoTrack.Factory,
    private val defaultsManager: DefaultsManager,
    @Named(InjectionNames.DISPATCHER_DEFAULT)
    coroutineDispatcher: CoroutineDispatcher,
    @Named(InjectionNames.SENDER)
    private val capabilitiesGetter: CapabilitiesGetter,
) : Participant("", null, coroutineDispatcher) {

    var audioTrackCaptureDefaults: LocalAudioTrackOptions by defaultsManager::audioTrackCaptureDefaults
    var audioTrackPublishDefaults: AudioTrackPublishDefaults by defaultsManager::audioTrackPublishDefaults
    var videoTrackCaptureDefaults: LocalVideoTrackOptions by defaultsManager::videoTrackCaptureDefaults
    var videoTrackPublishDefaults: VideoTrackPublishDefaults by defaultsManager::videoTrackPublishDefaults

    var republishes: List<LocalTrackPublication>? = null
    private val localTrackPublications
        get() = tracks.values
            .mapNotNull { it as? LocalTrackPublication }
            .toList()

    /**
     * Creates an audio track, recording audio through the microphone with the given [options].
     *
     * @exception SecurityException will be thrown if [Manifest.permission.RECORD_AUDIO] permission is missing.
     */
    fun createAudioTrack(
        name: String = "",
        options: LocalAudioTrackOptions = audioTrackCaptureDefaults,
    ): LocalAudioTrack {
        return LocalAudioTrack.createTrack(context, peerConnectionFactory, options, name)
    }

    /**
     * Creates a video track, recording video through the supplied [capturer].
     *
     * This method will call [VideoCapturer.initialize] and handle the lifecycle of
     * [SurfaceTextureHelper].
     */
    fun createVideoTrack(
        name: String = "",
        capturer: VideoCapturer,
        options: LocalVideoTrackOptions = videoTrackCaptureDefaults.copy(),
        videoProcessor: VideoProcessor? = null,
    ): LocalVideoTrack {
        return LocalVideoTrack.createTrack(
            peerConnectionFactory = peerConnectionFactory,
            context = context,
            name = name,
            capturer = capturer,
            options = options,
            rootEglBase = eglBase,
            trackFactory = videoTrackFactory,
            videoProcessor = videoProcessor,
        )
    }

    /**
     * Creates a video track, recording video through the camera with the given [options].
     *
     * @exception SecurityException will be thrown if [Manifest.permission.CAMERA] permission is missing.
     */
    fun createVideoTrack(
        name: String = "",
        options: LocalVideoTrackOptions = videoTrackCaptureDefaults.copy(),
        videoProcessor: VideoProcessor? = null,
    ): LocalVideoTrack {
        return LocalVideoTrack.createTrack(
            peerConnectionFactory,
            context,
            name,
            options,
            eglBase,
            videoTrackFactory,
            videoProcessor = videoProcessor,
        )
    }

    /**
     * Creates a screencast video track.
     *
     * @param mediaProjectionPermissionResultData The resultData returned from launching
     * [MediaProjectionManager.createScreenCaptureIntent()](https://developer.android.com/reference/android/media/projection/MediaProjectionManager#createScreenCaptureIntent()).
     */
    fun createScreencastTrack(
        name: String = "",
        mediaProjectionPermissionResultData: Intent,
    ): LocalScreencastVideoTrack {
        return LocalScreencastVideoTrack.createTrack(
            mediaProjectionPermissionResultData,
            peerConnectionFactory,
            context,
            name,
            LocalVideoTrackOptions(isScreencast = true),
            eglBase,
            screencastVideoTrackFactory,
        )
    }

    override fun getTrackPublication(source: Track.Source): LocalTrackPublication? {
        return super.getTrackPublication(source) as? LocalTrackPublication
    }

    override fun getTrackPublicationByName(name: String): LocalTrackPublication? {
        return super.getTrackPublicationByName(name) as? LocalTrackPublication
    }

    suspend fun setCameraEnabled(enabled: Boolean) {
        setTrackEnabled(Track.Source.CAMERA, enabled)
    }

    suspend fun setMicrophoneEnabled(enabled: Boolean) {
        setTrackEnabled(Track.Source.MICROPHONE, enabled)
    }

    /**
     * @param mediaProjectionPermissionResultData The resultData returned from launching
     * [MediaProjectionManager.createScreenCaptureIntent()](https://developer.android.com/reference/android/media/projection/MediaProjectionManager#createScreenCaptureIntent()).
     * @throws IllegalArgumentException if attempting to enable screenshare without [mediaProjectionPermissionResultData]
     */
    suspend fun setScreenShareEnabled(
        enabled: Boolean,
        mediaProjectionPermissionResultData: Intent? = null,
    ) {
        setTrackEnabled(Track.Source.SCREEN_SHARE, enabled, mediaProjectionPermissionResultData)
    }

    private suspend fun setTrackEnabled(
        source: Track.Source,
        enabled: Boolean,
        mediaProjectionPermissionResultData: Intent? = null,

    ) {
        val pub = getTrackPublication(source)
        if (enabled) {
            if (pub != null) {
                pub.muted = false

                if (source == Track.Source.CAMERA && pub.track is LocalVideoTrack) {
                    (pub.track as? LocalVideoTrack)?.startCapture()
                }
            } else {
                when (source) {
                    Track.Source.CAMERA -> {
                        val track = createVideoTrack()
                        track.startCapture()
                        publishVideoTrack(track)
                    }

                    Track.Source.MICROPHONE -> {
                        val track = createAudioTrack()
                        publishAudioTrack(track)
                    }

                    Track.Source.SCREEN_SHARE -> {
                        if (mediaProjectionPermissionResultData == null) {
                            throw IllegalArgumentException("Media Projection permission result data is required to create a screen share track.")
                        }
                        val track =
                            createScreencastTrack(mediaProjectionPermissionResultData = mediaProjectionPermissionResultData)
                        publishVideoTrack(track)
                    }

                    else -> {
                        LKLog.w { "Attempting to enable an unknown source, ignoring." }
                    }
                }
            }
        } else {
            pub?.track?.let { track ->
                // screenshare cannot be muted, unpublish instead
                if (pub.source == Track.Source.SCREEN_SHARE) {
                    unpublishTrack(track)
                } else {
                    pub.muted = true

                    // Release camera session so other apps can use.
                    if (pub.source == Track.Source.CAMERA && track is LocalVideoTrack) {
                        track.stopCapture()
                    }
                }
            }
        }
    }

    suspend fun publishAudioTrack(
        track: LocalAudioTrack,
        options: AudioTrackPublishOptions = AudioTrackPublishOptions(
            null,
            audioTrackPublishDefaults,
        ),
        publishListener: PublishListener? = null,
    ) {
        val encodings = listOf(
            RtpParameters.Encoding(null, true, null).apply {
                if (options.audioBitrate != null && options.audioBitrate > 0) {
                    maxBitrateBps = options.audioBitrate
                }
            },
        )
        publishTrackImpl(
            track = track,
            options = options,
            requestConfig = {
                disableDtx = !options.dtx
                source = LivekitModels.TrackSource.MICROPHONE
            },
            encodings = encodings,
            publishListener = publishListener,
        )
    }

    suspend fun publishVideoTrack(
        track: LocalVideoTrack,
        options: VideoTrackPublishOptions = VideoTrackPublishOptions(null, videoTrackPublishDefaults),
        publishListener: PublishListener? = null,
    ) {
        val encodings = computeVideoEncodings(track.dimensions, options)
        val videoLayers =
            EncodingUtils.videoLayersFromEncodings(track.dimensions.width, track.dimensions.height, encodings)

        publishTrackImpl(
            track = track,
            options = options,
            requestConfig = {
                width = track.dimensions.width
                height = track.dimensions.height
                source = if (track.options.isScreencast) {
                    LivekitModels.TrackSource.SCREEN_SHARE
                } else {
                    LivekitModels.TrackSource.CAMERA
                }
                addAllLayers(videoLayers)
            },
            encodings = encodings,
            publishListener = publishListener,
        )
    }

    /**
     * @return true if the track publish was successful.
     */
    private suspend fun publishTrackImpl(
        track: Track,
        options: TrackPublishOptions,
        requestConfig: LivekitRtc.AddTrackRequest.Builder.() -> Unit,
        encodings: List<RtpParameters.Encoding> = emptyList(),
        publishListener: PublishListener? = null,
    ): Boolean {
        if (localTrackPublications.any { it.track == track }) {
            publishListener?.onPublishFailure(TrackException.PublishException("Track has already been published"))
            return false
        }

        val cid = track.rtcTrack.id()
        val builder = LivekitRtc.AddTrackRequest.newBuilder().apply {
            this.requestConfig()
        }
        val trackInfo = engine.addTrack(
            cid = cid,
            name = track.name,
            kind = track.kind.toProto(),
            builder = builder,
        )
        val transInit = RtpTransceiver.RtpTransceiverInit(
            RtpTransceiver.RtpTransceiverDirection.SEND_ONLY,
            listOf(this.sid),
            encodings,
        )
        val transceiver = engine.publisher.peerConnection.addTransceiver(track.rtcTrack, transInit)

        when (track) {
            is LocalVideoTrack -> track.transceiver = transceiver
            is LocalAudioTrack -> track.transceiver = transceiver
            else -> {
                throw IllegalArgumentException("Trying to publish a non local track of type ${track.javaClass}")
            }
        }

        if (transceiver == null) {
            publishListener?.onPublishFailure(TrackException.PublishException("null sender returned from peer connection"))
            return false
        }

        track.statsGetter = createStatsGetter(engine.publisher.peerConnection, transceiver.sender)

        if (options is VideoTrackPublishOptions && options.videoCodec != null) {
            val targetCodec = options.videoCodec.lowercase()
            val capabilities = capabilitiesGetter(MediaStreamTrack.MediaType.MEDIA_TYPE_VIDEO)
            LKLog.v { "capabilities:" }
            capabilities.codecs.forEach { codec ->
                LKLog.v { "codec: ${codec.name}, ${codec.kind}, ${codec.mimeType}, ${codec.parameters}, ${codec.preferredPayloadType}" }
            }

            val matched = mutableListOf<CodecCapability>()
            val partialMatched = mutableListOf<CodecCapability>()
            val unmatched = mutableListOf<CodecCapability>()

            for (codec in capabilities.codecs) {
                val mimeType = codec.mimeType.lowercase()
                if (mimeType == "audio/opus") {
                    matched.add(codec)
                    continue
                }

                if (mimeType != "video/$targetCodec") {
                    unmatched.add(codec)
                    continue
                }
                // for h264 codecs that have sdpFmtpLine available, use only if the
                // profile-level-id is 42e01f for cross-browser compatibility
                if (targetCodec == "h264") {
                    if (codec.parameters["profile-level-id"] == "42e01f") {
                        matched.add(codec)
                    } else {
                        partialMatched.add(codec)
                    }
                    continue
                } else {
                    matched.add(codec)
                }
            }
            transceiver.setCodecPreferences(matched.plus(partialMatched).plus(unmatched))
        }

        val publication = LocalTrackPublication(
            info = trackInfo,
            track = track,
            participant = this,
            options = options,
        )
        addTrackPublication(publication)

        publishListener?.onPublishSuccess(publication)
        internalListener?.onTrackPublished(publication, this)
        eventBus.postEvent(ParticipantEvent.LocalTrackPublished(this, publication), scope)

        return true
    }

    private fun computeVideoEncodings(
        dimensions: Track.Dimensions,
        options: VideoTrackPublishOptions,
    ): List<RtpParameters.Encoding> {
        val (width, height) = dimensions
        var encoding = options.videoEncoding
        val simulcast = options.simulcast

        if ((encoding == null && !simulcast) || width == 0 || height == 0) {
            return emptyList()
        }

        if (encoding == null) {
            encoding = EncodingUtils.determineAppropriateEncoding(width, height)
            LKLog.d { "using video encoding: $encoding" }
        }

        val encodings = mutableListOf<RtpParameters.Encoding>()
        if (simulcast) {
            val presets = EncodingUtils.presetsForResolution(width, height)
            val midPreset = presets[1]
            val lowPreset = presets[0]

            fun addEncoding(videoEncoding: VideoEncoding, scale: Double) {
                if (scale < 1.0) {
                    LKLog.w { "Discarding encoding with a scale < 1.0: $scale." }
                    return
                }
                if (encodings.size >= EncodingUtils.VIDEO_RIDS.size) {
                    throw IllegalStateException("Attempting to add more encodings than we have rids for!")
                }
                // encodings is mutable, so this will grab next available rid
                val rid = EncodingUtils.VIDEO_RIDS[encodings.size]
                encodings.add(videoEncoding.toRtpEncoding(rid, scale))
            }

            // if resolution is high enough, we send both h and q res.
            // otherwise only send h
            val size = max(width, height)

            fun calculateScaleDown(captureParam: VideoCaptureParameter): Double {
                val targetSize = max(captureParam.width, captureParam.height)
                return size / targetSize.toDouble()
            }
            if (size >= 960) {
                val lowScale = calculateScaleDown(lowPreset.capture)
                val midScale = calculateScaleDown(midPreset.capture)

                addEncoding(lowPreset.encoding, lowScale)
                addEncoding(midPreset.encoding, midScale)
            } else {
                val lowScale = calculateScaleDown(lowPreset.capture)
                addEncoding(lowPreset.encoding, lowScale)
            }
            addEncoding(encoding, 1.0)
        } else {
            encodings.add(encoding.toRtpEncoding())
        }

        // Make largest size at front. addTransceiver seems to fail if ordered from smallest to largest.
        encodings.reverse()
        return encodings
    }

    /**
     * Control who can subscribe to LocalParticipant's published tracks.
     *
     * By default, all participants can subscribe. This allows fine-grained control over
     * who is able to subscribe at a participant and track level.
     *
     * Note: if access is given at a track-level (i.e. both [allParticipantsAllowed] and
     * [ParticipantTrackPermission.allTracksAllowed] are false), any newer published tracks
     * will not grant permissions to any participants and will require a subsequent
     * permissions update to allow subscription.
     *
     * @param allParticipantsAllowed Allows all participants to subscribe all tracks.
     *  Takes precedence over [participantTrackPermissions] if set to true.
     *  By default this is set to true.
     * @param participantTrackPermissions Full list of individual permissions per
     *  participant/track. Any omitted participants will not receive any permissions.
     */
    fun setTrackSubscriptionPermissions(
        allParticipantsAllowed: Boolean,
        participantTrackPermissions: List<ParticipantTrackPermission> = emptyList(),
    ) {
        engine.updateSubscriptionPermissions(allParticipantsAllowed, participantTrackPermissions)
    }

    fun unpublishTrack(track: Track, stopOnUnpublish: Boolean = true) {
        val publication = localTrackPublications.firstOrNull { it.track == track }
        if (publication === null) {
            LKLog.d { "this track was never published." }
            return
        }

        val sid = publication.sid
        tracks = tracks.toMutableMap().apply { remove(sid) }

        if (engine.connectionState == ConnectionState.CONNECTED) {
            val senders = engine.publisher.peerConnection.senders
            for (sender in senders) {
                val t = sender.track() ?: continue
                if (t.id() == track.rtcTrack.id()) {
                    engine.publisher.peerConnection.removeTrack(sender)
                }
            }
        }
        if (stopOnUnpublish) {
            track.stop()
        }
        internalListener?.onTrackUnpublished(publication, this)
        eventBus.postEvent(ParticipantEvent.LocalTrackUnpublished(this, publication), scope)
    }

    /**
     * Publish a new data payload to the room. Data will be forwarded to each participant in the room.
     * Each payload must not exceed 15k in size
     *
     * @param data payload to send
     * @param reliability for delivery guarantee, use RELIABLE. for fastest delivery without guarantee, use LOSSY
     * @param destination list of participant SIDs to deliver the payload, null to deliver to everyone
     * @param topic the topic under which the message was published
     */
    @Suppress("unused")
    suspend fun publishData(
        data: ByteArray,
        reliability: DataPublishReliability = DataPublishReliability.RELIABLE,
        destination: List<String>? = null,
        topic: String? = null,
    ) {
        if (data.size > RTCEngine.MAX_DATA_PACKET_SIZE) {
            throw IllegalArgumentException("cannot publish data larger than " + RTCEngine.MAX_DATA_PACKET_SIZE)
        }

        val kind = when (reliability) {
            DataPublishReliability.RELIABLE -> LivekitModels.DataPacket.Kind.RELIABLE
            DataPublishReliability.LOSSY -> LivekitModels.DataPacket.Kind.LOSSY
        }
        val packetBuilder = LivekitModels.UserPacket.newBuilder().apply {
            payload = ByteString.copyFrom(data)
            participantSid = sid
            if (topic != null) {
                setTopic(topic)
            }
            if (destination != null) {
                addAllDestinationSids(destination)
            }
        }
        val dataPacket = LivekitModels.DataPacket.newBuilder()
            .setUser(packetBuilder)
            .setKind(kind)
            .build()

        engine.sendData(dataPacket)
    }

    override fun updateFromInfo(info: LivekitModels.ParticipantInfo) {
        super.updateFromInfo(info)

        // detect tracks that have mute status mismatched on server
        for (ti in info.tracksList) {
            val publication = this.tracks[ti.sid] as? LocalTrackPublication ?: continue
            val localMuted = publication.muted
            if (ti.muted != localMuted) {
                engine.updateMuteStatus(sid, localMuted)
            }
        }
    }

    /**
     * Updates the metadata of the local participant.  Changes will not be reflected until the
     * server responds confirming the update.
     * Note: this requires `CanUpdateOwnMetadata` permission encoded in the token.
     * @param metadata
     */
    fun updateMetadata(metadata: String) {
        this.engine.client.sendUpdateLocalMetadata(metadata, name)
    }

    /**
     * Updates the name of the local participant. Changes will not be reflected until the
     * server responds confirming the update.
     * Note: this requires `CanUpdateOwnMetadata` permission encoded in the token.
     * @param name
     */
    fun updateName(name: String) {
        this.engine.client.sendUpdateLocalMetadata(metadata, name)
    }

    internal fun onRemoteMuteChanged(trackSid: String, muted: Boolean) {
        val pub = tracks[trackSid]
        pub?.muted = muted
    }

    internal fun handleSubscribedQualityUpdate(subscribedQualityUpdate: LivekitRtc.SubscribedQualityUpdate) {
        if (!dynacast) {
            return
        }

        val trackSid = subscribedQualityUpdate.trackSid
        val qualities = subscribedQualityUpdate.subscribedQualitiesList
        val pub = tracks[trackSid] ?: return
        val track = pub.track as? LocalVideoTrack ?: return

        val sender = track.transceiver?.sender ?: return
        val parameters = sender.parameters ?: return
        val encodings = parameters.encodings ?: return

        var hasChanged = false
        for (quality in qualities) {
            val rid = EncodingUtils.ridForVideoQuality(quality.quality) ?: continue
            val encoding = encodings.firstOrNull { it.rid == rid }
                // use low quality layer settings for non-simulcasted streams
                ?: encodings.takeIf { it.size == 1 && quality.quality == LivekitModels.VideoQuality.LOW }?.first()
                ?: continue
            if (encoding.active != quality.enabled) {
                hasChanged = true
                encoding.active = quality.enabled
                LKLog.v { "setting layer ${quality.quality} to ${quality.enabled}" }
            }
        }

        if (hasChanged) {
            sender.parameters = parameters
        }
    }

    internal fun handleLocalTrackUnpublished(unpublishedResponse: LivekitRtc.TrackUnpublishedResponse) {
        val pub = tracks[unpublishedResponse.trackSid]
        val track = pub?.track
        if (track == null) {
            LKLog.w { "Received unpublished track response for unknown or non-published track: ${unpublishedResponse.trackSid}" }
            return
        }

        unpublishTrack(track)
    }

    fun prepareForFullReconnect() {
        val pubs = localTrackPublications.toList() // creates a copy, so is safe from the following removal.

        // Only set the first time we start a full reconnect.
        if (republishes == null) {
            republishes = pubs
        }

        tracks = tracks.toMutableMap().apply { clear() }

        for (publication in pubs) {
            internalListener?.onTrackUnpublished(publication, this)
            eventBus.postEvent(ParticipantEvent.LocalTrackUnpublished(this, publication), scope)
        }
    }

    suspend fun republishTracks() {
        val publish = republishes?.toList() ?: emptyList()
        republishes = null

        for (pub in publish) {
            val track = pub.track ?: continue
            unpublishTrack(track, false)
            // Cannot publish muted tracks.
            if (!pub.muted) {
                when (track) {
                    is LocalAudioTrack -> publishAudioTrack(track, pub.options as AudioTrackPublishOptions, null)
                    is LocalVideoTrack -> publishVideoTrack(track, pub.options as VideoTrackPublishOptions, null)
                    else -> throw IllegalStateException("LocalParticipant has a non local track publish?")
                }
            }
        }
    }

    fun cleanup() {
        for (pub in tracks.values) {
            val track = pub.track

            if (track != null) {
                track.stop()
                unpublishTrack(track)
                track.dispose()
            }
        }
    }

    override fun dispose() {
        cleanup()
        super.dispose()
    }

    interface PublishListener {
        fun onPublishSuccess(publication: TrackPublication) {}
        fun onPublishFailure(exception: Exception) {}
    }

    @AssistedFactory
    interface Factory {
        fun create(dynacast: Boolean): LocalParticipant
    }
}

internal fun LocalParticipant.publishTracksInfo(): List<LivekitRtc.TrackPublishedResponse> {
    return tracks.values.mapNotNull { trackPub ->
        val track = trackPub.track ?: return@mapNotNull null

        LivekitRtc.TrackPublishedResponse.newBuilder()
            .setCid(track.rtcTrack.id())
            .setTrack(trackPub.trackInfo)
            .build()
    }
}

interface TrackPublishOptions {
    val name: String?
}

abstract class BaseVideoTrackPublishOptions {
    abstract val videoEncoding: VideoEncoding?
    abstract val simulcast: Boolean

    /**
     * The video codec to use if available.
     */
    abstract val videoCodec: String?
}

data class VideoTrackPublishDefaults(
    override val videoEncoding: VideoEncoding? = null,
    override val simulcast: Boolean = true,
    override val videoCodec: String? = null,
) : BaseVideoTrackPublishOptions()

data class VideoTrackPublishOptions(
    override val name: String? = null,
    override val videoEncoding: VideoEncoding? = null,
    override val simulcast: Boolean = true,
    override val videoCodec: String? = null,
) : BaseVideoTrackPublishOptions(), TrackPublishOptions {
    constructor(
        name: String? = null,
        base: BaseVideoTrackPublishOptions,
    ) : this(
        name,
        base.videoEncoding,
        base.simulcast,
        base.videoCodec,
    )
}

abstract class BaseAudioTrackPublishOptions {
    abstract val audioBitrate: Int?
    abstract val dtx: Boolean
}

data class AudioTrackPublishDefaults(
    override val audioBitrate: Int? = 20_000,
    override val dtx: Boolean = true,
) : BaseAudioTrackPublishOptions()

data class AudioTrackPublishOptions(
    override val name: String? = null,
    override val audioBitrate: Int? = null,
    override val dtx: Boolean = true,
) : BaseAudioTrackPublishOptions(), TrackPublishOptions {
    constructor(
        name: String? = null,
        base: BaseAudioTrackPublishOptions,
    ) : this(
        name,
        base.audioBitrate,
        base.dtx,
    )
}

data class ParticipantTrackPermission(
    /**
     * The participant identity this permission applies to.
     * You can either provide this or `participantSid`
     */
    val participantIdentity: String? = null,
    /**
     * The participant id this permission applies to.
     */
    val participantSid: String? = null,
    /**
     * If set to true, the target participant can subscribe to all tracks from the local participant.
     *
     * Takes precedence over [allowedTrackSids].
     */
    val allTracksAllowed: Boolean = false,
    /**
     * The list of track ids that the target participant can subscribe to.
     */
    val allowedTrackSids: List<String> = emptyList(),
) {
    init {
        if (participantIdentity == null && participantSid == null) {
            throw IllegalArgumentException("Either identity or sid must be provided.")
        }
    }

    fun toProto(): LivekitRtc.TrackPermission {
        return LivekitRtc.TrackPermission.newBuilder()
            .setParticipantIdentity(participantIdentity)
            .setParticipantSid(participantSid)
            .setAllTracks(allTracksAllowed)
            .addAllTrackSids(allowedTrackSids)
            .build()
    }
}

sealed class PublishRecord() {
    data class AudioTrackPublishRecord(
        val track: LocalAudioTrack,
        val options: AudioTrackPublishOptions,
    )

    data class VideoTrackPublishRecord(
        val track: LocalVideoTrack,
        val options: VideoTrackPublishOptions,
    )
}