summaryrefslogtreecommitdiffstats
path: root/dom/media/webrtc/jsapi/RTCRtpReceiver.cpp
blob: 972b81adba5772a5bdd078199191c2260273a41e (plain)
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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "RTCRtpReceiver.h"
#include "transport/logging.h"
#include "mozilla/dom/MediaStreamTrack.h"
#include "mozilla/dom/Promise.h"
#include "transportbridge/MediaPipeline.h"
#include "nsPIDOMWindow.h"
#include "PrincipalHandle.h"
#include "nsIPrincipal.h"
#include "mozilla/dom/Document.h"
#include "mozilla/NullPrincipal.h"
#include "MediaTrackGraph.h"
#include "RemoteTrackSource.h"
#include "libwebrtcglue/RtpRtcpConfig.h"
#include "nsString.h"
#include "mozilla/dom/AudioStreamTrack.h"
#include "mozilla/dom/VideoStreamTrack.h"
#include "MediaTransportHandler.h"
#include "jsep/JsepTransceiver.h"
#include "mozilla/dom/RTCRtpReceiverBinding.h"
#include "mozilla/dom/RTCRtpSourcesBinding.h"
#include "RTCStatsReport.h"
#include "mozilla/Preferences.h"
#include "TransceiverImpl.h"
#include "libwebrtcglue/AudioConduit.h"

namespace mozilla::dom {

NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE(RTCRtpReceiver, mWindow, mTrack)
NS_IMPL_CYCLE_COLLECTING_ADDREF(RTCRtpReceiver)
NS_IMPL_CYCLE_COLLECTING_RELEASE(RTCRtpReceiver)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(RTCRtpReceiver)
  NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
  NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END

LazyLogModule gReceiverLog("RTCRtpReceiver");

static PrincipalHandle GetPrincipalHandle(nsPIDOMWindowInner* aWindow,
                                          bool aPrivacyNeeded) {
  // Set the principal used for creating the tracks. This makes the track
  // data (audio/video samples) accessible to the receiving page. We're
  // only certain that privacy hasn't been requested if we're connected.
  nsCOMPtr<nsIScriptObjectPrincipal> winPrincipal = do_QueryInterface(aWindow);
  RefPtr<nsIPrincipal> principal = winPrincipal->GetPrincipal();
  if (NS_WARN_IF(!principal)) {
    principal = NullPrincipal::CreateWithoutOriginAttributes();
  } else if (aPrivacyNeeded) {
    principal = NullPrincipal::CreateWithInheritedAttributes(principal);
  }
  return MakePrincipalHandle(principal);
}

static already_AddRefed<dom::MediaStreamTrack> CreateTrack(
    nsPIDOMWindowInner* aWindow, bool aAudio,
    const nsCOMPtr<nsIPrincipal>& aPrincipal) {
  MediaTrackGraph* graph = MediaTrackGraph::GetInstance(
      aAudio ? MediaTrackGraph::AUDIO_THREAD_DRIVER
             : MediaTrackGraph::SYSTEM_THREAD_DRIVER,
      aWindow, MediaTrackGraph::REQUEST_DEFAULT_SAMPLE_RATE,
      MediaTrackGraph::DEFAULT_OUTPUT_DEVICE);

  RefPtr<MediaStreamTrack> track;
  RefPtr<RemoteTrackSource> trackSource;
  if (aAudio) {
    RefPtr<SourceMediaTrack> source =
        graph->CreateSourceTrack(MediaSegment::AUDIO);
    trackSource = new RemoteTrackSource(source, aPrincipal, u"remote audio"_ns);
    track = new AudioStreamTrack(aWindow, source, trackSource);
  } else {
    RefPtr<SourceMediaTrack> source =
        graph->CreateSourceTrack(MediaSegment::VIDEO);
    trackSource = new RemoteTrackSource(source, aPrincipal, u"remote video"_ns);
    track = new VideoStreamTrack(aWindow, source, trackSource);
  }

  // Spec says remote tracks start out muted.
  trackSource->SetMuted(true);

  return track.forget();
}

RTCRtpReceiver::RTCRtpReceiver(nsPIDOMWindowInner* aWindow, bool aPrivacyNeeded,
                               const std::string& aPCHandle,
                               MediaTransportHandler* aTransportHandler,
                               JsepTransceiver* aJsepTransceiver,
                               nsISerialEventTarget* aMainThread,
                               nsISerialEventTarget* aStsThread,
                               MediaSessionConduit* aConduit,
                               TransceiverImpl* aTransceiverImpl)
    : mWindow(aWindow),
      mPCHandle(aPCHandle),
      mJsepTransceiver(aJsepTransceiver),
      mMainThread(aMainThread),
      mStsThread(aStsThread),
      mTransportHandler(aTransportHandler),
      mTransceiverImpl(aTransceiverImpl) {
  PrincipalHandle principalHandle = GetPrincipalHandle(aWindow, aPrivacyNeeded);
  mTrack = CreateTrack(aWindow, aConduit->type() == MediaSessionConduit::AUDIO,
                       principalHandle.get());
  // Until Bug 1232234 is fixed, we'll get extra RTCP BYES during renegotiation,
  // so we'll disable muting on RTCP BYE and timeout for now.
  if (Preferences::GetBool("media.peerconnection.mute_on_bye_or_timeout",
                           false)) {
    aConduit->SetRtcpEventObserver(this);
  }
  if (aConduit->type() == MediaSessionConduit::AUDIO) {
    mPipeline = new MediaPipelineReceiveAudio(
        mPCHandle, aTransportHandler, mMainThread.get(), mStsThread.get(),
        static_cast<AudioSessionConduit*>(aConduit), mTrack, principalHandle);
  } else {
    mPipeline = new MediaPipelineReceiveVideo(
        mPCHandle, aTransportHandler, mMainThread.get(), mStsThread.get(),
        static_cast<VideoSessionConduit*>(aConduit), mTrack, principalHandle);
  }
}

RTCRtpReceiver::~RTCRtpReceiver() { MOZ_ASSERT(!mPipeline); }

JSObject* RTCRtpReceiver::WrapObject(JSContext* aCx,
                                     JS::Handle<JSObject*> aGivenProto) {
  return RTCRtpReceiver_Binding::Wrap(aCx, this, aGivenProto);
}

RTCDtlsTransport* RTCRtpReceiver::GetTransport() const {
  if (!mTransceiverImpl) {
    return nullptr;
  }
  return mTransceiverImpl->GetDtlsTransport();
}

already_AddRefed<Promise> RTCRtpReceiver::GetStats() {
  nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(mWindow);
  ErrorResult rv;
  RefPtr<Promise> promise = Promise::Create(global, rv);
  if (NS_WARN_IF(rv.Failed())) {
    rv.StealNSResult();
    return nullptr;
  }

  // Two promises; one for RTP/RTCP stats, another for ICE stats.
  auto promises = GetStatsInternal();
  RTCStatsPromise::All(mMainThread, promises)
      ->Then(
          mMainThread, __func__,
          [promise, window = mWindow](
              const nsTArray<UniquePtr<RTCStatsCollection>>& aStats) {
            RefPtr<RTCStatsReport> report(new RTCStatsReport(window));
            for (const auto& stats : aStats) {
              report->Incorporate(*stats);
            }
            promise->MaybeResolve(std::move(report));
          },
          [promise](nsresult aError) {
            promise->MaybeReject(NS_ERROR_FAILURE);
          });

  return promise.forget();
}

static UniquePtr<dom::RTCStatsCollection> GetReceiverStats_s(
    const RefPtr<MediaPipelineReceive>& aPipeline,
    const nsString& aRecvTrackId) {
  UniquePtr<dom::RTCStatsCollection> report(new dom::RTCStatsCollection);
  auto asVideo = aPipeline->Conduit()->AsVideoSessionConduit();

  nsString kind = asVideo.isNothing() ? u"audio"_ns : u"video"_ns;
  nsString idstr = kind + u"_"_ns;
  idstr.AppendInt(static_cast<uint32_t>(aPipeline->Level()));

  // Add bandwidth estimation stats
  aPipeline->Conduit()->GetBandwidthEstimation().apply([&](auto& bw) {
    bw.mTrackIdentifier = aRecvTrackId;
    if (!report->mBandwidthEstimations.AppendElement(bw, fallible)) {
      mozalloc_handle_oom(0);
    }
  });

  Maybe<uint32_t> ssrc;
  unsigned int ssrcval;
  if (aPipeline->Conduit()->GetRemoteSSRC(&ssrcval)) {
    ssrc = Some(ssrcval);
  }

  // Add frame history
  asVideo.apply([&](const auto& conduit) {
    if (conduit->AddFrameHistory(&report->mVideoFrameHistories)) {
      auto& history = report->mVideoFrameHistories.LastElement();
      history.mTrackIdentifier = aRecvTrackId;
    }
  });

  // TODO(@@NG):ssrcs handle Conduits having multiple stats at the same level
  // This is pending spec work
  // Gather pipeline stats.
  nsString localId = u"inbound_rtp_"_ns + idstr;
  nsString remoteId;

  // First, fill in remote stat with rtcp sender data, if present.
  uint32_t packetsSent;
  uint64_t bytesSent;
  DOMHighResTimeStamp remoteTimestamp;
  Maybe<DOMHighResTimeStamp> timestamp =
      aPipeline->Conduit()->LastRtcpReceived();
  if (timestamp.isSome() && aPipeline->Conduit()->GetRTCPSenderReport(
                                &packetsSent, &bytesSent, &remoteTimestamp)) {
    RTCRemoteOutboundRtpStreamStats s;
    remoteId = u"inbound_rtcp_"_ns + idstr;
    s.mTimestamp.Construct(*timestamp);
    s.mId.Construct(remoteId);
    s.mType.Construct(RTCStatsType::Remote_outbound_rtp);
    ssrc.apply([&s](uint32_t aSsrc) { s.mSsrc.Construct(aSsrc); });
    s.mMediaType.Construct(kind);  // mediaType is the old name for kind.
    s.mKind.Construct(kind);
    s.mLocalId.Construct(localId);
    s.mPacketsSent.Construct(packetsSent);
    s.mBytesSent.Construct(bytesSent);
    s.mRemoteTimestamp.Construct(remoteTimestamp);
    if (!report->mRemoteOutboundRtpStreamStats.AppendElement(s, fallible)) {
      mozalloc_handle_oom(0);
    }
  }

  // Then, fill in local side (with cross-link to remote only if present)
  RTCInboundRtpStreamStats s;
  // TODO(bug 1496533): Should we use the time of the most-recently received
  // RTP packet? If so, what do we use if we haven't received any RTP? Now?
  s.mTimestamp.Construct(aPipeline->GetNow());
  s.mId.Construct(localId);
  s.mType.Construct(RTCStatsType::Inbound_rtp);
  ssrc.apply([&s](uint32_t aSsrc) { s.mSsrc.Construct(aSsrc); });
  s.mMediaType.Construct(kind);  // mediaType is the old name for kind.
  s.mKind.Construct(kind);
  unsigned int jitterMs, packetsLost;
  if (aPipeline->Conduit()->GetRTPReceiverStats(&jitterMs, &packetsLost)) {
    s.mJitter.Construct(double(jitterMs) / 1000);
    s.mPacketsLost.Construct(packetsLost);
  }
  if (remoteId.Length()) {
    s.mRemoteId.Construct(remoteId);
  }
  s.mPacketsReceived.Construct(aPipeline->RtpPacketsReceived());
  s.mBytesReceived.Construct(aPipeline->RtpBytesReceived());

  // Fill in packet type statistics
  webrtc::RtcpPacketTypeCounter counters;
  if (aPipeline->Conduit()->GetRecvPacketTypeStats(&counters)) {
    s.mNackCount.Construct(counters.nack_packets);
    // Fill in video only packet type stats
    if (asVideo) {
      s.mFirCount.Construct(counters.fir_packets);
      s.mPliCount.Construct(counters.pli_packets);
    }
  }
  // Lastly, fill in video decoder stats if this is video
  asVideo.apply([&s](auto conduit) {
    double framerateMean;
    double framerateStdDev;
    double bitrateMean;
    double bitrateStdDev;
    uint32_t discardedPackets;
    uint32_t framesDecoded;
    if (conduit->GetVideoDecoderStats(&framerateMean, &framerateStdDev,
                                      &bitrateMean, &bitrateStdDev,
                                      &discardedPackets, &framesDecoded)) {
      s.mFramerateMean.Construct(framerateMean);
      s.mFramerateStdDev.Construct(framerateStdDev);
      s.mBitrateMean.Construct(bitrateMean);
      s.mBitrateStdDev.Construct(bitrateStdDev);
      s.mDiscardedPackets.Construct(discardedPackets);
      s.mFramesDecoded.Construct(framesDecoded);
    }
  });
  if (!report->mInboundRtpStreamStats.AppendElement(s, fallible)) {
    mozalloc_handle_oom(0);
  }

  // Fill in Contributing Source statistics
  aPipeline->GetContributingSourceStats(localId,
                                        report->mRtpContributingSourceStats);

  return report;
}

nsTArray<RefPtr<RTCStatsPromise>> RTCRtpReceiver::GetStatsInternal() {
  nsTArray<RefPtr<RTCStatsPromise>> promises;
  if (mPipeline && mHaveStartedReceiving) {
    nsString recvTrackId;
    MOZ_ASSERT(mTrack);
    if (mTrack) {
      mTrack->GetId(recvTrackId);
    }
    promises.AppendElement(InvokeAsync(
        mStsThread, __func__, [pipeline = mPipeline, recvTrackId]() {
          return RTCStatsPromise::CreateAndResolve(
              GetReceiverStats_s(pipeline, recvTrackId), __func__);
        }));

    if (mJsepTransceiver->mTransport.mComponents) {
      promises.AppendElement(mTransportHandler->GetIceStats(
          mJsepTransceiver->mTransport.mTransportId, mPipeline->GetNow()));
    }
  }
  return promises;
}

void RTCRtpReceiver::GetContributingSources(
    nsTArray<RTCRtpContributingSource>& aSources) {
  // Duplicate code...
  if (mPipeline && mPipeline->Conduit()) {
    RefPtr<AudioSessionConduit> conduit(
        static_cast<AudioSessionConduit*>(mPipeline->Conduit()));
    nsTArray<dom::RTCRtpSourceEntry> sources;
    conduit->GetRtpSources(sources);
    sources.RemoveElementsBy([](const dom::RTCRtpSourceEntry& aEntry) {
      return aEntry.mSourceType != dom::RTCRtpSourceEntryType::Contributing;
    });
    aSources.ReplaceElementsAt(0, aSources.Length(), sources.Elements(),
                               sources.Length());
  }
}

void RTCRtpReceiver::GetSynchronizationSources(
    nsTArray<dom::RTCRtpSynchronizationSource>& aSources) {
  // Duplicate code...
  if (mPipeline && mPipeline->Conduit()) {
    RefPtr<AudioSessionConduit> conduit(
        static_cast<AudioSessionConduit*>(mPipeline->Conduit()));
    nsTArray<dom::RTCRtpSourceEntry> sources;
    conduit->GetRtpSources(sources);
    sources.RemoveElementsBy([](const dom::RTCRtpSourceEntry& aEntry) {
      return aEntry.mSourceType != dom::RTCRtpSourceEntryType::Synchronization;
    });
    aSources.ReplaceElementsAt(0, aSources.Length(), sources.Elements(),
                               sources.Length());
  }
}

nsPIDOMWindowInner* RTCRtpReceiver::GetParentObject() const { return mWindow; }

void RTCRtpReceiver::Shutdown() {
  ASSERT_ON_THREAD(mMainThread);
  if (mPipeline) {
    mPipeline->Shutdown_m();
    mPipeline->Conduit()->SetRtcpEventObserver(nullptr);
    mPipeline = nullptr;
  }
  mTransceiverImpl = nullptr;
}

void RTCRtpReceiver::UpdateTransport() {
  ASSERT_ON_THREAD(mMainThread);
  if (!mHaveSetupTransport) {
    mPipeline->SetLevel(mJsepTransceiver->GetLevel());
    mHaveSetupTransport = true;
  }

  UniquePtr<MediaPipelineFilter> filter;

  auto const& details = mJsepTransceiver->mRecvTrack.GetNegotiatedDetails();
  if (mJsepTransceiver->HasBundleLevel() && details) {
    std::vector<webrtc::RtpExtension> extmaps;
    details->ForEachRTPHeaderExtension(
        [&extmaps](const SdpExtmapAttributeList::Extmap& extmap) {
          extmaps.emplace_back(extmap.extensionname, extmap.entry);
        });
    filter = MakeUnique<MediaPipelineFilter>(extmaps);

    // Add remote SSRCs so we can distinguish which RTP packets actually
    // belong to this pipeline (also RTCP sender reports).
    for (uint32_t ssrc : mJsepTransceiver->mRecvTrack.GetSsrcs()) {
      filter->AddRemoteSSRC(ssrc);
    }
    for (uint32_t ssrc : mJsepTransceiver->mRecvTrack.GetRtxSsrcs()) {
      filter->AddRemoteSSRC(ssrc);
    }
    auto mid = Maybe<std::string>();
    if (GetMid() != "") {
      mid = Some(GetMid());
    }
    filter->SetRemoteMediaStreamId(mid);

    // Add unique payload types as a last-ditch fallback
    auto uniquePts = mJsepTransceiver->mRecvTrack.GetNegotiatedDetails()
                         ->GetUniquePayloadTypes();
    for (unsigned char& uniquePt : uniquePts) {
      filter->AddUniquePT(uniquePt);
    }
  }

  mPipeline->UpdateTransport_m(mJsepTransceiver->mTransport.mTransportId,
                               std::move(filter));
}

nsresult RTCRtpReceiver::UpdateConduit() {
  if (mPipeline->Conduit()->type() == MediaSessionConduit::VIDEO) {
    return UpdateVideoConduit();
  }
  return UpdateAudioConduit();
}

nsresult RTCRtpReceiver::UpdateVideoConduit() {
  RefPtr<VideoSessionConduit> conduit =
      static_cast<VideoSessionConduit*>(mPipeline->Conduit());

  // NOTE(pkerr) - this is new behavior. Needed because the
  // CreateVideoReceiveStream method of the Call API will assert (in debug)
  // and fail if a value is not provided for the remote_ssrc that will be used
  // by the far-end sender.
  if (!mJsepTransceiver->mRecvTrack.GetSsrcs().empty()) {
    MOZ_LOG(gReceiverLog, LogLevel::Debug,
            ("%s[%s]: %s Setting remote SSRC %u", mPCHandle.c_str(),
             GetMid().c_str(), __FUNCTION__,
             mJsepTransceiver->mRecvTrack.GetSsrcs().front()));
    uint32_t rtxSsrc = mJsepTransceiver->mRecvTrack.GetRtxSsrcs().empty()
                           ? 0
                           : mJsepTransceiver->mRecvTrack.GetRtxSsrcs().front();
    conduit->SetRemoteSSRC(mJsepTransceiver->mRecvTrack.GetSsrcs().front(),
                           rtxSsrc);
  }

  // TODO (bug 1423041) once we pay attention to receiving MID's in RTP
  // packets (see bug 1405495) we could make this depending on the presence of
  // MID in the RTP packets instead of relying on the signaling.
  if (mJsepTransceiver->HasBundleLevel() &&
      (!mJsepTransceiver->mRecvTrack.GetNegotiatedDetails() ||
       !mJsepTransceiver->mRecvTrack.GetNegotiatedDetails()->GetExt(
           webrtc::RtpExtension::kMIdUri))) {
    mStsThread->Dispatch(
        NewRunnableMethod("VideoSessionConduit::DisableSsrcChanges", conduit,
                          &VideoSessionConduit::DisableSsrcChanges));
  }

  if (mJsepTransceiver->mRecvTrack.GetNegotiatedDetails() &&
      mJsepTransceiver->mRecvTrack.GetActive()) {
    const auto& details(*mJsepTransceiver->mRecvTrack.GetNegotiatedDetails());

    TransceiverImpl::UpdateConduitRtpExtmap(
        *conduit, details, MediaSessionConduitLocalDirection::kRecv);

    std::vector<UniquePtr<VideoCodecConfig>> configs;
    nsresult rv = TransceiverImpl::NegotiatedDetailsToVideoCodecConfigs(
        details, &configs);

    if (NS_FAILED(rv)) {
      MOZ_LOG(gReceiverLog, LogLevel::Error,
              ("%s[%s]: %s Failed to convert "
               "JsepCodecDescriptions to VideoCodecConfigs (recv).",
               mPCHandle.c_str(), GetMid().c_str(), __FUNCTION__));
      return rv;
    }

    auto error =
        conduit->ConfigureRecvMediaCodecs(configs, details.GetRtpRtcpConfig());

    if (error) {
      MOZ_LOG(gReceiverLog, LogLevel::Error,
              ("%s[%s]: %s "
               "ConfigureRecvMediaCodecs failed: %u",
               mPCHandle.c_str(), GetMid().c_str(), __FUNCTION__, error));
      return NS_ERROR_FAILURE;
    }
  }

  return NS_OK;
}

nsresult RTCRtpReceiver::UpdateAudioConduit() {
  RefPtr<AudioSessionConduit> conduit =
      static_cast<AudioSessionConduit*>(mPipeline->Conduit());

  if (!mJsepTransceiver->mRecvTrack.GetSsrcs().empty()) {
    MOZ_LOG(gReceiverLog, LogLevel::Debug,
            ("%s[%s]: %s Setting remote SSRC %u", mPCHandle.c_str(),
             GetMid().c_str(), __FUNCTION__,
             mJsepTransceiver->mRecvTrack.GetSsrcs().front()));
    uint32_t rtxSsrc = mJsepTransceiver->mRecvTrack.GetRtxSsrcs().empty()
                           ? 0
                           : mJsepTransceiver->mRecvTrack.GetRtxSsrcs().front();
    conduit->SetRemoteSSRC(mJsepTransceiver->mRecvTrack.GetSsrcs().front(),
                           rtxSsrc);
  }

  if (mJsepTransceiver->mRecvTrack.GetNegotiatedDetails() &&
      mJsepTransceiver->mRecvTrack.GetActive()) {
    const auto& details(*mJsepTransceiver->mRecvTrack.GetNegotiatedDetails());
    std::vector<UniquePtr<AudioCodecConfig>> configs;
    nsresult rv = TransceiverImpl::NegotiatedDetailsToAudioCodecConfigs(
        details, &configs);

    if (NS_FAILED(rv)) {
      MOZ_LOG(gReceiverLog, LogLevel::Error,
              ("%s[%s]: %s Failed to convert "
               "JsepCodecDescriptions to AudioCodecConfigs (recv).",
               mPCHandle.c_str(), GetMid().c_str(), __FUNCTION__));
      return rv;
    }

    // Ensure conduit knows about extensions prior to creating streams
    TransceiverImpl::UpdateConduitRtpExtmap(
        *conduit, details, MediaSessionConduitLocalDirection::kRecv);

    auto error = conduit->ConfigureRecvMediaCodecs(configs);

    if (error) {
      MOZ_LOG(gReceiverLog, LogLevel::Error,
              ("%s[%s]: %s "
               "ConfigureRecvMediaCodecs failed: %u",
               mPCHandle.c_str(), GetMid().c_str(), __FUNCTION__, error));
      return NS_ERROR_FAILURE;
    }
  }

  return NS_OK;
}

void RTCRtpReceiver::Stop() {
  if (mPipeline) {
    mPipeline->Stop();
  }
}

void RTCRtpReceiver::Start() {
  mPipeline->Start();
  mHaveStartedReceiving = true;
}

bool RTCRtpReceiver::HasTrack(const dom::MediaStreamTrack* aTrack) const {
  return !aTrack || (mTrack == aTrack);
}

void RTCRtpReceiver::UpdateStreams(StreamAssociationChanges* aChanges) {
  // We don't sort and use set_difference, because we need to report the
  // added/removed streams in the order that they appear in the SDP.
  std::set<std::string> newIds(
      mJsepTransceiver->mRecvTrack.GetStreamIds().begin(),
      mJsepTransceiver->mRecvTrack.GetStreamIds().end());
  MOZ_ASSERT(mJsepTransceiver->mRecvTrack.GetRemoteSetSendBit() ||
             newIds.empty());
  bool needsTrackEvent = false;
  for (const auto& id : mStreamIds) {
    if (!newIds.count(id)) {
      aChanges->mStreamAssociationsRemoved.push_back({mTrack, id});
    }
  }

  std::set<std::string> oldIds(mStreamIds.begin(), mStreamIds.end());
  for (const auto& id : mJsepTransceiver->mRecvTrack.GetStreamIds()) {
    if (!oldIds.count(id)) {
      needsTrackEvent = true;
      aChanges->mStreamAssociationsAdded.push_back({mTrack, id});
    }
  }

  mStreamIds = mJsepTransceiver->mRecvTrack.GetStreamIds();

  if (mRemoteSetSendBit != mJsepTransceiver->mRecvTrack.GetRemoteSetSendBit()) {
    mRemoteSetSendBit = mJsepTransceiver->mRecvTrack.GetRemoteSetSendBit();
    if (mRemoteSetSendBit) {
      needsTrackEvent = true;
    } else {
      aChanges->mTracksToMute.push_back(mTrack);
    }
  }

  if (needsTrackEvent) {
    aChanges->mTrackEvents.push_back({this, mStreamIds});
  }
}

void RTCRtpReceiver::MozAddRIDExtension(unsigned short aExtensionId) {
  if (mPipeline) {
    mPipeline->AddRIDExtension_m(aExtensionId);
  }
}

void RTCRtpReceiver::MozAddRIDFilter(const nsAString& aRid) {
  if (mPipeline) {
    mPipeline->AddRIDFilter_m(NS_ConvertUTF16toUTF8(aRid).get());
  }
}

// test-only: adds fake CSRCs and audio data
void RTCRtpReceiver::MozInsertAudioLevelForContributingSource(
    const uint32_t aSource, const DOMHighResTimeStamp aTimestamp,
    const uint32_t aRtpTimestamp, const bool aHasLevel, const uint8_t aLevel) {
  if (!mPipeline || mPipeline->IsVideo() || !mPipeline->Conduit()) {
    return;
  }
  WebrtcAudioConduit* audio_conduit =
      static_cast<WebrtcAudioConduit*>(mPipeline->Conduit());
  audio_conduit->InsertAudioLevelForContributingSource(
      aSource, aTimestamp, aRtpTimestamp, aHasLevel, aLevel);
}

void RTCRtpReceiver::OnRtcpBye() { SetReceiveTrackMuted(true); }

void RTCRtpReceiver::OnRtcpTimeout() { SetReceiveTrackMuted(true); }

void RTCRtpReceiver::SetReceiveTrackMuted(bool aMuted) {
  if (mTrack) {
    // This sets the muted state for mTrack and all its clones.
    static_cast<RemoteTrackSource&>(mTrack->GetSource()).SetMuted(aMuted);
  }
}

std::string RTCRtpReceiver::GetMid() const {
  if (mJsepTransceiver->IsAssociated()) {
    return mJsepTransceiver->GetMid();
  }
  return std::string();
}

}  // namespace mozilla::dom

#undef LOGTAG