publishVideoTrack method

Future<LocalTrackPublication<LocalVideoTrack>> publishVideoTrack(
  1. LocalVideoTrack track, {
  2. VideoPublishOptions? publishOptions,
})

Publish a LocalVideoTrack to the Room. For most cases, using setCameraEnabled would be simpler and recommended.

Implementation

Future<LocalTrackPublication<LocalVideoTrack>> publishVideoTrack(
  LocalVideoTrack track, {
  VideoPublishOptions? publishOptions,
}) async {
  if (videoTracks.any(
      (e) => e.track?.mediaStreamTrack.id == track.mediaStreamTrack.id)) {
    throw TrackPublishException('track already exists');
  }

  // Use defaultPublishOptions if options is null
  publishOptions =
      publishOptions ?? room.roomOptions?.defaultVideoPublishOptions;

  // use constraints passed to getUserMedia by default
  VideoDimensions dimensions = track.currentOptions.params.dimensions;

  if (kIsWeb) {
    // getSettings() is only implemented for Web
    try {
      // try to use getSettings for more accurate resolution
      final settings = track.mediaStreamTrack.getSettings();
      if (settings['width'] is int) {
        dimensions = dimensions.copyWith(width: settings['width'] as int);
      }
      if (settings['height'] is int) {
        dimensions = dimensions.copyWith(height: settings['height'] as int);
      }
    } catch (_) {
      logger.warning('Failed to call `mediaStreamTrack.getSettings()`');
    }
  }

  logger.fine(
      'Compute encodings with resolution: ${dimensions}, options: ${publishOptions}');

  // Video encodings and simulcasts
  final encodings = Utils.computeVideoEncodings(
    isScreenShare: track.source == TrackSource.screenShareVideo,
    dimensions: dimensions,
    options: publishOptions,
  );

  logger.fine('Using encodings: ${encodings?.map((e) => e.toMap())}');

  final layers = Utils.computeVideoLayers(dimensions, encodings);

  logger.fine('Video layers: ${layers.map((e) => e)}');

  final trackInfo = await room.engine.addTrack(
    cid: track.getCid(),
    name: track.name,
    kind: track.kind,
    source: track.source.toPBType(),
    dimensions: dimensions,
    videoLayers: layers,
  );

  logger.fine('publishVideoTrack addTrack response: ${trackInfo}');

  await track.start();

  final transceiverInit = rtc.RTCRtpTransceiverInit(
    direction: rtc.TransceiverDirection.SendOnly,
    sendEncodings: encodings,
    streams: [track.mediaStream],
  );

  logger.fine('publishVideoTrack publisher: ${room.engine.publisher}');

  track.transceiver = await room.engine.publisher?.pc.addTransceiver(
    track: track.mediaStreamTrack,
    kind: rtc.RTCRtpMediaType.RTCRtpMediaTypeVideo,
    init: transceiverInit,
  );

  await room.engine.negotiate();

  final pub = LocalTrackPublication<LocalVideoTrack>(
    participant: this,
    info: trackInfo,
    track: track,
  );
  addTrackPublication(pub);

  [events, room.events].emit(LocalTrackPublishedEvent(
    participant: this,
    publication: pub,
  ));

  return pub;
}