1 /* This Source Code Form is subject to the terms of the Mozilla Public
2  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
3  * You can obtain one at http://mozilla.org/MPL/2.0/. */
4 
5 #include "signaling/src/peerconnection/PacketDumper.h"
6 #include "signaling/src/peerconnection/PeerConnectionImpl.h"
7 #include "mozilla/media/MediaUtils.h"  // NewRunnableFrom
8 #include "nsThreadUtils.h"             // NS_DispatchToMainThread
9 
10 namespace mozilla {
11 
PacketDumper(PeerConnectionImpl * aPc)12 PacketDumper::PacketDumper(PeerConnectionImpl* aPc) : mPc(aPc) {}
13 
PacketDumper(const std::string & aPcHandle)14 PacketDumper::PacketDumper(const std::string& aPcHandle) {
15   if (!aPcHandle.empty()) {
16     PeerConnectionWrapper pcw(aPcHandle);
17     mPc = pcw.impl();
18   }
19 }
20 
~PacketDumper()21 PacketDumper::~PacketDumper() {
22   RefPtr<Runnable> pcDisposeRunnable = media::NewRunnableFrom(std::bind(
23       [](RefPtr<PeerConnectionImpl> pc) { return NS_OK; }, mPc.forget()));
24   NS_DispatchToMainThread(pcDisposeRunnable);
25 }
26 
Dump(size_t level,dom::mozPacketDumpType type,bool sending,const void * data,size_t size)27 void PacketDumper::Dump(size_t level, dom::mozPacketDumpType type, bool sending,
28                         const void* data, size_t size) {
29   // Optimization; avoids making a copy of the buffer, but we need to lock a
30   // mutex and check the flags. Could be optimized further, if we really want to
31   if (!mPc || !mPc->ShouldDumpPacket(level, type, sending)) {
32     return;
33   }
34 
35   RefPtr<PeerConnectionImpl> pc = mPc;
36 
37   UniquePtr<uint8_t[]> ownedPacket = MakeUnique<uint8_t[]>(size);
38   memcpy(ownedPacket.get(), data, size);
39 
40   RefPtr<Runnable> dumpRunnable = media::NewRunnableFrom(std::bind(
41       [pc, level, type, sending,
42        size](UniquePtr<uint8_t[]>& packet) -> nsresult {
43         pc->DumpPacket_m(level, type, sending, packet, size);
44         return NS_OK;
45       },
46       std::move(ownedPacket)));
47 
48   NS_DispatchToMainThread(dumpRunnable);
49 }
50 
51 }  // namespace mozilla
52